Пример #1
0
        /// <summary>
        ///     Adds a number of entities to the system.
        /// </summary>
        /// <param name="entities">The entities to add.</param>
        /// <param name="db">The unit of work to operate against.</param>
        public virtual void Add(IEnumerable <TEntity> entities, IUnitOfWorkLinq <TEntity, TKey> db)
        {
            Guard.ArgumentNotNull(entities, nameof(entities));
            Guard.ArgumentNotNull(db, nameof(db));

            //avoid multiple enumerations
            var entitiesAsArray = entities.ToArray();

            entitiesAsArray.Each(OnBeforeAdd);

            DemandValid(entitiesAsArray);

            // try assign domain id
            entitiesAsArray.Each(entity =>
            {
                if (entity.Id.Equals(default(TKey)))
                {
                    _idProvider.Provide(entity); //assign next key
                }
            });

            Db.EntitySet.Writer.Insert(entitiesAsArray);

            // send domain events
            entitiesAsArray.Each(entity =>
            {
                MessagePipe.SendAsync(new ItemAdded <TEntity>(entity));

                // notify item add
                OnAfterItemAdded(entity);
            }
                                 );
        }
Пример #2
0
        public void MergeNewStatements()
        {
            var  statementLocations = this.Repository.GetStatementLocations();
            bool isAnyMerged        = false;

            foreach (var statementLocation in statementLocations)
            {
                if (this.LatestMerged.HasImportInfo(statementLocation.ImportInfo.Id))
                {
                    MessagePipe.SendMessage("Location {0} skipped".FormatEx(statementLocation.Address));
                }
                else
                {
                    var statementTransactions = this.Repository.TransactionsStorage.Load(statementLocation);

                    var oldCount = this.LatestMerged.AllParentChildTransactions.Count();
                    this.LatestMerged.Merge(statementTransactions, false);

                    isAnyMerged = true;

                    MessagePipe.SendMessage("{0} transactions found ({1} new) in {2}".FormatEx(statementTransactions.AllParentChildTransactions.Count(),
                                                                                               this.LatestMerged.AllParentChildTransactions.Count() - oldCount, statementLocation.Address));
                }
            }

            if (isAnyMerged)
            {
                this.LatestMerged.MatchTransactions();
            }
        }
Пример #3
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    //ENTERING_SHAPE.Dispose();
                    //MOVING_SHAPE.Dispose();
                    //DRAGGING.Dispose();
                    //DEFAULT.Dispose();
                    //ZOOM_OUT.Dispose();
                    //ZOOM_IN.Dispose();
                    __selectedShapes.Clear();
                    __messagePipe.Dispose();
                    __userLayers.ForEach(l => l.Dispose());
                    __userLayers.Clear();
                    __opLayer.Clear();
                    __opLayer.Dispose();
                }

                //__cur = null;
                __userLayers   = null;
                __opLayer      = null;
                __defaultLayer = null;
                __messagePipe  = null;

                disposedValue = true;
            }
        }
Пример #4
0
        /// <summary>
        /// 是否连接上VPN服务器
        /// </summary>
        /// <param name="vpnAccount">VPN服务器供应账号信息</param>
        /// <param name="vpnServer">VPN服务器信息</param>
        /// <returns>返回连接结果</returns>
        public bool IslinkVpnServer(MVPNAccount vpnAccount, MVPNServer vpnServer)
        {
            bool linkResult = false;

            VpnHelper = new VPNHelper(vpnServer.Address, vpnServer.Area + vpnServer.Line, VpnAccount.Account, VpnAccount.Password);
            bool createOrUpdateResult = VpnHelper.CreateOrUpdateVPN();

            if (createOrUpdateResult)
            {
                ////连接VPN
                linkResult = VpnHelper.TryConnectVPN();
                if (linkResult)
                {
                    DateTime startTime    = DateTime.Now;
                    string   testLinkInfo = new TestLink().GetPingStr("www.baidu.com", 32, 200, 3);
                    if (testLinkInfo.Contains("100% 丢失"))
                    {
                        ////访问超时,也认为IP不可用
                        ////记录交互日志
                        string request = "VPN通道名称:" + vpnServer.Area + vpnServer.Line + ";VPN账号:" + vpnAccount.Account;
                        RecordLog.RecordInteractionLog(vpnAccount.Account, "连接VPN成功后,测试请求外网", request, testLinkInfo, DateTime.Now.Subtract(startTime), vpnServer.Address);
                        linkResult = false;
                    }

                    MessagePipe.ExcuteWriteMessageEvent(testLinkInfo, Color.Green, false);
                }
            }

            return(linkResult);
        }
