Пример #1
0
        public static void WriteHeaderLines(string filePath, string settingName, PTMagicConfiguration systemConfiguration)
        {
            // Writing Header lines
            List <string> lines = File.ReadAllLines(filePath).ToList();

            lines.Insert(0, "");
            lines.Insert(0, "# ####################################");
            lines.Insert(0, "# PTMagic_LastChanged = " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString());
            lines.Insert(0, "# PTMagic_ActiveSetting = " + SystemHelper.StripBadCode(settingName, Constants.WhiteListProperties));
            lines.Insert(0, "# ####### PTMagic Current Setting ########");
            lines.Insert(0, "# ####################################");

            if (!systemConfiguration.GeneralSettings.Application.TestMode)
            {
                File.WriteAllLines(filePath, lines);
            }
        }
Пример #2
0
        private void Fnodeexportpdf_Click(object sender, EventArgs e)
        {
            NFileInfo tag = navigateTree.SelectedNode.Tag as NFileInfo;

            if ((tag != null) && FileHelper.IsImageExt(tag.FileName))
            {
                SaveFileDialog dialog = new SaveFileDialog
                {
                    FileName = tag.LocalPath + ".pdf"
                };
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    PDFHelper.Img2PDF(tag.LocalPath, dialog.FileName);
                    SystemHelper.ExplorerFile(dialog.FileName);
                }
            }
        }
Пример #3
0
        public static string Parse(Bitmap bitmap, string language, Rectangle rect)
        {
            //TesseractEngine tesseractEngine = new TesseractEngine("C:\\workspace\\space_imageclient\\SinoImage-Client\\DocScanner.Main\\bin\\Debug\\Tesseract\\tessdata", "eng", EngineMode.Default);
            //bitmap = new Bitmap("f:\\testimage\\number.jpg");
            //Rect region = new Rect(rect.X, rect.Y, rect.Width, rect.Height);
            string          datapath        = SystemHelper.GetAssemblesDirectory() + "tessdata";
            TesseractEngine tesseractEngine = new TesseractEngine(datapath, language.ToString(), EngineMode.Default);

            page = tesseractEngine.Process(bitmap);
            //Page page = tesseractEngine.Process(bitmap, Rect.FromCoords(rect.X, rect.Y, rect.Width, rect.Height));
            page.RegionOfInterest = Rect.FromCoords(rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height);
            //string a = page.GetText();
            //         Bitmap bitmap1 = ImageHelper.LoadCorectedImage("f:\\testimage\\number.jpg").ToBitmap();
            //         Page page = tesseractEngine.Process(bitmap);
            //Page page = tesseractEngine.Process(bitmap, Rect.FromCoords(rect.X, rect.Y, rect.Width, rect.Height));
            return(page.GetText());
        }
 public static void Del_Old(string batchno)
 {
     if (FunctionSetting.GetInstance().AllowLogUploaded)
     {
         UploadedBatchLogger localUploaded = UploadedBatchLogger.GetLocalUploaded();
         foreach (UploadedBatchInfo info in localUploaded.BatchNos)
         {
             if (info.BatchNo == batchno)
             {
                 localUploaded.BatchNos.RemoveAll(o => o.BatchNo == batchno);
                 string fname = SystemHelper.GetAssemblesDirectory() + _localuploadebatchsfname;
                 SerializeHelper.SerializeToXML <UploadedBatchLogger>(localUploaded, fname);
                 break;
             }
         }
     }
 }
        /// <summary>
        /// 查询软件配置信息
        /// </summary>
        /// <returns></returns>
        public void GetSoftWareCfg(out List <string> swConfigList, out List <DateTime> swConfigStoreTimeList)
        {
            swConfigList          = new List <string>();
            swConfigStoreTimeList = new List <DateTime>();
            string    strSql = "select content,updatetime from softwareconfig";
            DataTable dt     = _idbRead.ExecuteDataTable(strSql);

            if (dt == null || dt.Rows.Count == 0)
            {
                return;
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                swConfigList.Add((string)dt.Rows[i][0]);
                swConfigStoreTimeList.Add(SystemHelper.GetTimeByUtcTicks((long)dt.Rows[i][1]));
            }
        }
