Beispiel #1
0
        /// <summary>
        /// 获取符合配置的MonitorServer
        /// </summary>
        /// <returns></returns>
        public MonitorServer GetMonitorServer(Model.Config config, ErrorPathInfo epi)
        {
            MonitorServer ms      = null;
            string        connstr = config.DB.ConnString;
            string        sql     = "select top 1 * from [monitorServer] where [deleteFlg]=0 and charindex([monitorDrive],@monitorDrive)>0";

            SqlParameter sp = new SqlParameter("@monitorDrive", epi.source);

            DataSet   ds = DBHelper.ExecuteDataset(connstr, CommandType.Text, sql, sp);
            DataTable dt = null;

            if (ds != null && ds.Tables.Count == 1)
            {
                dt = ds.Tables[0];
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                ms = new MonitorServer()
                {
                    //monitorServerName unique
                    monitorServerName = Convert.ToString(dr["monitorServerName"]),
                    monitorServerIP   = Convert.ToString(dr["monitorServerIP"]),
                    account           = Convert.ToString(dr["account"]),
                    password          = Convert.ToString(dr["password"]),
                    startFile         = Convert.ToString(dr["startFile"]),
                    monitorDrive      = Convert.ToString(dr["monitorDrive"]),
                    monitorMacPath    = Convert.ToString(dr["monitorMacPath"]),
                    monitorLocalPath  = Convert.ToString(dr["monitorLocalPath"]),
                };
            }
            return(ms);
        }
Beispiel #2
0
 /// <summary>
 /// init the monitor server modifification page
 /// </summary>
 private void FrmObject_Load(object sender, EventArgs e)
 {
     //get monitor server by record id
     if (!String.IsNullOrEmpty(id))
     {
         monitorServer               = ms.GetMonitorServerById(Convert.ToInt32(id));
         this.txtId.Text             = monitorServer.id.ToString();
         this.txtMonitorName.Text    = monitorServer.monitorServerName;
         this.txtMonitorIp.Text      = monitorServer.monitorServerIP;
         this.txtMonitorMemo.Text    = monitorServer.memo;
         this.txtMonitorAccount.Text = monitorServer.account;
         this.txtMonitorPass.Text    = monitorServer.password;
         this.txtMonitorStfile.Text  = monitorServer.startFile;
         this.txtLocalPath.Text      = monitorServer.monitorLocalPath;
         this.txtMacPath.Text        = monitorServer.monitorMacPath;
         //
         if (monitorServer.copyInit == 1)
         {
             this.checkBoxTopDirFile.Checked = true;
         }
         else
         {
             this.checkBoxTopDirFile.Checked = false;
         }
     }
     else
     {
         this.txtLocalPath.Text = CommonUtil.GetLocalCopyPath();
     }
 }
Beispiel #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="MonitorServer"></param>
        /// <param name="conn"></param>
        /// <returns></returns>
        public int UpdateMonitorFileListen(MonitorServer MonitorServer, MonitorServer MonitorServerForOld, OdbcConnection conn)
        {
            int    result = -1;
            string sql    = "UPDATE monitorFileListen SET monitorServerIP = ?,"
                            + " sharePoint = ?,"
                            + " monitorLocalPath = ?,"
                            + " updater = ?,"
                            + " updateDate = ?,"
                            + " synchronismFlg = 0"
                            + " WHERE monitorServerIP = ? and sharePoint = ?";

            OdbcParameter[] para = new OdbcParameter[] {
                new OdbcParameter("@monitorServerIP", MonitorServer.monitorServerIP),
                new OdbcParameter("@sharePoint", MonitorServer.startFile),
                new OdbcParameter("@monitorLocalPath", MonitorServer.monitorLocalPath),
                new OdbcParameter("@updater", MonitorServer.updater),
                new OdbcParameter("@updateDate", MonitorServer.updateDate),
                new OdbcParameter("@monitorServerIP2", MonitorServerForOld.monitorServerIP),
                new OdbcParameter("@sharePoint2", MonitorServerForOld.startFile),
            };
            try
            {
                result = db.Udaquery(sql, conn, para);
            }
            catch (Exception e)
            {
                throw e;
            }
            return(result);
        }
Beispiel #4
0
        /// <summary>
        /// 判断此路径是否发生变化
        /// 数据库中路径信息 暂定:有效性为一个月 即 每个月全部清空一次
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool IsUpdate(Model.Config config, SftpFile sf, MonitorServer ms)
        {
            //判断是否更新
            bool isUpdate = false;

            try
            {
                SSHPathInfo spi = new SSHPathInfo()
                {
                    MonitorServerIP = ms.monitorServerIP,
                    MacPath         = sf.FullName,
                    LastName        = sf.FullName.Substring(sf.FullName.LastIndexOf('/') + 1),
                    depth           = GetDepth(sf.FullName),
                    typeflag        = sf.IsDirectory ? 0 : 1,
                    updateTime      = (Int32)(sf.Attributes.LastWriteTime.Subtract(new DateTime(1970, 1, 1))).TotalSeconds
                };

                SSHPathInfoDAL spidal = new SSHPathInfoDAL();
                isUpdate = spidal.IsUpdate(config, spi);
            }
            catch (System.Exception ex)
            {
                isUpdate = true;
                BudSSH.Common.Util.LogManager.WriteLog(Common.Util.LogFile.Error, MessageUtil.GetExceptionMsg(ex, ""));
            }

            return(isUpdate);
        }