Пример #5
0
        /// <summary>
        ///     菜单项“退出”单击时的事件。
        /// </summary>
        /// <param name="sender">触发事件的控件对象。</param>
        /// <param name="e">事件的参数。</param>
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 创建载入界面
            var task = new Thread(stop => { StopModels(); })
            {
                Name = RegisteredThreadName.ExitStopAllModels.ToString()
            };

            MessagePipe.SendInMessage(new KeyValuePair <Message, Thread>(Message.TaskIn, task));
            var loading = new Loading("正在退出,请稍候", task);

            loading.ShowDialog();

            // 等待结果
            if (!new WaitTimeoutChecker(30000).ThreadSleep(500, () => {
                var msg = MessagePipe.GetNextOutMessage(task);
                switch (msg)
                {
                case Message.NoAvailableMessage:
                    return(true);

                case Message.TaskOut:
                    return(false);

                default:
                    throw new Exception($"无效的消息类型:{msg}");
                }
            }))
            {
                Environment.Exit(-1);
            }

            // 模块已停止
            Environment.Exit(0);
        }
Пример #6
0
        protected static MessagePipe CreateMessagePipe(Message m, bool expectingOne = true)
        {
            var pipe = new MessagePipe(m);

            VerifyDefaultMessagePipe(pipe, expectingOne);
            return(pipe);
        }
Пример #7
0
        /// <summary>
        /// 取的默认网关
        /// </summary>
        /// <returns>返回网关地址</returns>
        public string GetDefaultGateWay()
        {
            string defaultGateWay = string.Empty;

            try
            {
                string        gateWayStr = this.ExcuteOrder("route print | find \"0.0.0.0\"");
                List <string> temp       = gateWayStr.Split(new char[] { ' ' }).ToList();
                List <string> iplist     = new List <string>();
                foreach (var str in temp)
                {
                    if (!string.IsNullOrEmpty(str))
                    {
                        iplist.Add(str);
                        if (iplist.Count > 3)
                        {
                            break;
                        }
                    }
                }

                if (iplist != null && iplist.Count > 3)
                {
                    defaultGateWay = iplist[2];
                }
            }
            catch (Exception ex)
            {
                MessagePipe.ExcuteWriteMessageEvent("取默认网关异常" + ex.Message.ToString(), Color.Green, false);
            }

            return(defaultGateWay);
        }