Пример #6
0
 static HistoryAutoRec()
 {
     //检查历史记录剩余空间
     Task.Run(() =>
     {
         while (true)
         {
             try
             {
                 using (SysDB db = new SysDB())
                 {
                     var info = (from m in db.SystemSetting
                                 select new { path = m.HistoryPath, g = m.HistoryStoreAlarm }).FirstOrDefault();
                     if (info == null || string.IsNullOrEmpty(info.path) || info.path.Length < 2 || info.g == null || info.g == 0 || info.path[1] != ':')
                     {
                         continue;
                     }
                     System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
                     foreach (System.IO.DriveInfo drive in drives)
                     {
                         if (drive.Name.ToLower()[0] == info.path.ToLower()[0])
                         {
                             var gb = Math.Round(drive.TotalFreeSpace / (double)(1024 * 1024 * 1024), 2);
                             if (gb <= info.g.GetValueOrDefault())
                             {
                                 SystemHelper.AddAlarm(new Alarm()
                                 {
                                     Content = $"历史路径{info.path}剩余空间只有{gb}GB了,请尽快扩展磁盘!",
                                 });
                             }
                             break;
                         }
                     }
                 }
             }
             catch (Exception ex)
             {
                 using (Way.Lib.CLog log = new Way.Lib.CLog("HistoryAutoRec 检查磁盘剩余空间 error "))
                 {
                     log.Log(ex.ToString());
                 }
             }
             Thread.Sleep(1000 * 60);
         }
     });
 }
Пример #7
0
 /// <summary>
 /// 断开连接
 /// </summary>
 public void Disconnect()
 {
     new Thread(() =>
     {
         while (!_mainProcess.HasExited)
         {
             try
             {
                 Input("exit");
                 Thread.Sleep(100);
             }
             catch { }
         }
         SystemHelper.KillProcessAndChildrens(_mainProcess.Id);
         IsConnect = false;
     }).Start();
 }
Пример #8
0
        /// <summary>
        /// 创建根节点对象
        /// </summary>
        /// <param name="xmlFilePath">Xml文件的相对路径</param>
        private static XmlElement CreateRootElement(string xmlFilePath)
        {
            //定义变量,表示XML文件的绝对路径
            string filePath = "";

            //获取XML文件的绝对路径
            filePath = SystemHelper.GetRootPath(xmlFilePath);

            //创建XmlDocument对象
            XmlDocument xmlDocument = new XmlDocument();

            //加载XML文件
            xmlDocument.Load(filePath);

            //返回根节点
            return(xmlDocument.DocumentElement);
        }
Пример #9
0
        public static void ExecuteMuteRecipe(bool doMute)
        {
            var muteRecipe = Repository.Instance.GetRecipe("Mute");

            if (muteRecipe != null && muteRecipe.IsAvailable && muteRecipe.IsEnabled)
            {
                if (doMute && !SystemHelper.IsMute())
                {
                    SystemHelper.Mute();
                }

                if (!doMute && SystemHelper.IsMute())
                {
                    SystemHelper.Mute();
                }
            }
        }
Пример #10
0
    private static void EnableBlur(Window window, bool isEnabled)
    {
        var versionInfo = SystemHelper.GetSystemVersionInfo();

        var accentPolicy     = new InteropValues.ACCENTPOLICY();
        var accentPolicySize = Marshal.SizeOf(accentPolicy);

        accentPolicy.AccentFlags = 2;

        if (isEnabled)
        {
            if (versionInfo >= SystemVersionInfo.Windows10_1809)
            {
                accentPolicy.AccentState = InteropValues.ACCENTSTATE.ACCENT_ENABLE_ACRYLICBLURBEHIND;
            }
            else if (versionInfo >= SystemVersionInfo.Windows10)
            {
                accentPolicy.AccentState = InteropValues.ACCENTSTATE.ACCENT_ENABLE_BLURBEHIND;
            }
            else
            {
                accentPolicy.AccentState = InteropValues.ACCENTSTATE.ACCENT_ENABLE_TRANSPARENTGRADIENT;
            }
        }
        else
        {
            accentPolicy.AccentState = InteropValues.ACCENTSTATE.ACCENT_ENABLE_BLURBEHIND;
        }

        accentPolicy.GradientColor = ResourceHelper.GetResource <uint>(ResourceToken.BlurGradientValue);

        var accentPtr = Marshal.AllocHGlobal(accentPolicySize);

        Marshal.StructureToPtr(accentPolicy, accentPtr, false);

        var data = new InteropValues.WINCOMPATTRDATA
        {
            Attribute = InteropValues.WINDOWCOMPOSITIONATTRIB.WCA_ACCENT_POLICY,
            DataSize  = accentPolicySize,
            Data      = accentPtr
        };

        InteropMethods.Gdip.SetWindowCompositionAttribute(window.GetHandle(), ref data);

        Marshal.FreeHGlobal(accentPtr);
    }