Beispiel #5
0
        /// <summary>
        /// 初期化の時 転送のファイルを取得する
        /// </summary>
        /// <param name="strMonitorServerID">転送元ID</param>
        /// <returns></returns>
        public ActionResult GetInitMonitorFolderDatail(string monistorId)
        {
            string strResult = string.Empty;

            try
            {
                //IList<MonitorServerFolder> folderList = msFolderService.GetMonitorServerFolderByMonitorServerID(monistorId);

                //IList<MonitorServerFolder> folderList = msFolderService.GetMonitorFolderByServerIDAndInitFlg(monistorId);
                //List<budbackup.Models.MonitFolder> initFolderList = new List<Models.MonitFolder>();
                //if (folderList.Count > 0)
                //{
                //    foreach (MonitorServerFolder folderModel in folderList)
                //    {
                //        budbackup.Models.MonitFolder model = new Models.MonitFolder();
                //        model.monitorFileName = folderModel.monitorFileName;
                //        model.monitorFilePath = folderModel.monitorFilePath;
                //        model.monitorFileType = folderModel.monitorFileType;
                //        initFolderList.Add(model);
                //    }
                //    strResult = JsonHelper.GetJson<List<budbackup.Models.MonitFolder>>(initFolderList);
                //}
                MonitorServer monitorServer = msService.GetMonitorServerById(int.Parse(monistorId));
                if (!System.IO.Directory.Exists(@"\\" + monitorServer.monitorServerIP + @"\" + monitorServer.startFile.TrimStart('\\').Replace('/', '\\')))
                {
                    int status = Common.NetworkConnection.Connect(@"\\" + monitorServer.monitorServerIP + @"\" + monitorServer.startFile.TrimStart('\\').Replace('/', '\\'), monitorServer.monitorDriveP, monitorServer.account, monitorServer.password);
                }

                List <budbackup.Models.MonitFolder> initFolderList = new List <Models.MonitFolder>();
                globalfolderList = msFolderService.GetMonitorFolderByServerIDAndInitFlg(monistorId);

                //format folder list——2014-06-11 wjd commented——Not filter
                //formatListsByFileTypeSet(monistorId);

                if (globalfolderList.Count > 0)
                {
                    foreach (MonitorServerFolder folderModel in globalfolderList)
                    {
                        budbackup.Models.MonitFolder model = new Models.MonitFolder();
                        model.monitorFileName = folderModel.monitorFileName;
                        model.monitorFilePath = folderModel.monitorFilePath;
                        model.monitorFileType = folderModel.monitorFileType;
                        initFolderList.Add(model);
                    }
                    strResult = JsonHelper.GetJson <List <budbackup.Models.MonitFolder> >(initFolderList);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            Response.Write(strResult);
            Response.End();
            return(null);
        }
Beispiel #6
0
 public int InsertMonitorServer(MonitorServer MonitorServer, SqlConnection conn)
 {
     try
     {
         return(db.insert(MonitorServer, "monitorServer", conn));
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Beispiel #7
0
        public ActionResult NetworkTest(MonitorServer model)
        {
            int    Result         = 0;
            string ipMessage      = model.monitorServerIP;
            string stfileMessage  = model.startFile;
            string monitorDriveP  = model.monitorDriveP;
            string accountMessage = model.account;
            string passMessage    = model.password;
            //string serverFolderPath = @"\\" + ipMessage + @"\" + stfileMessage.TrimStart('\\').Replace('/','\\');
            //2014-06-02 wjd modified
            string localPath = model.monitorLocalPath;  //monitorDriveP.IndexOf(':') <= -1 ? monitorDriveP + ":" : monitorDriveP;

            try
            {
                //Use cmd to test the link.
                string ip = @"\\" + ipMessage;
                Common.NetWorkFileShare1 netWorkFileShare = new Common.NetWorkFileShare1();
                if (netWorkFileShare.ConnectState(ip, accountMessage.Trim(), passMessage.Trim()))
                {
                    Result = 1;
                }
                else
                {
                    Result = -1;
                }

                //int status = Common.NetworkConnection.Connect(serverFolderPath, localPath, accountMessage, passMessage);
                //if (status == (int)Common.ERROR_ID.ERROR_SUCCESS)
                //{
                //    Result = 1;
                //}
                //else
                //{
                //    Result = -1;
                //}
                logger.Info("接続状態:" + Result.ToString());
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("1312") > -1)
                {
                    Result = 1;
                }
                else
                {
                    Result = -10;
                }
                logger.Error(ex.Message);
            }
            Response.Write(Result);
            Response.End();
            return(null);
        }
Beispiel #8
0
        public int UpdateMonitorServer(MonitorServer MonitorServer, MonitorServer MonitorServerForOld)
        {
            OdbcConnection conn;
            int            count = 0;

            using (conn = OdbcHelper.CreateConntion())
            {
                conn.Open();
                count = MonitorFileListenDal.UpdateMonitorFileListen(MonitorServer, MonitorServerForOld, conn);
                conn.Close();
            }
            return(count);
        }
Beispiel #9
0
        public int InsertMonitorServer(MonitorServer MonitorServer)
        {
            OdbcConnection conn;
            int            count = 0;

            using (conn = OdbcHelper.CreateConntion())
            {
                conn.Open();
                count = MonitorServerDal.InsertMonitorServer(MonitorServer, conn);
                conn.Close();
            }
            return(count);
        }
Beispiel #10
0
 private void CreateMonitorServer()
 {
     try
     {
         mMonitorServer        = new MonitorServer();
         mMonitorServer.Debug += MonitorServer_Debug;
         mMonitorServer.Start();
     }
     catch (Exception ex)
     {
         WriteLog(LogMode.Error, string.Format("CreateMonitorServer fail.\t{0}", ex.Message));
     }
 }
Beispiel #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="MonitorServer"></param>
        /// <param name="conn"></param>
        /// <returns></returns>
        public int UpdateMonitorServer(MonitorServer MonitorServer, OdbcConnection conn)
        {
            int    result = -1;
            string sql    = "UPDATE monitorServer SET monitorServerName = ?,"
                            + " monitorServerIP = ?,"
                            + " monitorSystem = ?,"
                            + " memo = ?, "
                            + " account = ?,"
                            + " password = ?,"
                            + " startFile = ?,"
                            + " monitorDrive = ?,"
                            + " monitorDriveP = ?,"
                            + " monitorMacPath = ?,"
                            + " monitorLocalPath = ?,"
                            + " copyInit = ?,"
                            + " updater = ?,"
                            + " updateDate = ?,"
                            + " synchronismFlg = 0"
                            + " WHERE id = ?";

            OdbcParameter[] para = new OdbcParameter[] {
                new OdbcParameter("@monitorServerName", MonitorServer.monitorServerName),
                new OdbcParameter("@monitorServerIP", MonitorServer.monitorServerIP),
                new OdbcParameter("@monitorSystem", MonitorServer.monitorSystem),
                new OdbcParameter("@memo", MonitorServer.memo),
                new OdbcParameter("@account", MonitorServer.account),
                new OdbcParameter("@password", MonitorServer.password),
                new OdbcParameter("@startFile", MonitorServer.startFile),
                new OdbcParameter("@monitorDrive", MonitorServer.monitorDrive),
                new OdbcParameter("@monitorDriveP", MonitorServer.monitorDriveP),
                new OdbcParameter("@monitorMacPath", MonitorServer.monitorMacPath),
                new OdbcParameter("@monitorLocalPath", MonitorServer.monitorLocalPath),
                new OdbcParameter("@copyInit", MonitorServer.copyInit),
                new OdbcParameter("@updater", MonitorServer.updater),
                new OdbcParameter("@updateDate", MonitorServer.updateDate),
                new OdbcParameter("@id", MonitorServer.id)
            };
            try
            {
                result = db.Udaquery(sql, conn, para);
            }
            catch (Exception e)
            {
                throw e;
            }
            return(result);
        }
Beispiel #12
0
 /// <summary>
 /// 転送先・編集ページ
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public ActionResult Edit(int id)
 {
     try
     {
         ViewData["bkserver"] = bkService.GetBackupServerById(id);
         ViewData["msList"]   = mService.GetMonitorServerList();
         ViewData["model"]    = groupSerivce.GetBackupServerGroupByBackupServerID(id);
     }
     catch (Exception ex)
     {
         ViewData["bkserver"] = new BackupServer();
         ViewData["msList"]   = new MonitorServer();
         ViewData["model"]    = new BackupServerGroup();
         logger.Error(ex.Message);
     }
     return(View());
 }
Beispiel #13
0
        public ActionResult Edit(int id)
        {
            MonitorServer initMonitor = new MonitorServer();
            string        startPath   = "";

            try
            {
                initMonitor = msSerivice.GetMonitorServerById(id);
                startPath   = Common.CommonUtil.GetLocalCopyPath();
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            ViewData["msData"]    = initMonitor;
            ViewData["StartPath"] = startPath;
            return(View());
        }
Beispiel #14
0
        /// <summary>
        /// 获取文件对应的SSH本地文件路径
        /// </summary>
        /// <param name="ms"></param>
        /// <param name="macPath"></param>
        /// <returns></returns>
        private string GetLocalSSHPath(MonitorServer ms, string macPath, string sshOP)
        {
            string localBasePath = ms.monitorLocalPath;

            //获取SSH输出基础路径 暂时不支持网络位置
            string localSSHBasePath = string.Empty;

            if (string.IsNullOrWhiteSpace(sshOP.Trim()))
            {
                localSSHBasePath = localBasePath.Substring(0, localBasePath.IndexOf(':') + 1) + "\\SSH\\" + ms.monitorServerName + "-SSH";
            }
            else
            {
                sshOP.TrimEnd('\\');
                localSSHBasePath = sshOP + "\\" + ms.monitorServerName + "-SSH";
            }
            string localSSHPath = macPath.Replace(ms.monitorMacPath, localSSHBasePath).Replace('/', '\\');

            localSSHPath = PathValidUtil.GetValidPath(localSSHPath);
            return(localSSHPath);
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            // change from service account's dir to more logical one
            Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

            HostFactory.Run(x =>
            {
                x.RunAsLocalSystem();

                x.SetDescription("系统服务监控");
                x.SetDisplayName("eWorldServerMonitor");
                x.SetServiceName("eWorldServerMonitor");

                x.Service(factory =>
                {
                    MonitorServer server = new MonitorServer();
                    //server.Initialize();
                    return(server);
                });
            });
        }
Beispiel #16
0
        public ActionResult PathSelectModePartial(string monistorId)
        {
            MonitorServer initMonitor = new MonitorServer();

            try
            {
                if (monistorId != null)
                {
                    initMonitor = msService.GetMonitorServerById(Convert.ToInt32(monistorId));
                    ViewData["initFolderDetail"] = GetinitFolderList(monistorId);
                }
                ViewData["StartPath"] = initMonitor.monitorDrive;
                ViewData["msID"]      = TempData["msID"];
            }
            catch (Exception ex)
            {
                ViewData["StartPath"] = "";
                ViewData["msID"]      = 0;
                logger.Error(ex.Message);
            }
            return(PartialView("PathSelectModePartial"));
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            if (args != null && args.Length > 0)
            {
                if (args[0].ToUpper() == "C")
                {
                    //以控制台运行
                    try
                    {
                        IsConsole = true;
                        MonitorServer MonitorServer = new MonitorServer();
                        MonitorServer.Debug += MonitorServer_Debug;
                        //调试模式
                        if (args.Length > 1 && args[1].ToUpper() == "D")
                        {
                            IsDebug = true;
                        }
                        MonitorServer.Start();
                        Console.ReadLine();
                        MonitorServer.Stop();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    return;
                }
            }
            //以Windows服务器运行
            MonitorService MonitorService = new MonitorService();

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                MonitorService
            };
            ServiceBase.Run(ServicesToRun);
        }
Beispiel #18
0
        /// <summary>
        /// 获取所有MonitorServer
        /// </summary>
        /// <returns></returns>
        public List <MonitorServer> GetAllMonitorServer(Model.Config config)
        {
            List <MonitorServer> list = new List <MonitorServer>();

            string    sql = "select * from [monitorServer] where [deleteFlg]=0 ";
            DataSet   ds  = DBHelper.ExecuteDataset(config.DB.ConnString, CommandType.Text, sql);
            DataTable dt  = null;

            if (ds != null && ds.Tables.Count == 1)
            {
                dt = ds.Tables[0];
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                //获取数据
                foreach (DataRow dr in dt.Rows)
                {
                    MonitorServer ms = new MonitorServer()
                    {
                        //monitorServerName unique
                        monitorServerName = Convert.ToString(dr["monitorServerName"]),
                        monitorServerIP   = Convert.ToString(dr["monitorServerIP"]),
                        account           = Convert.ToString(dr["account"]),
                        password          = Convert.ToString(dr["password"]),
                        startFile         = Convert.ToString(dr["startFile"]),
                        monitorDrive      = Convert.ToString(dr["monitorDrive"]),
                        monitorMacPath    = Convert.ToString(dr["monitorMacPath"]),
                        monitorLocalPath  = Convert.ToString(dr["monitorLocalPath"]),
                    };

                    list.Add(ms);
                }
            }

            return(list);
        }
Beispiel #19
0
        public int UpdateMonitorServer(MonitorServer MonitorServer, SqlConnection conn)
        {
            int    result = -1;
            string sql    = "UPDATE monitorServer SET monitorServerName = @servername,"
                            + " monitorServerIP = @ip,"
                            + " memo = @memo, "
                            + " account =@account,"
                            + " password =@password,"
                            + " startFile =@startFile,"
                            + " monitorDrive = @monitorDrive,"
                            + " updater =@updater,"
                            + " updateDate =@updateDate"
                            + " WHERE id = @id";

            SqlParameter[] para = new SqlParameter[] {
                new SqlParameter("@servername", MonitorServer.monitorServerName),
                new SqlParameter("@ip", MonitorServer.monitorServerIP),
                new SqlParameter("@memo", MonitorServer.memo),
                new SqlParameter("@account", MonitorServer.account),
                new SqlParameter("@password", MonitorServer.password),
                new SqlParameter("@startFile", MonitorServer.startFile),
                new SqlParameter("@monitorDrive", MonitorServer.monitorDrive),
                new SqlParameter("@updater", MonitorServer.updater),
                new SqlParameter("@updateDate", MonitorServer.updateDate),
                new SqlParameter("@id", MonitorServer.id)
            };
            try
            {
                result = db.Udaquery(sql, conn, para);
            }
            catch (Exception e)
            {
                throw e;
            }
            return(result);
        }
Beispiel #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTansferFile(object sender, System.Timers.ElapsedEventArgs e)
        {
            m_timer.Enabled = false;
            //バックアップ先list
            IList <BackupServer> BackupServer = BackupServerService.GetGroupBackupServerList(backupgroupid);
            //バックアップ元
            MonitorServer MonitorServer = MonitorServerService.GetMonitorServerById(Int32.Parse(monitorid));
            string        strSenderDir  = MonitorServer.monitorLocalPath + "\\";
            //バックアップ元のファイル変更list
            IList <MonitorServerFile> monitorServerFileList = MonitorServerFileService.GetMonitorServerFileSSBPutList(monitorid, strSenderDir.TrimEnd('\\'));
            string requestUrl = System.Configuration.ConfigurationManager.AppSettings["ssbapi"];
            string account    = System.Configuration.ConfigurationManager.AppSettings["ssbaccount"];
            string password   = System.Configuration.ConfigurationManager.AppSettings["ssbpassword"];

            try
            {
                if (Directory.GetDirectories(strSenderDir).Length > 0 || Directory.GetFiles(strSenderDir).Length > 0)
                {
                    foreach (BackupServer backup in BackupServer)
                    {
                        try
                        {
                            SkeedFileTransfer filetransfer = new SkeedFileTransfer(requestUrl, account, password);
                            var jsonSession = filetransfer.connect(backup.backupServerIP);
                            //
                            if (monitorServerFileList.Count > 0)
                            {
                                // linq
                                var dirList = monitorServerFileList.ToList().Distinct(new DirectoryNameComparer());
                                // 転送情報
                                Hashtable transferInfo = new Hashtable();
                                if (dirList.Count() > 0)
                                {
                                    foreach (var dirname in dirList)
                                    {
                                        if (jsonSession.ToString() != string.Empty && jsonSession.result == 0)
                                        {
                                            dynamic jsonResult = filetransfer.doingTransferBatchesList();
                                            if (jsonResult.ToString() != string.Empty && jsonResult.result == 0)
                                            {
                                                try
                                                {
                                                    filetransfer.disconnect(jsonSession.session.sessionId);
                                                }
                                                catch (Exception ex)
                                                {
                                                }
                                                int taskeNum = Regex.Matches(jsonResult.ToString(), "taskId").Count;
                                                if (taskeNum <= SSBTaskMaxNum)
                                                {
                                                    //SSB Upload
                                                    DateTime startTime = DateTime.Now;
                                                    // 削除の場合
                                                    bool   transferresult;
                                                    string remotepath = RemotePathConvert(strSenderDir, dirname.monitorFileDirectory, backup.ssbpath);
                                                    transferresult = TransferDir(backup.backupServerIP, dirname.monitorFileDirectory, remotepath, minbpsset, maxbpsset, initbpsset);
                                                    DateTime       endTime        = DateTime.Now;
                                                    TimeSpan       timespan       = endTime - startTime;
                                                    TransferResult transferResult = new TransferResult();
                                                    if (transferresult)
                                                    {
                                                        transferResult.OKResult = true;
                                                        MonitorServerFileService.UpdateAllTransferFlg(dirname.monitorFileDirectory, 1);
                                                    }
                                                    else
                                                    {
                                                        transferResult.OKResult = false;
                                                        MonitorServerFileService.UpdateAllTransferFlg(dirname.monitorFileDirectory, 2);
                                                    }
                                                    transferResult.StartTime = startTime;
                                                    transferResult.EndTime   = endTime;
                                                    transferResult.TimeSpan  = timespan;
                                                    transferInfo.Add(dirname.monitorFileDirectory, transferResult);
                                                }
                                            }
                                        }
                                    }
                                    // ファイル更新
                                    foreach (MonitorServerFile file in monitorServerFileList)
                                    {
                                        try
                                        {
                                            TransferResult dirResult = transferInfo[file.monitorFileDirectory] as TransferResult;
                                            if (dirResult.OKResult)
                                            {
                                                MonitorServerFileService.UpdateTransferFlg(file.id, 1);
                                                //insert log and backupserverfile
                                                //InsertTransferInfo(file, backup, dirResult.StartTime, dirResult.EndTime, dirResult.TimeSpan, 1);
                                            }
                                            else
                                            {
                                                MonitorServerFileService.UpdateTransferFlg(file.id, 2);
                                                //insert log and backupserverfile
                                                //InsertTransferInfo(file, backup, dirResult.StartTime, dirResult.EndTime, dirResult.TimeSpan, 2);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            logger.Error(ex.Message);
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex.Message);
                            continue;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            m_timer.Enabled = true;
        }
Beispiel #21
0
        public ActionResult Index(string monistorId)
        {
            //session値チェック
            if (Session["LoginId"] == null)
            {
                return(RedirectToAction("Account", "Account/LogOn", new { url = Request.Url }));
            }
            string strMonitorId = string.Empty;

            try
            {
                IList <MonitorServer> monitorList = msService.GetMonitorServerList();
                ViewData["monitorList"]    = monitorList;
                ViewData["expandedPath"]   = Request.QueryString["expandedPath"];
                ViewData["StartPath"]      = "";
                ViewData["initMonistorId"] = "";
                TempData["msID"]           = 0;

                MonitorServer msModel = null;
                if (!String.IsNullOrWhiteSpace(monistorId))
                {
                    msModel = msService.GetMonitorServerById(int.Parse(monistorId));
                }
                else if (monitorList.Count > 0)
                {
                    msModel = monitorList[0];
                }

                if (msModel != null)
                {
                    ViewData["StartPath"]      = msModel.monitorDrive.TrimEnd('\\');
                    ViewData["initMonistorId"] = msModel.id;
                    TempData["msID"]           = msModel.id;
                    if (!System.IO.Directory.Exists(@"\\" + msModel.monitorServerIP + @"\" + msModel.startFile.TrimStart('\\').Replace('/', '\\')))
                    {
                        int status = Common.NetworkConnection.Connect(@"\\" + msModel.monitorServerIP + @"\" + msModel.startFile.TrimStart('\\').Replace('/', '\\'), msModel.monitorDriveP, msModel.account, msModel.password);
                    }
                    //connState = networkConntion(monitorList[0].monitorServerIP, monitorList[0].startFile, monitorList[0].monitorDrive, monitorList[0].account, monitorList[0].password);
                }

                List <Model.MonitorServerFolder> folderList = new List <MonitorServerFolder>();
                ViewData["ClientSideEvents"] = new string[] {
                    "Init",
                    "ExpandedChanging",
                    "ExpandedChanged",
                    "CheckedChanged",
                    "NodeClick"
                };
                ViewData["initFolderDetail"] = GetinitFolderList(strMonitorId);
            }
            catch (Exception ex)
            {
                ViewData["monitorList"]      = new List <MonitorServer>();
                TempData["msID"]             = 0;
                ViewData["StartPath"]        = "";
                ViewData["initMonistorId"]   = "";
                ViewData["initFolderDetail"] = new List <Models.MonitFolder>();
                logger.Error(ex.Message);
            }
            return(View());
        }
Beispiel #22
0
        public ActionResult Add(MonitorServer msModel)
        {
            int result = -1;

            //session获取值
            if (Session["LoginId"] == null)
            {
                result = -99;
            }
            else
            {
                //保存
                try
                {
                    //string strpath = msModel.monitorDrive + ":";
                    string strpath = "\\\\" + msModel.monitorServerIP.Trim() + "\\" + msModel.startFile.Trim().Trim('\\').Replace('/', '\\') + "\\";
                    //if (!Directory.Exists(strpath))
                    //{
                    //    result = -20;
                    //}
                    //else
                    //{
                    string dt = Common.CommonUtil.DateTimeNowToString();
                    msModel.monitorDrive   = strpath.TrimEnd('\\');
                    msModel.monitorDriveP  = msModel.monitorDriveP + ":";
                    msModel.creater        = Session["LoginId"].ToString();
                    msModel.createDate     = dt;
                    msModel.deleteFlg      = 0;
                    msModel.updater        = Session["LoginId"].ToString();
                    msModel.updateDate     = dt;
                    msModel.synchronismFlg = 0;
                    result = msSerivice.InsertMonitorServer(msModel);

                    //maxID
                    int intMonitorServerID = msSerivice.GetMaxId();
                    //if (Directory.Exists(strpath))
                    //{
                    MonitorServerFolder model = new MonitorServerFolder();
                    model.monitorServerID = intMonitorServerID;
                    model.monitorFileType = "99";
                    model.monitorFilePath = strpath.TrimEnd('\\');
                    model.monitorFileName = "";
                    model.createDate      = dt;
                    model.updateDate      = dt;
                    model.creater         = Session["LoginId"].ToString();
                    model.updater         = Session["LoginId"].ToString();
                    model.monitorServerID = intMonitorServerID;
                    model.monitorFileName = "";
                    model.monitorFlg      = "0";
                    model.initFlg         = "1";
                    model.deleteFlg       = 0;
                    model.synchronismFlg  = 0;
                    result = msFolderService.InsertMonitorServerFolder(model);
                    result = InsertFolder(strpath, dt, intMonitorServerID);
                    //}
                    //}
                }
                catch (Exception ex)
                {
                    result = -10;
                    logger.Error(ex.Message);
                }
            }
            Response.Write(result);
            Response.End();
            return(null);
        }
Beispiel #23
0
        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="sf"></param>
        /// <param name="ms"></param>
        /// <param name="sshOP">SSH output path</param>
        /// <param name="sftpProxy"></param>
        private void SSHCopyFile(SftpFile sf, MonitorServer ms, string sshOP, SFTPProxy sftpProxy)
        {
            var sshlog = new Common.Util.SSHLogManager();
            //获取本地合法路径
            string localPath = GetValidLocalPath(sf.FullName, ms.monitorMacPath, ms.monitorLocalPath);

            //获取SSH输出路径 暂时不支持网络位置
            if (string.IsNullOrWhiteSpace(sshOP.Trim()))
            {
                localPath = localPath.Substring(0, localPath.IndexOf(':') + 1) + "\\SSH\\" + ms.monitorServerName + "-SSH";
            }
            else
            {
                sshOP.TrimEnd('\\');
                localPath = localPath.Replace(ms.monitorLocalPath.TrimEnd('\\'), sshOP + "\\" + ms.monitorServerName + "-SSH");
            }
            #region  制
            DateTime dateM = sf.Attributes.LastWriteTime;
            DateTime dateA = sf.Attributes.LastAccessTime;

            #region
            try
            {
                Alphaleonis.Win32.Filesystem.FileInfo targetFile = new Alphaleonis.Win32.Filesystem.FileInfo(localPath);
                //如果文件没有发生改变,则不进行下载
                if (targetFile.Exists)
                {
                    if (targetFile.LastWriteTime == dateM)
                    {
                        return;
                    }
                }

                if (!Directory.Exists(targetFile.DirectoryName))
                {
                    try
                    {
                        Directory.CreateDirectory(targetFile.DirectoryName);
                    }
                    catch (System.Exception) { }
                    if (!Directory.Exists(targetFile.DirectoryName))
                    {
                        LongPath.CreateDirectory(targetFile.DirectoryName);
                    }
                }

                sftpProxy.GetFile(sf.FullName, targetFile.FullName, true);

                targetFile.Refresh();
                if (targetFile.Exists)
                {
                    targetFile.CreationTime   = dateM;
                    targetFile.LastWriteTime  = dateM;
                    targetFile.LastAccessTime = dateA;
                }
                else
                {
                    #region
                    string errorDirToFileNameExtension = "";
                    if (sf.Name.IndexOf(".") > -1)
                    {
                        errorDirToFileNameExtension = sf.Name.Substring(sf.Name.IndexOf(@".") + 1);
                    }
                    Thread.Sleep(2000);
                    bool copyconfirm   = true;
                    int  confirmCoount = 0;
                    while (copyconfirm)
                    {
                        #region
                        if (confirmCoount < 3)
                        {
                            targetFile.Refresh();
                            if (targetFile.Exists)
                            {
                                DateTime fileFirstTime = targetFile.LastWriteTime;
                                Thread.Sleep(2000);
                                DateTime fileSecondTime = targetFile.LastWriteTime;
                                if (fileFirstTime.Equals(fileSecondTime))
                                {
                                    targetFile.CreationTime   = dateM;
                                    targetFile.LastWriteTime  = dateM;
                                    targetFile.LastAccessTime = dateA;
                                    copyconfirm = false;
                                }
                            }
                            else
                            {
                                Thread.Sleep(2000);
                            }
                            confirmCoount++;
                        }
                        else
                        {
                            break;
                        }
                        #endregion
                    }

                    #endregion
                }

                sshlog.WriteLog(new Common.Util.SSHLog()
                {
                    DateTime = DateTime.Now, LogType = Common.Util.SSHLogType.Success, Message = targetFile.FullName
                });
            }
            catch (ArgumentException ae)
            {
                logger.Error("localpath:" + localPath + Environment.NewLine + MessageUtil.GetExceptionMsg(ae, ""));
                sshlog.WriteLog(new Common.Util.SSHLog()
                {
                    DateTime = DateTime.Now, LogType = Common.Util.SSHLogType.Failure, Message = ms.monitorServerIP + ", " + sf.FullName
                });
            }
            catch (System.Exception ex)
            {
                logger.Error("localpath:" + localPath + Environment.NewLine + MessageUtil.GetExceptionMsg(ex, ""));
                sshlog.WriteLog(new Common.Util.SSHLog()
                {
                    DateTime = DateTime.Now, LogType = Common.Util.SSHLogType.Failure, Message = ms.monitorServerIP + ", " + sf.FullName
                });
            }
            #endregion
            #endregion
        }
Beispiel #24
0
        /// <summary>
        /// 判断文件是否发生变化,若变化则copy文件
        /// </summary>
        /// <param name="config"></param>
        /// <param name="epi"></param>
        public void SSHCopy(Config config, ErrorPathInfo epi)
        {
            //获取mac端信息
            MonitorServerDAL msd = new MonitorServerDAL();
            MonitorServer    ms  = msd.GetMonitorServer(config, epi);

            if (ms == null)
            {
                Common.Util.LogManager.WriteLog(LogFile.Warning, "there is no MonitorServer that meet the conditions !");
                return;
            }
            SFTPProxy sftpProxy = null;
            var       sshlog    = new Common.Util.SSHLogManager();

            try
            {
                sftpProxy = new SFTPProxy(ms.monitorServerIP, ms.account, ms.password);
                #region 处理
                foreach (ErrorEntry ee in epi.PathList)
                {
                    string macPath = string.Empty;
                    try
                    {
                        //获取mac路径
                        macPath = MacPathConvert(epi.source, ee.Path, ms.monitorMacPath, ms.startFile);

                        //获取远端文件属性
                        SftpFile sf = sftpProxy.GetFileInfo(macPath);

                        if (!ErrorPathFilter.IsUpdate(config, sf, ms))
                        {
                            continue;
                        }
                        if (sf.IsDirectory)
                        {
                            #region  除job端已经删除的文件

                            #endregion
                            foreach (SftpFile sfile in sftpProxy.Ls(sf))
                            {
                                #region  过滤无关文件
                                if (String.Compare(sfile.Name.Trim('\r'), ".DS_Store", true) == 0 ||
                                    String.Compare(sfile.Name.Trim('\r'), ".com.apple.timemachine.supported", true) == 0 ||
                                    String.Compare(sfile.Name.Trim('\r'), "Icon", true) == 0)
                                {
                                    continue;
                                }
                                #endregion
                                if (!ErrorPathFilter.IsUpdate(config, sfile, ms))
                                {
                                    continue;
                                }

                                SSHCopyFile(sfile, ms, config.Path.OutputPath, sftpProxy);
                            }
                        }
                        else
                        {
                            SSHCopyFile(sf, ms, config.Path.OutputPath, sftpProxy);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        Common.Util.LogManager.WriteLog(LogFile.Error, MessageUtil.GetExceptionMsg(ex, ""));
                        sshlog.WriteLog(new Common.Util.SSHLog()
                        {
                            DateTime = DateTime.Now, LogType = Common.Util.SSHLogType.Failure, Message = ee.Path
                        });
                    }
                }
                #endregion
            }
            catch (System.Exception ex)
            {
                Common.Util.LogManager.WriteLog(LogFile.Error, MessageUtil.GetExceptionMsg(ex, ""));
            }
            finally
            {
                if (sftpProxy != null)
                {
                    sftpProxy.Close();
                }
            }
        }
Beispiel #25
0
        /// <summary>
        /// データ更新
        /// </summary>
        /// <param name="msModel"></param>
        /// <returns></returns>
        public ActionResult Update(MonitorServer msModel)
        {
            int result = -1;

            if (Session["LoginId"] == null)
            {
                result = -99;
            }
            else
            {
                try
                {
                    msModel.id = Request.Form["msId"];
                    string        dt            = Common.CommonUtil.DateTimeNowToString();
                    MonitorServer monitorServer = msSerivice.GetMonitorServerById(Convert.ToInt32(msModel.id));
                    msModel.updater    = Session["LoginId"].ToString();
                    msModel.updateDate = dt;
                    if (msModel.memo == null)
                    {
                        msModel.memo = string.Empty;
                    }
                    if (msModel.monitorDriveP == "" || msModel.monitorDriveP == null)
                    {
                        for (char i = 'A'; i <= 'Z'; i++)
                        {
                            if (!Directory.Exists(i + ":"))
                            {
                                msModel.monitorDriveP = i.ToString();
                                break;
                            }
                        }
                    }
                    string strpath = "\\\\" + msModel.monitorServerIP.Trim() + "\\" + msModel.startFile.Trim().Trim('\\').Replace('/', '\\') + "\\";
                    msModel.monitorDrive = strpath.TrimEnd('\\');
                    result = msSerivice.UpdateMonitorServer(msModel);
                    if (result > -1)
                    {
                        if (msModel.monitorDriveP.IndexOf(':') <= -1)
                        {
                            msModel.monitorDriveP = msModel.monitorDriveP + ":";
                        }
                        if (System.IO.Directory.Exists(msModel.monitorDriveP))
                        {
                            int resultForDeleteMonitorServerFolder = msFolderService.DeleteMonitorServerFolderByServerId(Int32.Parse(msModel.id));
                            if (resultForDeleteMonitorServerFolder > -1)
                            {
                                //string strpath = "\\\\" + msModel.monitorServerIP.Trim() + "\\" + msModel.startFile.Trim().Trim('\\').Replace('/', '\\') + "\\";
                                DirectoryInfo       di    = new DirectoryInfo(msModel.monitorDrive);
                                MonitorServerFolder model = new MonitorServerFolder();
                                model.monitorServerID = Convert.ToInt32(msModel.id);
                                model.monitorFileType = "99";
                                model.monitorFilePath = strpath.TrimEnd('\\');
                                model.monitorFileName = "";
                                model.createDate      = dt;
                                model.updateDate      = dt;
                                model.creater         = Session["LoginId"].ToString();
                                model.updater         = Session["LoginId"].ToString();
                                model.monitorFileName = "";
                                model.monitorFlg      = "0";
                                model.initFlg         = "1";
                                model.deleteFlg       = 0;
                                int innerId = msFolderService.InsertMonitorServerFolder(model);
                            }
                        }
                        int monitorFileListenForResult = msFileListenService.UpdateMonitorServer(msModel, monitorServer);
                    }
                }
                catch (Exception ex)
                {
                    result = -10;
                    logger.Error(ex.Message);
                }
            }
            Response.Write(result);
            Response.End();
            return(null);
        }
Beispiel #26
0
        /// <summary>
        /// 扫描数据库,判断是否在mac上存在
        /// </summary>
        /// <param name="config"></param>
        private void DBSync(Config config)
        {
            try
            {
                /*
                 * 分页获取SSHPathInfo,找出mac端已经删除文件对应的id,删除对应的本地文件并刷新数据库
                 *
                 * 待确定的想法:如果发现mac端文件已经更新,则更新本地文件
                 */

                List <string>  delIDList = new List <string>();
                SSHPathInfoDAL spid      = new SSHPathInfoDAL();

                #region 主要处理
                try
                {
                    FileSystemUtil fsu = new FileSystemUtil();
                    //获取所有MonitorServer,以便于数据处理
                    MonitorServerDAL     msd    = new MonitorServerDAL();
                    List <MonitorServer> msList = msd.GetAllMonitorServer(config);

                    foreach (SSHPathInfo spi in spid.GetSSHPathInfo(config))
                    {
                        if (Signal.IsSystemStoping)
                        {
                            break;
                        }
                        #region 判断Mac端文件是否存在,如果不存在,则删除本地SSH输出目录中对应文件
                        SFTPProxy sftpProxy    = null;
                        string    localSSHPath = string.Empty;
                        try
                        {
                            //获取对应mac机的信息
                            MonitorServer ms = msList.Find(x => x.monitorServerIP.Trim().Equals(spi.MonitorServerIP.Trim()) && spi.MacPath.ToLower().Trim().Contains(x.monitorMacPath.ToLower().Trim()));
                            if (ms != null)
                            {
                                sftpProxy = new SFTPProxy(ms.monitorServerIP, ms.account, ms.password);
                                if (!sftpProxy.IsExist(spi.MacPath))
                                {
                                    delIDList.Add(spi.ID);
                                    #region  除SSH输出路径的本地文件
                                    //获取本地路径
                                    localSSHPath = GetLocalSSHPath(ms, spi.MacPath, config.Path.OutputPath);
                                    if (spi.typeflag == 0)
                                    {
                                        fsu.DeleteDir(localSSHPath);
                                    }
                                    else
                                    {
                                        //如果是文件
                                        fsu.DeleteFile(localSSHPath);
                                        //判断目录是否为空:是否有文件
                                        CleanLocalSSHDirectory(fsu, localSSHPath);
                                    }
                                    #endregion
                                }
                            }
                        }
                        catch (System.Exception ex)
                        {
                            Common.Util.LogManager.WriteLog(Common.Util.LogFile.DBSync, localSSHPath + Environment.NewLine + MessageUtil.GetExceptionMsg(ex, ""));
                        }
                        finally
                        {
                            if (sftpProxy != null)
                            {
                                sftpProxy.Close();
                            }
                        }
                        #endregion
                    }
                }
                catch (System.Exception ex)
                {
                    Common.Util.LogManager.WriteLog(Common.Util.LogFile.DBSync, MessageUtil.GetExceptionMsg(ex, ""));
                }
                finally
                {
                    spid.Dispose();
                }
                #endregion

                #region 更新数据库
                spid.DeleteEntrys(config, delIDList);
                #endregion
            }
            catch (System.Exception ex)
            {
                Common.Util.LogManager.WriteLog(Common.Util.LogFile.DBSync, MessageUtil.GetExceptionMsg(ex, ""));
            }
        }
Beispiel #27
0
        private void _localSync(Config config)
        {
            #region  步到本地目的目录
            try
            {
                //获取所有MonitorServer,以便于数据处理
                MonitorServerDAL     msd    = new MonitorServerDAL();
                List <MonitorServer> msList = msd.GetAllMonitorServer(config);

                #region 获取SSH输出路径中的第一层子目录 (PS:此情况为:SSH输出路径 必须配置)
                //获取SSH输出基础路径 暂时不支持网络位置
                DirectoryInfo sshDI = new DirectoryInfo(config.Path.OutputPath);
                if (sshDI.Exists)
                {
                    //获取MonitorServer相对的SSH根目录
                    foreach (DirectoryInfo di in sshDI.EnumerateDirectories())
                    {
                        if (Signal.IsSystemStoping)
                        {
                            break;
                        }

                        //获取对应的MonitorServer
                        int flagIndex = di.Name.LastIndexOf("-SSH");
                        if (flagIndex <= 0)
                        {
                            continue;
                        }

                        Common.Util.LogManager.WriteLog(Common.Util.LogFile.LocalSync, di.FullName);

                        string        msName = di.Name.Substring(0, flagIndex);
                        MonitorServer ms     = msList.Find(x => x.monitorServerName.Equals(msName));

                        //相对于本地设定的基础路径
                        DirectoryInfo roboBasePathDI = new DirectoryInfo(ms.monitorLocalPath);
                        if (roboBasePathDI.Exists)
                        {
                            //判断文件在Robocopy目标路径中是否存在
                            foreach (FileInfo fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
                            {
                                if (Signal.IsSystemStoping)
                                {
                                    break;
                                }
                                //获取Robocopy目标路径
                                string   destPath   = fi.FullName.Replace(di.FullName, ms.monitorLocalPath);
                                FileInfo targetFile = new FileInfo(destPath);
                                //如果已经被删除,则复制
                                if (!targetFile.Exists)
                                {
                                    if (!Directory.Exists(targetFile.DirectoryName))
                                    {
                                        Directory.CreateDirectory(targetFile.DirectoryName);
                                    }

                                    File.Copy(fi.FullName, targetFile.FullName);
                                }
                            }
                        }
                    }
                }
                #endregion

                //探测 Robocopy目的路径中的SSH copy文件是否存在
            }
            catch (System.Exception ex)
            {
                Common.Util.LogManager.WriteLog(Common.Util.LogFile.LocalSync, MessageUtil.GetExceptionMsg(ex, ""));
            }
            #endregion
        }
Beispiel #28
0
        public DownloadSearchResult GetMatchList(string searchPattern, string monitorServerID, int maxsize, string username)
        {
            SqlDataReader        sdr       = null;
            SqlDataReader        sdrPathBk = null;
            DownloadSearchResult ds        = null;

            //the max size
            try
            {
                #region get the monitor server id
                string msid = string.Empty;
                if (monitorServerID == "-1")
                {
                    msid = monitorServerID;
                }
                else
                {
                    msid = monitorServerID.Split('|')[1];
                }
                #endregion

                FileDownloadDAL fdal = new FileDownloadDAL();

                //get monitor Server
                string dbServerip = ConfigUtil.AppSetting("remoteIP");
                string msidCond   = GetMsidCond(username, dbServerip, msid);

                List <MonitorServer> mslist = fdal.GetMSList(dbServerip, msidCond);
                if (mslist != null && mslist.Count > 0)
                {
                    //use this to check whether the folder exists
                    HashSet <string> folderSet = new HashSet <string>();
                    HashSet <string> fileSet   = new HashSet <string>();
                    #region  from filelisten
                    #region get reader
                    sdr = fdal.GetSearchReader(searchPattern, msidCond);
                    #endregion

                    #region get the match list
                    if (sdr != null)
                    {
                        ds = new DownloadSearchResult();
                        while (sdr.Read())
                        {
                            string relativePath = Convert.ToString(sdr["monitorFileRelativeFullPath"]);

                            if (fileSet.Add(relativePath))
                            {
                                #region analyse  the rows
                                //get the monitor server
                                string        msID = Convert.ToString(sdr["monitorServerID"]);
                                MonitorServer ms   = mslist.Find((x) => x.ID.Equals(msID));

                                //get the filename
                                string fileName      = Convert.ToString(sdr["monitorFileName"]);
                                string macbasePath   = @"\\" + Convert.ToString(sdr["monitorServerIP"]) + @"\" + Convert.ToString(sdr["sharePoint"]);
                                string winbasePath   = ms.DBServerIP + ms.MonitorLocalPath.Substring(ms.MonitorLocalPath.IndexOf(':') + 1);
                                string lastWriteTime = Convert.ToString(sdr["updateDate"]);

                                //check filename or subdir contains the search pattern
                                if (fileName.Contains(searchPattern))
                                {
                                    #region file

                                    ds.FileInfoList.Add(new DFileInfo()
                                    {
                                        Name          = fileName,
                                        WinPath       = winbasePath + relativePath,
                                        MacPath       = macbasePath + relativePath,
                                        LastWriteTime = lastWriteTime
                                    });

                                    #endregion
                                }

                                #region check folder

                                //check the count match the needle
                                string[] subdirs = relativePath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                                for (int i = 0; i < subdirs.Count() - 1; i++)
                                {
                                    string subdir = subdirs[i];
                                    if (subdir.Contains(searchPattern))
                                    {
                                        string temp = string.Empty;
                                        for (int j = 0; j <= i; j++)
                                        {
                                            temp += @"\" + subdirs[j];
                                        }
                                        string folderMacPath = macbasePath + temp;
                                        if (folderSet.Add(folderMacPath))
                                        {
                                            ds.FolderInfoList.Add(new DFolderInfo()
                                            {
                                                Name          = subdir,
                                                WinPath       = winbasePath + temp,
                                                MacPath       = folderMacPath,
                                                LastWriteTime = lastWriteTime
                                            });
                                        }
                                    }
                                }
                                #endregion

                                #endregion
                                //check the count
                                if (ds.Count >= maxsize)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    #endregion
                    #endregion

                    #region from pathBk
                    if (ds.Count <= maxsize)
                    {
                        #region get reader
                        sdrPathBk = fdal.GetSearchReaderPathBk(searchPattern, msidCond);

                        #endregion
                        #region get the match list

                        if (sdrPathBk != null)
                        {
                            while (sdrPathBk.Read())
                            {
                                //get the filename
                                string relativePath = Convert.ToString(sdrPathBk["monitorFileRelativeFullPath"]);
                                if (fileSet.Add(relativePath))
                                {
                                    #region analyse  the rows
                                    //get the monitor server
                                    string        msID = Convert.ToString(sdrPathBk["monitorServerID"]);
                                    MonitorServer ms   = mslist.Find((x) => x.ID.Equals(msID));


                                    int    lastIndex     = relativePath.LastIndexOf(Path.DirectorySeparatorChar);
                                    string fileName      = relativePath.Substring(lastIndex + 1);
                                    string macbasePath   = @"\\" + ms.MonitorServerIP + @"\" + ms.StartFile;
                                    string winbasePath   = ms.DBServerIP + ms.MonitorLocalPath.Substring(ms.MonitorLocalPath.IndexOf(':') + 1);
                                    string lastWriteTime = "";

                                    #endregion

                                    //check filename or subdir contains the search pattern
                                    if (fileName.Contains(searchPattern))
                                    {
                                        #region file
                                        ds.FileInfoList.Add(new DFileInfo()
                                        {
                                            Name          = fileName,
                                            WinPath       = winbasePath + relativePath,
                                            MacPath       = macbasePath + relativePath,
                                            LastWriteTime = lastWriteTime
                                        });
                                        #endregion
                                    }

                                    #region check folder

                                    //check the count match the needle
                                    string[] subdirs = relativePath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                                    for (int i = 0; i < subdirs.Count() - 1; i++)
                                    {
                                        string subdir = subdirs[i];
                                        if (subdir.Contains(searchPattern))
                                        {
                                            string temp = string.Empty;
                                            for (int j = 0; j <= i; j++)
                                            {
                                                temp += @"\" + subdirs[j];
                                            }
                                            string folderMacPath = macbasePath + temp;
                                            if (folderSet.Add(folderMacPath))
                                            {
                                                ds.FolderInfoList.Add(new DFolderInfo()
                                                {
                                                    Name          = subdir,
                                                    WinPath       = winbasePath + temp,
                                                    MacPath       = folderMacPath,
                                                    LastWriteTime = lastWriteTime
                                                });
                                            }
                                        }
                                    }
                                    #endregion

                                    //check the count
                                    if (ds.Count >= maxsize)
                                    {
                                        break;
                                    }
                                }
                            }
                        }

                        #endregion
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            finally
            {
                if (sdr != null)
                {
                    sdr.Close();
                }

                if (sdrPathBk != null)
                {
                    sdr.Close();
                }
            }
            return(ds);
        }
Beispiel #29
0
        /// <summary>
        /// 転送ファイルのチェック
        /// </summary>
        /// <param name="dirs"></param>
        private void TransferMain()
        {
            //バックアップ先list
            IList <BackupServer> BackupServer = BackupServerService.GetGroupBackupServerList(_backupgroupid);
            //バックアップ元
            MonitorServer MonitorServer = MonitorServerService.GetMonitorServerById(Int32.Parse(_monitorid));
            string        strSenderDir  = MonitorServer.monitorLocalPath + "\\";
            //バックアップ元のファイル変更list
            IList <MonitorServerFile> monitorServerFileForDelList    = MonitorServerFileService.GetMonitorServerFileDelList(_monitorid);
            IList <MonitorServerFile> monitorServerFileForTopDirList = MonitorServerFileService.GetMonitorServerFileTopDirList(_monitorid, strSenderDir.TrimEnd('\\'));
            string requestUrl = System.Configuration.ConfigurationManager.AppSettings["ssbapi"];
            string account    = System.Configuration.ConfigurationManager.AppSettings["ssbaccount"];
            string password   = System.Configuration.ConfigurationManager.AppSettings["ssbpassword"];

            foreach (BackupServer backup in BackupServer)
            {
                try
                {
                    SkeedFileTransfer filetransfer = new SkeedFileTransfer(requestUrl, account, password);
                    var jsonSession = filetransfer.connect(backup.backupServerIP);

                    if (jsonSession.ToString() != string.Empty && jsonSession.result == 0)
                    {
                        //批量传输
                        string strFileName    = "";
                        string fileId         = "";
                        string strDelFileName = "";
                        string fileDelId      = "";
                        foreach (MonitorServerFile file in monitorServerFileForDelList)
                        {
                            strDelFileName = strDelFileName + "&files=./" + file.monitorFilePath.Replace(strSenderDir, "");
                            fileDelId      = fileDelId + file.id + ",";
                        }
                        foreach (MonitorServerFile file in monitorServerFileForTopDirList)
                        {
                            strFileName = strFileName + "&files=" + file.monitorFilePath;
                            fileId      = fileId + file.id + ",";
                        }
                        if (strDelFileName != "")
                        {
                            //SSB Delete
                            DateTime startTime  = DateTime.Now;
                            dynamic  jsonResult = filetransfer.deleteFiles(jsonSession.session.sessionId, strSenderDir, backup.startFile, strDelFileName.TrimStart('&'));
                            DateTime endTime    = DateTime.Now;
                            TimeSpan timespan   = endTime - startTime;
                            if (jsonResult.ToString() != string.Empty && jsonResult.result == 0)
                            {
                                foreach (MonitorServerFile file in monitorServerFileForDelList)
                                {
                                    try
                                    {
                                        //更新传输flg
                                        MonitorServerFileService.UpdateTransferFlg(file.id, 1);
                                        //insert log and backupserverfile
                                        //InsertTransferInfo(file, backup, startTime, endTime, timespan, 1);
                                        //logger.Info("["+file.monitorFilePath + "] is deleted to [" + backup.backupServerIP + "] OK");
                                    }
                                    catch (Exception ex)
                                    {
                                        logger.Error(ex.Message);
                                        continue;
                                    }
                                }
                            }
                            else
                            {
                                try
                                {
                                    foreach (MonitorServerFile file in monitorServerFileForDelList)
                                    {
                                        //更新传输flg
                                        MonitorServerFileService.UpdateTransferFlg(file.id, 2);
                                        //insert log and backupserverfile
                                        //InsertTransferInfo(file, backup, startTime, endTime, timespan, 2);
                                        //logger.Info("[" + file.monitorFilePath + "] is deleted to [" + backup.backupServerIP + "] NG");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    logger.Error(ex.Message);
                                    continue;
                                }
                            }
                        }
                        if (strFileName != "")
                        {
                            //SSB Upload
                            DateTime startTime  = DateTime.Now;
                            dynamic  jsonResult = filetransfer.transferFiles(jsonSession.session.sessionId, strSenderDir, strFileName);
                            DateTime endTime    = DateTime.Now;
                            TimeSpan timespan   = endTime - startTime;
                            if (jsonResult.ToString() != string.Empty && jsonResult.result == 0)
                            {
                                foreach (MonitorServerFile file in monitorServerFileForTopDirList)
                                {
                                    try
                                    {
                                        //更新传输flg
                                        MonitorServerFileService.UpdateTransferFlg(file.id, 1);
                                        //insert log and backupserverfile
                                        //InsertTransferInfo(file, backup, startTime, endTime, timespan, 1);
                                        //logger.Info("[" + file.monitorFilePath + "] is uploaded to [" + backup.backupServerIP + "] OK");
                                    }
                                    catch (Exception ex)
                                    {
                                        logger.Error(ex.Message);
                                        continue;
                                    }
                                }
                            }
                            else
                            {
                                foreach (MonitorServerFile file in monitorServerFileForTopDirList)
                                {
                                    try
                                    {
                                        //更新传输flg
                                        MonitorServerFileService.UpdateTransferFlg(file.id, 2);
                                        //insert log and backupserverfile
                                        //InsertTransferInfo(file, backup, startTime, endTime, timespan, 2);
                                        //logger.Info("[" + file.monitorFilePath + "] is uploaded to [" + backup.backupServerIP + "] NG");
                                    }
                                    catch (Exception ex)
                                    {
                                        logger.Error(ex.Message);
                                        continue;
                                    }
                                }
                            }
                        }
                        var jsonSession2 = filetransfer.disconnect(jsonSession.session.sessionId);
                    }
                    else
                    {
                        logger.Error("[" + backup.backupServerIP + "]は接続できません");
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message);
                    continue;
                }
            }
        }