Пример #8
0
        public void message_pipe_down()
        {
            MessagePipe root  = new MessagePipe();
            MessagePipe left  = new MessagePipe(root);
            MessagePipe right = new MessagePipe(root);

            bool received = false;

            right.Sub <TestMessage>((in TestMessage tm) => { received = true; });
Пример #9
0
        /// <summary>
        ///     菜单项“启动所有模块”单击时的事件。
        /// </summary>
        /// <param name="sender">触发事件的控件对象。</param>
        /// <param name="e">事件的参数。</param>
        private void 启动所有模块ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 判断是否为重启
            if (启动所有模块ToolStripMenuItem.Text == "重启所有模块")
            {
                var result = false;

                // 创建载入界面
                var task = new Thread(stop => { result = StopModels(); })
                {
                    Name = RegisteredThreadName.RestartStopAllModels.ToString()
                };
                MessagePipe.SendInMessage(new KeyValuePair <Message, Thread>(Message.TaskIn, task));
                var loading = new Loading("正在停止,请稍候", task);
                loading.ShowDialog();

                // 等待结果
                new WaitTimeoutChecker(30000).ThreadSleep(500, () => {
                    var msg = MessagePipe.GetNextOutMessage(task);
                    switch (msg)
                    {
                    case Message.NoAvailableMessage:
                        return(true);

                    case Message.TaskOut:
                        return(false);

                    default:
                        throw new Exception($"无效的消息类型:{msg}");
                    }
                });

                // 模块已停止
                MessagePipe.ClearAllMessage(task);
                if (!result)
                {
                    MessageBox.Show("一个或多个模块未能成功停止,请检查。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                DisableAllItems();
            }

            // 启动模块
            if (StartupModels(Models))
            {
                if (Models.Any(item => item.CurDevName == ""))
                {
                    return;
                }
                MessageBox.Show("所有模块均已成功设置。", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                EnableAllItems();
            }
            else
            {
                MessageBox.Show("一个或多个模块未能成功初始化,请检查。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #10
0
        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            MessagePipe.RemoveListner("FormMain");

            if (textBoxRootFolder.Text != defaultRootPath)
            {
                Settings.Default.RootFolder = textBoxRootFolder.Text;
                Settings.Default.Save();
            }
        }
Пример #11
0
        /// <summary>
        /// 创建或更新一个VPN连接(指定VPN名称,及IP)
        /// </summary>
        /// <param name="updateVPNname">更新vpn名称</param>
        /// <param name="updateVPNip">更新VPN地址</param>
        /// <returns>操作成功:true,操作失败:false</returns>
        public bool CreateOrUpdateVPN(string updateVPNname, string updateVPNip)
        {
            bool     result    = true;
            DateTime startTime = DateTime.Now;
            string   msg       = string.Empty;

            try
            {
                RasDialer    dialer            = new RasDialer();
                RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
                allUsersPhoneBook.Open();

                // 如果已经该名称的VPN已经存在,则更新这个VPN服务器地址
                if (allUsersPhoneBook.Entries.Contains(updateVPNname))
                {
                    allUsersPhoneBook.Entries[updateVPNname].PhoneNumber = updateVPNip;
                    ////不管当前VPN是否连接,服务器地址的更新总能成功,如果正在连接,则需要VPN重启后才能起作用
                    bool updateResult = allUsersPhoneBook.Entries[updateVPNname].Update();
                    msg = "更新VPN服务器通道为:" + updateVPNip;
                    if (updateResult)
                    {
                        MessagePipe.ExcuteWriteMessageEvent(msg + "成功", Color.Green, false);
                    }
                    else
                    {
                        MessagePipe.ExcuteWriteMessageEvent(msg + "失败", Color.Green, false);
                    }
                }
                else
                {
                    ////创建一个新VPN
                    RasEntry entry = RasEntry.CreateVpnEntry(updateVPNname, updateVPNip, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

                    allUsersPhoneBook.Entries.Add(entry);
                    dialer.EntryName = updateVPNname;

                    dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
                    msg = "新建VPN通道:" + updateVPNip + "成功";
                    MessagePipe.ExcuteWriteMessageEvent(msg, Color.Green, false);
                }
            }
            catch (Exception ex)
            {
                result = false;
                MessagePipe.ExcuteWriteMessageEvent("更新或创建VPN通道异常:" + ex.Message.ToString(), Color.Green, true);
            }
            finally
            {
                ////记录交互日志
                string request = "VPN通道名称:" + updateVPNname + ";VPN账号:" + this.userName + ";VPN地址:" + updateVPNip;
                RecordLog.RecordInteractionLog(updateVPNname, "创建VPN通道", request, msg, DateTime.Now.Subtract(startTime), updateVPNip);
            }

            return(result);
        }
Пример #12
0
        internal Session(SessionManager manager, IIdentity user, string id, Interpreter interpreter, string commandLineArguments, ILogger sessionLogger, ILogger messageLogger)
        {
            Manager              = manager;
            Interpreter          = interpreter;
            User                 = user;
            Id                   = id;
            CommandLineArguments = commandLineArguments;
            _sessionLogger       = sessionLogger;

            _pipe = new MessagePipe(messageLogger);
        }
Пример #13
0
 /// <summary>
 ///     取消按钮单击事件。
 /// </summary>
 /// <param name="sender">触发事件的控件对象。</param>
 /// <param name="e">事件的参数。</param>
 private void CancelButton_Click(object sender, EventArgs e)
 {
     if (this.GetNextOutMessage(_task) != Message.NoAvailableMessage)
     {
         Close();
     }
     else
     {
         MessagePipe.SendOutMessage(new KeyValuePair <Message, Thread>(Message.UserCancel, _task));
         Close();
     }
 }
Пример #14
0
        /// <summary>
        ///     Deletes an entity by its key.
        /// </summary>
        /// <param name="key">The id of the entity to delete.</param>
        /// <param name="db">The unit of work instance to work against.</param>
        public virtual void RemoveById(TKey key, IUnitOfWorkLinq <TEntity, TKey> db)
        {
            Guard.ArgumentNotNull(db, nameof(db));

            // assume db session is open
            OnBeforeDelete(key);

            db.EntitySet.Writer.DeleteById(key);

            OnBeforeDeleteCommit(db, key);

            MessagePipe.SendAsync(new ItemDeleted <TEntity, TKey>(key));
        }
Пример #15
0
 MouseManager()
 {
     __selectedShapes = new List <AbstractShape>();
     __lastPoint      = PressedPoint = PointF.Empty;
     //ENTERING_SHAPE = new Cursor(Cursors.Arrow.CopyHandle());
     //MOVING_SHAPE = new Cursor(Cursors.SizeAll.CopyHandle());
     //DRAGGING = new Cursor(Cursors.Hand.CopyHandle());
     //ZOOM_IN = new Cursor(Cursors.Cross.CopyHandle());
     //ZOOM_OUT = new Cursor(Cursors.Cross.CopyHandle());
     //__cur = DEFAULT = new Cursor(Cursors.Arrow.CopyHandle());
     __state          = StateManager.Normal;
     __messagePipe    = new MessagePipe(this);
     PropertyChanged += MouseManager_PropertyChanged;
 }
Пример #16
0
        public void StartHost(SecureString password, ILogger outputLogger, ILogger messageLogger)
        {
            string brokerPath   = Path.GetDirectoryName(typeof(Program).Assembly.GetAssemblyPath());
            string rhostExePath = Path.Combine(brokerPath, RHostExe);

            var psi = new ProcessStartInfo(rhostExePath)
            {
                UseShellExecute        = false,
                CreateNoWindow         = false,
                Arguments              = $"--rhost-name \"{Id}\" {CommandLineArguments}",
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            };

            var shortHome = new StringBuilder(NativeMethods.MAX_PATH);

            NativeMethods.GetShortPathName(Interpreter.Info.Path, shortHome, shortHome.Capacity);
            psi.EnvironmentVariables["R_HOME"] = shortHome.ToString();
            psi.EnvironmentVariables["PATH"]   = Interpreter.Info.BinPath + ";" + Environment.GetEnvironmentVariable("PATH");

            if (password != null)
            {
                psi.UserName = User.Name;
                psi.Password = password;
            }

            _process = new Process {
                StartInfo           = psi,
                EnableRaisingEvents = true,
            };

            _process.ErrorDataReceived += (sender, e) => {
                var process = (Process)sender;
                outputLogger?.LogTrace($"|{process.Id}|: {e.Data}");
            };

            _process.Exited += delegate {
                _pipe = null;
            };

            _process.Start();
            _process.BeginErrorReadLine();

            _pipe = new MessagePipe(messageLogger);
            var hostEnd = _pipe.ConnectHost(_process.Id);

            ClientToHostWorker(_process.StandardInput.BaseStream, hostEnd).DoNotWait();
            HostToClientWorker(_process.StandardOutput.BaseStream, hostEnd).DoNotWait();
        }
Пример #17
0
        private void FormMain_Load(object sender, EventArgs e)
        {
            MessagePipe.AddListner(UpdateLog, listnerKey: "FormMain");
            defaultRootPath        = Settings.Default.RootFolder.NullIfEmpty();
            textBoxRootFolder.Text = defaultRootPath;

            txnListView.BeforeCreatingGroups += txnListView_BeforeCreatingGroups;

            if (appState == null)
            {
                var repository = new FileRepository(defaultRootPath);
                appState = new AppState(repository);
            }
        }
Пример #18
0
        /// <summary>
        /// 调用IP监控组件
        /// </summary>
        /// <returns>返回true,Ip被限。返回false,IP没有被限制</returns>
        private bool InvokeIpMonitor()
        {
            bool result = false;

            while (true && !SignalControl.Issuspend)
            {
                double sleepTime = 5;
                try
                {
                    ////取监控间隔时间
                    string intervatTime = SysParamHelper.GetParamById <string>("ITZC_YW_CheckIPLockedIntervalTime", "xxxxx");
                    if (intervatTime == "xxxxx")
                    {
                        intervatTime = "5";
                    }

                    sleepTime = Convert.ToDouble(intervatTime);
                    MessagePipe.ExcuteWriteMessageEvent("开始调用监控组件,调用过后睡" + sleepTime + "分钟", Color.Red, false);
                    //////调用监控组件
                    MatchIpLimitRule iplimit = new MatchIpLimitRule();
                    result = iplimit.IslimitIp();

                    ////如果发现需要替换IP,并且距离上一次替换的时间间隔大于2分钟
                    if (result)
                    {
                        if (DateTime.Now.Subtract(this.replaceIpTime).Minutes > 2)
                        {
                            MessagePipe.ExcuteWriteMessageEvent("检测到IP:" + VpnServer.Address + "被限", Color.Red, true);
                            this.replaceIpTime = DateTime.Now;
                            break;
                        }
                        else
                        {
                            MessagePipe.ExcuteWriteMessageEvent("检测到IP被限,但距离上次替换时间间隔不到2分钟,暂不替换", Color.Red, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessagePipe.ExcuteWriteMessageEvent("调用监控组件异常" + ex.Message.ToString(), Color.Red, true);
                }
                finally
                {
                    Thread.Sleep(TimeSpan.FromMinutes(sleepTime));
                }
            }

            return(result);
        }
Пример #19
0
        /// <summary>
        ///     Updates a given entity against a given unit of work.
        /// </summary>
        /// <remarks>
        ///     Caller must control commits to the given unit of work.
        /// </remarks>
        /// <param name="entity">The entity to update.</param>
        /// <param name="db">The unit of work instance to work against.</param>
        public virtual void Update(TEntity entity, IUnitOfWorkLinq <TEntity, TKey> db)
        {
            Guard.ArgumentNotNull(entity, nameof(entity));
            Guard.ArgumentNotNull(db, nameof(db));

            //validate business logic
            DemandValid(entity);

            OnBeforeUpdate(entity);

            db.EntitySet.Writer.Update(entity);

            MessagePipe
            .SendAsync(new ItemUpdated <TEntity>(entity));
        }
Пример #20
0
        /// <summary>
        /// 获取一个关键词
        /// </summary>
        /// <returns>返回关键词</returns>
        private string GetOneKeyWord()
        {
            string result = string.Empty;

            if (keywordsList != null && keywordsList.Count > 0)
            {
                result = keywordsList[0];
                keywordsList.RemoveAt(0);
            }
            else
            {
                MessagePipe.ExcuteWriteMessageEvent("处理完成", 0);
            }

            return(result);
        }
Пример #21
0
        /// <summary>
        /// 获取当前正在连接中的VPN名称
        /// </summary>
        /// <returns>返回当前连接的VPN名称</returns>
        public List <string> GetCurrentConnectingVPNNames()
        {
            List <string> connectingVPNList = new List <string>();

            try
            {
                Process proIP = new Process();

                proIP.StartInfo.FileName               = "cmd.exe ";
                proIP.StartInfo.UseShellExecute        = false;
                proIP.StartInfo.RedirectStandardInput  = true;
                proIP.StartInfo.RedirectStandardOutput = true;
                proIP.StartInfo.RedirectStandardError  = true;
                ////不显示cmd窗口
                proIP.StartInfo.CreateNoWindow = true;
                proIP.Start();

                proIP.StandardInput.WriteLine(rasDialFileName);
                proIP.StandardInput.WriteLine("exit");

                // 命令行运行结果
                string strResult = proIP.StandardOutput.ReadToEnd();
                proIP.Close();

                Regex regger = new Regex("(?<=已连接\r\n)(.*\n)*(?=命令已完成)", RegexOptions.Multiline);

                // 如果匹配,则说有正在连接的VPN
                if (regger.IsMatch(strResult))
                {
                    string[] list = regger.Match(strResult).Value.ToString().Split('\n');
                    for (int index = 0; index < list.Length; index++)
                    {
                        if (list[index] != string.Empty)
                        {
                            connectingVPNList.Add(list[index].Replace("\r", string.Empty));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessagePipe.ExcuteWriteMessageEvent("获取正在连接的VPN异常:" + ex.Message.ToString(), Color.Red, true);
            }

            // 没有正在连接的VPN,则直接返回一个空List<string>
            return(connectingVPNList);
        }
Пример #22
0
        /// <summary>
        /// 抽象图元基类构造函数
        /// </summary>
        protected AbstractPrimitive()
        {
            UUID = Guid.NewGuid().ToString();

            border = new BorderPattern();
            border.PropertyChanged += PropertyChangedEvent;

            fillPattern = new FillPattern.None();
            fillPattern.PropertyChanged += PropertyChangedEvent;

            PropertyChanged += PropertyChangedEvent;


            IsPropertyChanged = true;
            Layer             = null;
            __messagePipe     = new MessagePipe(this);
        }
Пример #23
0
        protected bool disposedValue = false; // 要检测冗余调用


        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    __messagePipe.Dispose();
                    fillPattern.Dispose();
                    border.Dispose();
                }

                Layer           = null;
                __messagePipe   = null;
                PropertyChanged = null;
                disposedValue   = true;
            }
        }
Пример #24
0
        /// <summary>
        /// 保存日志按钮
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void ToolItemSaveLog_Click(object sender, EventArgs e)
        {
            ////利用SaveFileDialog,让用户指定文件的路径名
            SaveFileDialog saveDlg = new SaveFileDialog();

            saveDlg.Filter = "文本文件|*.txt";
            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                FileStream   fs = null;
                StreamWriter sw = null;
                try
                {
                    // 创建文件,将textBox1中的内容保存到文件中
                    // saveDlg.FileName 是用户指定的文件路径
                    fs = File.Open(saveDlg.FileName, FileMode.Create, FileAccess.Write);
                    sw = new StreamWriter(fs);
                    List <string> recordStr = WorkingLog.LogStr.ToString().Split(Environment.NewLine.ToCharArray()).ToList();
                    foreach (string line in recordStr)
                    {
                        sw.WriteLine(line);
                    }
                }
                catch (Exception ex)
                {
                    MessagePipe.ExcuteWriteMessageEvent("保存日志文件失败" + ex.Message.ToString(), Color.Red, false);
                }
                finally
                {
                    if (sw != null)
                    {
                        ////关闭文件
                        sw.Flush();
                        sw.Close();
                    }

                    if (fs != null)
                    {
                        fs.Close();
                    }
                }

                ////提示用户:文件保存的位置和文件名
                MessageBox.Show("文件已成功保存到" + saveDlg.FileName);
            }
        }
Пример #25
0
        public void Save(ILocation location, TransactionEdits transactions, ILocation auxilaryComponentLocation = null)
        {
            if (this.Exists(location))
            {
                //Create backup
                var existingFileDateTime = File.GetLastWriteTimeUtc(location.Address);
                var newSuffix            = existingFileDateTime.ToString("yyyyMMddHHmmssffff");
                var ext             = Path.GetExtension(location.Address);
                var archiveFilePath = Path.ChangeExtension(location.Address, string.Concat(newSuffix, ".", ext));
                File.Copy(location.Address, archiveFilePath);
            }

            var serializedData = transactions.SerializeToJson();

            File.WriteAllText(location.Address, serializedData);

            MessagePipe.SendMessage("Saved {0}".FormatEx(location.Address));
        }
Пример #26
0
        /// <summary>
        /// 尝试连接VPN(指定VPN名称,用户名,密码)
        /// </summary>
        /// <param name="connVpnName">vpn名称</param>
        /// <param name="connUserName">连接的用户名称</param>
        /// <param name="connPassWord">连接的密码</param>
        /// <returns>连接成功true,连接失败false</returns>
        public bool TryConnectVPN(string connVpnName, string connUserName, string connPassWord)
        {
            bool     result    = false;
            DateTime startTime = DateTime.Now;
            string   linkInfo  = string.Empty;

            try
            {
                string args = string.Format("{0} {1} {2}", connVpnName, connUserName, SecurityUtility.DecryptString(connPassWord));

                ProcessStartInfo myProcess = new ProcessStartInfo(this.vpnProcess, args);

                myProcess.CreateNoWindow = true;

                myProcess.UseShellExecute        = false;
                myProcess.RedirectStandardOutput = true;
                var excuteResult = Process.Start(myProcess);
                linkInfo = excuteResult.StandardOutput.ReadToEnd();
                linkInfo = linkInfo.Replace("\n", string.Empty);
                if (linkInfo.Contains("已连接"))
                {
                    result = true;
                }
                else
                {
                    MessagePipe.ExcuteWriteMessageEvent("登陆失败,账号:" + connUserName + "密码:" + SecurityUtility.EncryptDES(connPassWord) + "VPN服务器:" + this.vpnIP, Color.Green, true);
                }

                MessagePipe.ExcuteWriteMessageEvent(connVpnName + "登陆验证结果:" + linkInfo, Color.Green, false);
            }
            catch (Exception ex)
            {
                string msg = "登陆异常,账号:" + connUserName + "密码:" + SecurityUtility.EncryptDES(connPassWord) + "VPN服务器:" + this.vpnIP;
                LogManager.Log.WriteException(new AppException(msg, ex, ExceptionLevel.Info));
            }
            finally
            {
                ////记录交互日志
                string request = "VPN通道名称:" + connVpnName + ";VPN账号:" + connUserName;
                RecordLog.RecordInteractionLog(connUserName, "通过用账号和密码登陆", request, linkInfo, DateTime.Now.Subtract(startTime), this.vpnIP);
            }

            return(result);
        }
        private Process StartProcessWithRequest(AgentRequest request, string workingDirectory)
        {
            var agentPath = request.GetType().Assembly.Location;


            var startInfo = new ProcessStartInfo(agentPath)
            {
                WorkingDirectory       = workingDirectory,
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                RedirectStandardInput  = true,
                CreateNoWindow         = true
            };

            using (var activationDirectory = new WorkingDirectory())
            {
                startInfo.EnvironmentVariables["COMPLUS_ApplicationMigrationRuntimeActivationConfigPath"] = activationDirectory.DirectoryInfo.FullName;
                if (_clrVersion == ClrVersion.Version4)
                {
                    var configPath = Path.Combine(activationDirectory.DirectoryInfo.FullName, string.Concat(Path.GetFileName(agentPath), ".activation_config"));
                    File.WriteAllText(configPath, ClrVersion4ActivationConfigContent);
                }

                var namedPipeName = string.Format("{0}.{1}", GetType().FullName, Guid.NewGuid());
                startInfo.Arguments = namedPipeName;
                using (var pipeServer = new NamedPipeServerStream(namedPipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
                {
                    var messagePipe = new MessagePipe(pipeServer);

                    var ar = pipeServer.BeginWaitForConnection(null, pipeServer);

                    var process = Process.Start(startInfo);

                    pipeServer.EndWaitForConnection(ar);

                    messagePipe.WriteMessage(request);

                    pipeServer.WaitForPipeDrain();

                    return(process);
                }
            }
        }
Пример #28
0
        /// <inheritdoc />
        /// <summary>
        ///     初始化 <see cref="MainPart" /> 窗口。
        /// </summary>
        public MainPart()
        {
            // 初始化模块
            TaskHandler.Init();
            var task = new Thread(load => {
                try {
                    // TODO:新增模块时请更新此处的代码
                    var threads = new[] {
                        new Thread(init => { Scanner = new Scanner(); }),
                        new Thread(init => { Poisoner = new Poisoner(); }),
                        new Thread(init => { Watcher = new Watcher(); })
                    };
                    foreach (var thread in threads)
                    {
                        thread.Start();
                    }
                    new WaitTimeoutChecker(30000).ThreadSleep(500, () => threads.Any(item => item.IsAlive));
                }
                catch (ThreadAbortException) {
                    Environment.Exit(-1);
                }
            })
            {
                Name = RegisteredThreadName.ProgramInit.ToString()
            };

            MessagePipe.SendInMessage(new KeyValuePair <Message, Thread>(Message.TaskIn, task));
            var loading = new Loading("初始化中,请稍候", task);

            loading.ShowDialog();

            // 用户取消
            if (MessagePipe.GetNextOutMessage(task) == Message.UserCancel)
            {
                Environment.Exit(-1);
            }

            // 初始化完成(由loading判断得到)
            MessagePipe.ClearAllMessage(task);

            TopMost = true;
            InitializeComponent();
        }
Пример #29
0
        /// <summary>
        /// 执行
        /// </summary>
        private void Excute()
        {
            ////调用一个方法取一条
            keyword = this.GetOneKeyWord();
            if (!string.IsNullOrEmpty(keyword))
            {
                MessagePipe.ExcuteWriteMessageEvent("开始处理关键词【" + keyword + "】", 0);

                string tempword = System.Web.HttpUtility.UrlEncode(keyword, System.Text.Encoding.GetEncoding("GB2312"));
                tempword = tempword.ToUpper();
                string url = string.Format("http://index.baidu.com/?tpl=crowd&word={0}", tempword);
                this.webBrowser1.Navigate(url);
                //this.webBrowser1.Document.GetElementById("schword").SetAttribute("value", keyword);
                //this.webBrowser1.Document.GetElementById("schsubmit").InvokeMember("click");

                Fiddler.FiddlerApplication.SetAppDisplayName("FiddlerCoreDemoApp");
                FiddlerApplication.Startup(7777, FiddlerCoreStartupFlags.Default);
                //FiddlerApplication.BeforeRequest += BeforeRequest;
                Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
                {
                    oS.bBufferResponse = true;
                    Monitor.Enter(oAllSessions);
                    oAllSessions.Add(oS);
                    Monitor.Exit(oAllSessions);
                    oS["X-AutoAuth"] = "(default)";
                    if ((oS.oRequest.pipeClient.LocalPort == iSecureEndpointPort) && (oS.hostname == sSecureEndpointHostname))
                    {
                        oS.utilCreateResponseAndBypassServer();
                        oS.oResponse.headers.SetStatus(200, "Ok");
                        oS.oResponse["Content-Type"]  = "text/html; charset=UTF-8";
                        oS.oResponse["Cache-Control"] = "private, max-age=0";
                        oS.utilSetResponseBody("<html><body>Request for httpS://" + sSecureEndpointHostname + ":" + iSecureEndpointPort.ToString() + " received. Your request was:<br /><plaintext>" + oS.oRequest.headers.ToString());
                    }
                };
                FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;
                Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
                {
                    //Console.WriteLine("Finished session:\t" + oS.fullUrl);
                    //MessagePipe.ExcuteWriteMessageEvent ("Session list contains: " + oAllSessions.Count.ToString() + " sessions",0);
                };
            }
        }
Пример #30
0
 /// <summary>
 /// 删除指定名称的VPN
 /// 如果VPN正在运行,一样会在电话本里删除,但是不会断开连接,所以,最好是先断开连接,再进行删除操作
 /// </summary>
 /// <param name="delVpnName">待删除的VPN名称</param>
 public void TryDeleteVPN(string delVpnName)
 {
     if (!string.IsNullOrEmpty(delVpnName))
     {
         RasDialer    dialer            = new RasDialer();
         RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
         try
         {
             allUsersPhoneBook.Open();
             if (allUsersPhoneBook.Entries.Contains(delVpnName))
             {
                 allUsersPhoneBook.Entries.Remove(delVpnName);
             }
         }
         catch (Exception ex)
         {
             MessagePipe.ExcuteWriteMessageEvent("删除指定VPN名称异常:" + ex.Message.ToString(), Color.Green, true);
         }
     }
 }