Пример #11
0
        private void Execute(ISender client, GetSystemInfo message)
        {
            try
            {
                IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();

                var domainName = (!string.IsNullOrEmpty(properties.DomainName)) ? properties.DomainName : "-";
                var hostName   = (!string.IsNullOrEmpty(properties.HostName)) ? properties.HostName : "-";

                var geoInfo     = GeoInformationFactory.GetGeoInformation();
                var userAccount = new UserAccount();

                List <Tuple <string, string> > lstInfos = new List <Tuple <string, string> >
                {
                    new Tuple <string, string>("Processor (CPU)", HardwareDevices.CpuName),
                    new Tuple <string, string>("Memory (RAM)", $"{HardwareDevices.TotalPhysicalMemory} MB"),
                    new Tuple <string, string>("Video Card (GPU)", HardwareDevices.GpuName),
                    new Tuple <string, string>("Username", userAccount.UserName),
                    new Tuple <string, string>("PC Name", SystemHelper.GetPcName()),
                    new Tuple <string, string>("Domain Name", domainName),
                    new Tuple <string, string>("Host Name", hostName),
                    new Tuple <string, string>("System Drive", Path.GetPathRoot(Environment.SystemDirectory)),
                    new Tuple <string, string>("System Directory", Environment.SystemDirectory),
                    new Tuple <string, string>("Uptime", SystemHelper.GetUptime()),
                    new Tuple <string, string>("MAC Address", HardwareDevices.MacAddress),
                    new Tuple <string, string>("LAN IP Address", HardwareDevices.LanIpAddress),
                    new Tuple <string, string>("WAN IPv4 Address", geoInfo.IPv4Address),
                    new Tuple <string, string>("WAN IPv6 Address", geoInfo.IPv6Address),
                    new Tuple <string, string>("ASN", geoInfo.Asn),
                    new Tuple <string, string>("ISP", geoInfo.Isp),
                    new Tuple <string, string>("Antivirus", SystemHelper.GetAntivirus()),
                    new Tuple <string, string>("Firewall", SystemHelper.GetFirewall()),
                    new Tuple <string, string>("Time Zone", geoInfo.Timezone),
                    new Tuple <string, string>("Country", geoInfo.Country)
                };

                client.Send(new GetSystemInfoResponse {
                    SystemInfos = lstInfos
                });
            }
            catch (Exception)
            {
                //cant get
            }
        }
Пример #12
0
        //保存修改
        private void BtnModify_Click(object sender, EventArgs e)
        {
            DialogResult result = DialogResult.OK;

            if (!Alading.Utils.SystemHelper.CompareTimeStamp(_orderTimeStamp as byte[], _tradeStock.OrderTimeStamp))
            {
                result = XtraMessageBox.Show("当前订单已经被修改,继续修改(OK)/查看流程信息(Canel)", "订单修改", MessageBoxButtons.OKCancel);
            }
            if (result == DialogResult.OK)
            {
                string     skuProsName = cmbProperties.Text.ToString();//取得选中sku_pros
                TradeOrder order       = TradeOrderService.GetTradeOrder(p => p.TradeOrderCode == _tradeStock.TradeOrderCode).FirstOrDefault();

                if (order.sku_properties_name != skuProsName) //的的确确修改订单信息才提交笔生成流程信息
                {
                    //创建一条交易信息
                    string flowMeassge = "商品\"" + _tradeStock.title + "\"销售属性修改:" + order.sku_properties_name + "-->" + skuProsName;
                    SystemHelper.CreateFlowMessage(_tradeStock.CustomTid, "订单信息修改", flowMeassge, "订单管理");
                    order.sku_properties_name = skuProsName;

                    #region  保存修改信息到数据库和并同步到淘宝
                    WaitDialogForm wdf = new WaitDialogForm(Alading.Taobao.Constants.OPERATE_TBDB_DATA);
                    try
                    {
                        UpdateTaobaoOrder();
                        TradeOrderService.UpdateTradeOrder(order);
                        wdf.Close();
                        XtraMessageBox.Show("修改订单信息成功!");
                    }
                    catch (Exception ex)
                    {
                        wdf.Close();
                        XtraMessageBox.Show("将修改信息保存到淘宝失败,修改无效!原因:" + ex.Message);
                    }
                    #endregion
                }
                else
                {
                    result = DialogResult.Ignore; //实际什么都没做,不需要更新数据库时间戳
                }
            }
            //如果在主界面接受到的结果为Dialog.Canel,则跳转流程信息页面。如果是Dialog.OK则修改界面信息,Dialog.Ignore不做
            this.DialogResult = result;
            this.Close();
        }
Пример #13
0
        public void AscomSubKeys()
        {
            SystemHelper sys = new SystemHelper();

            Console.WriteLine($"ASCOM platform SubKeys");
            AscomPlatformNode ascom = sys.Ascom;

            Console.WriteLine($"ASCOM System Node: {sys.System}");
            Console.WriteLine($"ASCOM Root Node: {ascom.ProfileNodeId}");
            IOrderedEnumerable <string> vals = sys.SubKeys(ascom.ProfileNodeId, true);

            foreach (var path in vals)
            {
                Console.Write($"[{path}]\t");
                string val = sys.ValueByPath(sys.Ascom, path);
                Console.WriteLine($"'{val}'");
            }
        }
Пример #14
0
        public virtual bool VisualizeGraph(string path, string file)
        {
            var rfs = (new Random()).Next();
            var s   = VisualizeGraph();
            var r   = new StreamWriter(path + "\\" + rfs + ".dot");

            r.Write(s);
            r.Close();

            var proc = SystemHelper.StartProcess(
                "dot.exe",
                " -Tjpg " + path + "\\" + rfs + ".dot" + " -o " + path + "\\" + file + ".jpg",
                true,
                "");

            proc.WaitForExit();
            return(proc.ExitCode == 0);
        }
Пример #15
0
        public int WriteWindowCode(int windowid, string windowCode, string filecontent)
        {
            ControlWindow window = null;

            if (!string.IsNullOrEmpty(windowCode))
            {
                window = this.db.ControlWindow.FirstOrDefault(m => m.Code == windowCode);
            }
            else
            {
                window = this.db.ControlWindow.FirstOrDefault(m => m.id == windowid);
            }

            SystemHelper.AddSysLog(this.User.id.Value, "修改监控窗口:" + window.Name);

            System.IO.File.WriteAllText(Way.Lib.PlatformHelper.GetAppDirectory() + "windows/" + window.FilePath, filecontent, System.Text.Encoding.UTF8);
            return(0);
        }
Пример #16
0
        /// <summary>
        /// Crop an image on disk.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="croppingRect"></param>
        public static void CropImageFileOnDisk(string path, Rectangle croppingRect)
        {
            string tempPath;

            using (var img = LoadImage(path))
            {
                using (var croppedImage = CropImage(img, croppingRect))
                {
                    var tempStub = RandomHelper.GetRandomAlphanumericString(16);

                    tempPath = SystemHelper.GetSimilarlyExtensionedNeighborFilePath(path, tempStub);                     //Can't save image on top of itself

                    croppedImage.Save(tempPath);
                }
            }

            SystemHelper.ReplaceFile(tempPath, path);
        }
Пример #17
0
        private static void RunWithIndependentProfile(string path)
        {
            path = SystemHelper.EnsureAbsolutePath(path);

            var conf = path + ".le.config";

            if (!File.Exists(conf))
            {
                Process.Start(
                    Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "LEGUI.exe"),
                    $"\"{path}.le.config\"");
            }
            else
            {
                var profile = LEConfig.GetProfiles(conf)[0];
                DoRunWithLEProfile(path, 2, profile);
            }
        }
Пример #18
0
    /// <summary>
    /// Restart webfarm.
    /// </summary>
    protected void RestartWebfarm(object sender = null, EventArgs args = null)
    {
        if (StopProcessing)
        {
            return;
        }

        // Restart current server
        SystemHelper.RestartApplication(Request.PhysicalApplicationPath);

        // Log event
        EventLogProvider.LogEvent(EventType.INFORMATION, "System", "RESTARTWEBFARM", GetString("Administration-System.WebframRestarted"));

        string url = URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, "lastaction", "WebfarmRestarted");

        url = URLHelper.UpdateParameterInUrl(url, "restartedhash", ValidationHelper.GetHashString("WebfarmRestarted"));
        URLHelper.Redirect(url);
    }
Пример #19
0
        public static void Start(string[] args)
        {
            var filepath = args.Length switch
            {
                0 => throw new TooFewArgumentsException(message: "Please provide path to .csv file"),
                      1 => args[0],
                      _ => throw new TooManyArgumentsException(message: "Please only provide one argument.")
            };

            if (!SystemHelper.IsCsv(filepath))
            {
                throw new WrongFileTypeException(message: "Please provide a .csv file");
            }

            using var reader = new StreamReader(filepath);
            ParseRainBom.Parse(reader);
        }
    }
Пример #20
0
        /// <summary>
        /// 执行检查
        /// </summary>
        public static void Perform()
        {
            Type attributeType = typeof(FaultCodeAttribute);
            var  duplicate     = SystemHelper.LoadAppAssemblies()
                                 .SelectMany(m => m.GetTypes().Where(t => t.IsDefined(attributeType, false)))
                                 .Select(m =>
            {
                return(m.GetCustomAttribute <FaultCodeAttribute>());
            })
                                 .GroupBy(f => f.Name)
                                 .Where(g => g.Count() > 1)
                                 .Select(g => g.ElementAt(0));

            if (duplicate.Count() > 0)
            {
                throw new InvalidOperationException(string.Format("FaultCode {0} 已经被使用过,请重新设置一个新的FaultCode。", duplicate.FirstOrDefault().Name));
            }
        }
Пример #21
0
    /// <summary>
    /// Restart webfarm.
    /// </summary>
    protected void RestartWebfarm(object sender = null, EventArgs args = null)
    {
        if (StopProcessing)
        {
            return;
        }

        // Restart current server
        SystemHelper.RestartApplication();

        // Log event
        Service.Resolve <IEventLogService>().LogInformation("System", "RESTARTWEBFARM", GetString("Administration-System.WebframRestarted"));

        string url = URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, "lastaction", "WebfarmRestarted");

        url = URLHelper.UpdateParameterInUrl(url, "restartedhash", ValidationHelper.GetHashString("WebfarmRestarted", new HashSettings("")));
        URLHelper.Redirect(url);
    }
Пример #22
0
        public ActionResult CommentToAnswer(int answerId, string context)
        {
            var answer = SystemHelper.getAnswerById(answerId);
            var userId = User.Identity.GetUserId();

            if (context != "")
            {
                SystemHelper.addCommentToAnswer(context, answerId, userId);
                return(RedirectToAction("AuthorizeUserPage", "Home"));
            }
            else
            {
                ViewBag.formError   = "Please Fill Comment Box";
                ViewBag.userName    = SystemHelper.getUserNameByAnswerId(answerId);
                ViewBag.description = answer.Context;
                return(View("CommentToAnswer"));
            }
        }
Пример #23
0
        private Dictionary <string, object> GetProfitTrailerProperties(List <string> formKeys, string sFormKey, string propertyType)
        {
            Dictionary <string, object> result = new Dictionary <string, object>();

            List <string> globalSettingPairsPropertiesFormKeys = formKeys.FindAll(k => k.StartsWith(sFormKey + propertyType + "Property_") && k.IndexOf("|Value") == -1);

            foreach (string globalSettingPairsFormKey in globalSettingPairsPropertiesFormKeys)
            {
                string originalKeySimplified = globalSettingPairsFormKey.Replace(sFormKey + propertyType + "Property_", "");
                string propertyFormKey       = sFormKey + propertyType + "Property_" + originalKeySimplified;

                for (int f = 0; f < HttpContext.Request.Form[propertyFormKey].Count; f++)
                {
                    string propertyKey         = HttpContext.Request.Form[propertyFormKey][f] + HttpContext.Request.Form[propertyFormKey + "|ValueMode"][f];
                    string propertyValueString = HttpContext.Request.Form[propertyFormKey + "|Value"][f];

                    object propertyValue = new object();
                    if (propertyValueString.Equals("true", StringComparison.InvariantCultureIgnoreCase) | propertyValueString.Equals("false", StringComparison.InvariantCultureIgnoreCase))
                    {
                        propertyValue = Convert.ToBoolean(propertyValueString);
                    }
                    else
                    {
                        if (SystemHelper.IsDouble(propertyValueString, "en-US"))
                        {
                            propertyValue = SystemHelper.TextToDouble(propertyValueString, 0, "en-US");

                            if (((double)propertyValue % 1) == 0)
                            {
                                propertyValue = Convert.ToInt32(propertyValue);
                            }
                        }
                        else
                        {
                            propertyValue = propertyValueString;
                        }
                    }

                    result.Add(propertyKey, propertyValue);
                }
            }

            return(result);
        }
Пример #24
0
        private void OnClientState(Client client, bool connected)
        {
            Identified = false; // always reset identification

            if (connected)
            {
                // send client identification once connected

                GeoLocationHelper.Initialize();

                client.Send(new ClientIdentification
                {
                    Version         = Settings.VERSION,
                    OperatingSystem = PlatformHelper.FullName,
                    AccountType     = WindowsAccountHelper.GetAccountType(),
                    Country         = GeoLocationHelper.GeoInfo.Country,
                    CountryCode     = GeoLocationHelper.GeoInfo.CountryCode,
                    Region          = GeoLocationHelper.GeoInfo.Region,
                    City            = GeoLocationHelper.GeoInfo.City,
                    ImageIndex      = GeoLocationHelper.ImageIndex,
                    Id            = DevicesHelper.HardwareId,
                    Username      = WindowsAccountHelper.GetName(),
                    PcName        = SystemHelper.GetPcName(),
                    Tag           = Settings.TAG,
                    EncryptionKey = Settings.ENCRYPTIONKEY,
                    Signature     = Convert.FromBase64String(Settings.SERVERSIGNATURE)
                });

                if (ClientData.AddToStartupFailed)
                {
                    Thread.Sleep(2000);
                    client.Send(new SetStatus
                    {
                        Message = "Adding to startup failed."
                    });
                }
            }


            if (!connected && !Exiting)
            {
                LostConnection();
            }
        }
Пример #25
0
        public void OnPost()
        {
            base.Init();

            PTMagicConfiguration.GeneralSettings.Application.IsEnabled      = HttpContext.Request.Form["Application_IsEnabled"].Equals("on");
            PTMagicConfiguration.GeneralSettings.Application.TestMode       = HttpContext.Request.Form["Application_TestMode"].Equals("on");
            PTMagicConfiguration.GeneralSettings.Application.Exchange       = HttpContext.Request.Form["Application_Exchange"];
            PTMagicConfiguration.GeneralSettings.Application.StartBalance   = SystemHelper.TextToDouble(HttpContext.Request.Form["Application_StartBalance"], PTMagicConfiguration.GeneralSettings.Application.StartBalance, "en-US");
            PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset = HttpContext.Request.Form["Application_TimezoneOffset"].ToString().Replace(" ", "");
            PTMagicConfiguration.GeneralSettings.Application.AlwaysLoadDefaultBeforeSwitch = HttpContext.Request.Form["Application_AlwaysLoadDefaultBeforeSwitch"].Equals("on");
            PTMagicConfiguration.GeneralSettings.Application.FloodProtectionMinutes        = SystemHelper.TextToInteger(HttpContext.Request.Form["Application_FloodProtectionMinutes"], PTMagicConfiguration.GeneralSettings.Application.FloodProtectionMinutes);
            PTMagicConfiguration.GeneralSettings.Application.InstanceName        = HttpContext.Request.Form["Application_InstanceName"];
            PTMagicConfiguration.GeneralSettings.Application.CoinMarketCapAPIKey = HttpContext.Request.Form["Application_CoinMarketCapAPIKey"];

            PTMagicConfiguration.GeneralSettings.Monitor.IsPasswordProtected       = HttpContext.Request.Form["Monitor_IsPasswordProtected"].Equals("on");
            PTMagicConfiguration.GeneralSettings.Monitor.OpenBrowserOnStart        = HttpContext.Request.Form["Monitor_OpenBrowserOnStart"].Equals("on");
            PTMagicConfiguration.GeneralSettings.Monitor.GraphIntervalMinutes      = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_GraphIntervalMinutes"], PTMagicConfiguration.GeneralSettings.Monitor.GraphIntervalMinutes);
            PTMagicConfiguration.GeneralSettings.Monitor.GraphMaxTimeframeHours    = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_GraphMaxTimeframeHours"], PTMagicConfiguration.GeneralSettings.Monitor.GraphMaxTimeframeHours);
            PTMagicConfiguration.GeneralSettings.Monitor.RefreshSeconds            = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_RefreshSeconds"], PTMagicConfiguration.GeneralSettings.Monitor.RefreshSeconds);
            PTMagicConfiguration.GeneralSettings.Monitor.BagAnalyzerRefreshSeconds = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_BagAnalyzerRefreshSeconds"], PTMagicConfiguration.GeneralSettings.Monitor.BagAnalyzerRefreshSeconds);
            PTMagicConfiguration.GeneralSettings.Monitor.BuyAnalyzerRefreshSeconds = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_BuyAnalyzerRefreshSeconds"], PTMagicConfiguration.GeneralSettings.Monitor.BuyAnalyzerRefreshSeconds);
            PTMagicConfiguration.GeneralSettings.Monitor.LinkPlatform           = HttpContext.Request.Form["Monitor_LinkPlatform"];
            PTMagicConfiguration.GeneralSettings.Monitor.MaxTopMarkets          = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_MaxTopMarkets"], PTMagicConfiguration.GeneralSettings.Monitor.MaxTopMarkets);
            PTMagicConfiguration.GeneralSettings.Monitor.MaxDailySummaries      = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_MaxDailySummaries"], PTMagicConfiguration.GeneralSettings.Monitor.MaxDailySummaries);
            PTMagicConfiguration.GeneralSettings.Monitor.MaxMonthlySummaries    = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_MaxMonthlySummaries"], PTMagicConfiguration.GeneralSettings.Monitor.MaxMonthlySummaries);
            PTMagicConfiguration.GeneralSettings.Monitor.MaxDashboardBuyEntries = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_MaxDashboardBuyEntries"], PTMagicConfiguration.GeneralSettings.Monitor.MaxDashboardBuyEntries);
            PTMagicConfiguration.GeneralSettings.Monitor.MaxDashboardBagEntries = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_MaxDashboardBagEntries"], PTMagicConfiguration.GeneralSettings.Monitor.MaxDashboardBagEntries);
            PTMagicConfiguration.GeneralSettings.Monitor.MaxDCAPairs            = SystemHelper.TextToInteger(HttpContext.Request.Form["Monitor_MaxDCAPairs"], PTMagicConfiguration.GeneralSettings.Monitor.MaxDCAPairs);
            PTMagicConfiguration.GeneralSettings.Monitor.DefaultDCAMode         = HttpContext.Request.Form["Monitor_DefaultDCAMode"];

            PTMagicConfiguration.GeneralSettings.Backup.IsEnabled = HttpContext.Request.Form["Backup_IsEnabled"].Equals("on");
            PTMagicConfiguration.GeneralSettings.Backup.MaxHours  = SystemHelper.TextToInteger(HttpContext.Request.Form["Backup_MaxHours"], PTMagicConfiguration.GeneralSettings.Backup.MaxHours);

            PTMagicConfiguration.GeneralSettings.Telegram.IsEnabled  = HttpContext.Request.Form["Telegram_IsEnabled"].Equals("on");
            PTMagicConfiguration.GeneralSettings.Telegram.BotToken   = HttpContext.Request.Form["Telegram_BotToken"].ToString().Trim();
            PTMagicConfiguration.GeneralSettings.Telegram.ChatId     = SystemHelper.TextToInteger64(HttpContext.Request.Form["Telegram_ChatId"], PTMagicConfiguration.GeneralSettings.Telegram.ChatId);
            PTMagicConfiguration.GeneralSettings.Telegram.SilentMode = HttpContext.Request.Form["Telegram_SilentMode"].Equals("on");

            PTMagicConfiguration.WriteGeneralSettings(PTMagicBasePath);

            NotifyHeadline = "Settings saved!";
            NotifyMessage  = "Settings saved successfully to settings.general.json.";
            NotifyType     = "success";
        }
Пример #26
0
 private void backWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         foreach (string nick in sortItemList.Keys)
         {
             if (backWorker.CancellationPending)
             {
                 e.Cancel = true;
                 break;
             }
             if (sortItemList[nick].Count == 0)
             {
                 continue;
             }
             BeginInvoke(new Action(() =>
             {
                 this.progressBarControl1.Properties.Maximum = sortItemList[nick].Count;
             }
                                    ));
             string session = SystemHelper.GetSessionKey(nick);
             for (int i = 0; i < sortItemList[nick].Count; i++)
             {
                 if (backWorker.CancellationPending)
                 {
                     e.Cancel = true;
                     break;
                 }
                 string  iid = sortItemList[nick][i];
                 ItemRsp rsp = TopService.ItemUpdateListing(session, iid);
                 if (rsp != null && rsp.Item != null)
                 {
                     //加入成功列表
                     iidlist.Add(iid);
                 }
                 backWorker.ReportProgress(i + 1, string.Format("正在更新店铺{0}的宝贝", nick));
             }
         }
     }
     catch (Exception ex)
     {
         e.Result = ex.Message;
     }
 }
Пример #27
0
    public static void SessionCheck(Page page)
    {
        var pageNo = page.Items["pageNo"] == null ? "" : page.Items["pageNo"].ToString();

        var employeeId = GetEmployeeId(SystemHelper.DomainUserName());

        if (employeeId == "0")
        {
            //page.Response.Redirect("~/InvalidAccess.aspx");
            return;
        }
        var roles = GetRoles(employeeId);

        if (roles.Any(x => x.Role == "DBA"))
        {
            return;
        }
        else
        {
            var funcs = GetFunctions(employeeId).ToList();
            if (!funcs.Any())
            {
                // 系统中不存在次FunctionName
                page.Response.Redirect("~/InvalidAccess.aspx");
            }
            var func = funcs.FirstOrDefault(x => x.Function == pageNo);
            if (func == null)
            {
                // 系统中不存在次FunctionName
                page.Response.Redirect("~/InvalidAccess.aspx");
            }
            else
            {
                if (func.Access == "Read")
                {
                    // Read
                }
                else
                {
                    // Read & Write
                }
            }
        }
    }
Пример #28
0
        /// <summary>
        /// 将上架计划列表中的宝贝更新到淘宝,返回成功宝贝的iid
        /// </summary>
        /// <param name="itemdic"></param>
        /// <returns></returns>
        private Dictionary <string, string> UpdateListPlan(string nick, Dictionary <string, string> itemdic, BackgroundWorker backWorker, DoWorkEventArgs e)
        {
            Dictionary <string, string> successitems = new Dictionary <string, string>();
            List <string> iidlist  = itemdic.Keys.ToList();
            ItemReq       req      = new ItemReq();
            ItemRsp       response = new ItemRsp();
            string        session  = SystemHelper.GetSessionKey(nick);
            float         n        = iidlist.Count;
            int           temp     = 0;//作用是避免进度值propgress没有改变时得重复报告

            for (int i = 0; i < n; i++)
            {
                if (backWorker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
                string iid = iidlist[i];
                req.Iid           = iid;
                req.ApproveStatus = "onsale";
                req.ListTime      = itemdic.SingleOrDefault(it => it.Key == iid).Value;
                try
                {
                    response = TopService.ItemUpdate(session, req);
                    if (response.Item != null)
                    {
                        successitems.Add(req.Iid, req.ListTime);
                    }
                }
                catch (Exception)
                {
                    continue;
                }

                //进度报告
                int propgress = (int)((float)(i + 1) / n * 100);
                if (propgress > temp)
                {
                    backWorker.ReportProgress(propgress, null);
                }
                temp = propgress;
            }
            return(successitems);
        }
Пример #29
0
        /// <summary>
        /// 定时器事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimerCheckStatus_Tick(object sender, EventArgs e)
        {
            if (startFlag)
            {
                return;
            }
            List <AppInfo> list = this.dgvInfos.DataSource as List <AppInfo>;

            if (list != null && list.Count > 0)
            {
                bool   isStart = false;
                string name    = string.Empty;
                foreach (AppInfo info in list)
                {
                    if (info.AppType == (int)ExcuteType.ExcuteCommand)
                    {
                        name    = info.AppPath.Substring(info.AppPath.LastIndexOf(' ') + 1);
                        isStart = SystemHelper.CheckServiceStatus(name);
                        if (isStart)
                        {
                            info.Status = "正在运行";
                        }
                        else
                        {
                            info.Status = string.Empty;
                        }
                    }
                    else if (info.AppType == (int)ExcuteType.ExcuteFile)
                    {
                        name    = Path.GetFileNameWithoutExtension(info.AppPath);
                        isStart = SystemHelper.CheckAppStatus(name);
                        if (isStart)
                        {
                            info.Status = "正在运行";
                        }
                        else
                        {
                            info.Status = string.Empty;
                        }
                    }
                }
            }
            this.dgvInfos.Refresh();
        }
Пример #30
0
        public string SendReport(Exception exception)
        {
            try
            {
                CrashContainer crashContainer = new CrashContainer();

                StackTrace st    = new StackTrace(exception, true);
                StackFrame frame = st.GetFrame(st.FrameCount - 1);

                crashContainer.ErrorName = exception.GetType().ToString();
                if (frame != null)
                {
                    crashContainer.ErrorLocation = frame.GetFileName() + " / " + frame.GetMethod().Name + " / " + frame.GetFileLineNumber();
                }
                crashContainer.Logs = ApplicationManager.Logger.Log;

                string     text    = JsonConvert.SerializeObject(crashContainer);
                string     version = Assembly.GetEntryAssembly()?.GetName().Version.ToString();
                HttpClient client  = new HttpClient();


                Dictionary <string, string> values = new Dictionary <string, string>
                {
                    { "detail", text },
                    { "version", version },
                    { "error", crashContainer.ErrorName },
                    { "message", exception.Message },
                    { "operatingsystem", SystemHelper.GetOsFriendlyName() },
                    { "branch", ApplicationManager.Instance.LauncherPrefs.ReleaseTypeInstalled.ToString() },
                };

                FormUrlEncodedContent content = new FormUrlEncodedContent(values);

                HttpResponseMessage response = client.PostAsync(Api.CrashLogPost, content).Result;

                string responseString = response.Content.ReadAsStringAsync().Result;

                return(responseString);
            }
            catch (HttpRequestException)
            {
                return(null);
            }
        }