Example #1
0
        /// <summary>
        /// 关闭
        /// </summary>
        private new void Stop()
        {
            try
            {
                // 服务关闭时应该会自动关闭吧
                ////关闭服务
                //if (null != host)
                //{
                //    try
                //    {
                //        host.Close();
                //        host = null;
                //    }
                //    catch (Exception ex)
                //    {
                //        ExceptionPro.ExpLog(ex);
                //    }
                //}

                //关闭线程
                Resources.GetRes().CloseThread();


                ExceptionPro.ExpInfoLog("Service closed successfully.");
            }
            catch (Exception ex)
            {
                ExceptionPro.ExpLog(ex, null, false, "Service close failed.");
            }
        }
Example #2
0
        /// <summary>
        /// 初始化服务器(获取服务端IP) (打算不获取了. 因为服务器IP万能就可以, 又支持私网或者公网IP都应该可以,你不愿意你自己调防火墙)
        /// </summary>
        public void InitialServer()
        {
            try
            {
                bool IsSuccessGetIP = false;


                using (StreamReader sr = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ServerConfig.txt"), Encoding.UTF8))
                {
                    string line = null;
                    string temp = null;

                    while ((line = sr.ReadLine()) != null)
                    {
                        //获取消费类型

                        if (!IsSuccessGetIP && line.Trim().StartsWith("IPAddress"))
                        {
                            try
                            {
                                temp = line.Trim().Split('=')[1];
                                if (System.Text.RegularExpressions.Regex.Match(temp, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").Success)
                                {
                                    Resources.GetRes().IPAddress = temp;
                                    IsSuccessGetIP = true;
                                }
                                else if (string.IsNullOrWhiteSpace(temp)) // 默认localhost
                                {
                                    IsSuccessGetIP = true;
                                }
                                else
                                {
                                    ExceptionPro.ExpInfoLog("Unknow IPAddress param.");
                                }
                            }
                            catch (Exception)
                            {
                                ExceptionPro.ExpInfoLog("Unknow IPAddress param.");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionPro.ExpLog(ex);
            }
        }
Example #3
0
            internal void CreateNewDB(string Conn, string dbNewPassword, string adminNewPassword)
            {
                ExceptionPro.ExpInfoLog("Database not found, creating a new database!");


                string osPath = Path.GetTempFileName();

                ExportFile("Oybab.ServerManager.Resources.Database.ts.db", osPath);

                // 如果有密码需要先创建密码
                ChangePassword(osPath, dbNewPassword, "", adminNewPassword);

                //现在返回(暂时先先复制再返回新文件路径, 免得无法读取,提示什么进程正在使用之类的错误).

                File.Copy(osPath, Conn, false);
            }
Example #4
0
        /// <summary>
        /// 加载
        /// </summary>
        internal void GetConfigs()
        {
            try
            {
                bool IsSuccessBackupFolder = false;
                bool IsSuccessDbKey        = false;
                bool IsSuccessUID          = false;
                bool IsSuccessPrintInfo    = false;


                using (StreamReader sr = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ServerConfig.txt"), Encoding.UTF8))
                {
                    string line = null;
                    string temp = null;

                    while ((line = sr.ReadLine()) != null)
                    {
                        //获取消费类型

                        if (!IsSuccessBackupFolder && line.Trim().StartsWith("BackupFolderPath"))
                        {
                            try
                            {
                                temp = line.Trim().TrimStart("BackupFolderPath=");
                                Resources.GetRes().BackupFolderPath = temp;
                                IsSuccessBackupFolder = true;
                            }
                            catch (Exception)
                            {
                                ExceptionPro.ExpInfoLog("Unknow BackupFolderPath param.");
                            }
                        }
                        else if (!IsSuccessDbKey && line.Trim().StartsWith("DbKey"))
                        {
                            try
                            {
                                temp = line.Trim().TrimStart("DbKey=");
                                if (string.IsNullOrWhiteSpace(Resources.GetRes().DB_KEY))
                                {
                                    Resources.GetRes().DB_KEY = temp;
                                }
                                IsSuccessDbKey = true;
                            }
                            catch (Exception)
                            {
                                ExceptionPro.ExpInfoLog("Unknow DB_KEY param.");
                            }
                        }
                        else if (!IsSuccessUID && line.Trim().StartsWith("UID"))
                        {
                            try
                            {
                                temp = line.Trim().TrimStart("UID=");
                                if (string.IsNullOrWhiteSpace(Resources.GetRes().UID))
                                {
                                    Resources.GetRes().UID = temp;
                                }
                                IsSuccessUID = true;
                            }
                            catch (Exception)
                            {
                                ExceptionPro.ExpInfoLog("Unknow UID param.");
                            }
                        }
                        else if (!IsSuccessPrintInfo && line.Trim().StartsWith("PrintInfo"))
                        {
                            try
                            {
                                temp = line.Trim().TrimStart("PrintInfo=");
                                try
                                {
                                    if (!string.IsNullOrWhiteSpace(temp))
                                    {
                                        Resources.GetRes().PrintInfo = JsonConvert.DeserializeObject <PrintInfo>(Resources.GetRes().PrintInfo.Decrypt(temp, true));
                                    }

                                    IsSuccessPrintInfo = true;
                                }
                                catch
                                {
                                    ExceptionPro.ExpInfoLog("Unknow PrintInfo param.");
                                }
                            }
                            catch (Exception)
                            {
                                ExceptionPro.ExpInfoLog("Unknow PhoneNo param.");
                            }
                        }
                    }
                }

                if (!IsSuccessBackupFolder)
                {
                    ExceptionPro.ExpInfoLog("undefined BackupFolderPath param.");
                }
                if (!IsSuccessDbKey)
                {
                    ExceptionPro.ExpInfoLog("undefined DbKey param.");
                }
                if (!IsSuccessUID)
                {
                    ExceptionPro.ExpInfoLog("undefined UID param.");
                }

                if (!IsSuccessPrintInfo)
                {
                    ExceptionPro.ExpInfoLog("undefined PrintInfo param.");
                }
            }
            catch (Exception ex)
            {
                ExceptionPro.ExpLog(ex);
            }
        }
Example #5
0
        /// <summary>
        /// 查找新版本
        /// </summary>
        public static void SearchUpdate(string more, Action <UpdateModel> FindNewVersion = null)
        {
            Action action = new Action(() =>
            {
                try
                {
                    //1分钟后执行
                    System.Threading.Thread.Sleep(1000 * 60 * 1);
                    System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                    string version = assembly.GetName().Version.ToString();//获取主版本号

                    //获取硬件号
                    string uid = Res.Server.OperatesService.GetOperates().ServiceUID();
                    //
                    //定义webClient对象
                    CookieAwareWebClient webClient = new CookieAwareWebClient();
                    //定义通信地址 和 JSON数据
                    string URL = "https://www.oybab.net/software/update/";
                    //string URL = "http://192.168.1.100/OyBabNet/software/update/";

                    //组装数据
                    NameValueCollection postValues = new NameValueCollection();
                    //postValues.Add("json_data", jsonString);
                    postValues.Add("version", version);
                    postValues.Add("uid", uid);
                    postValues.Add("lang", Resources.GetRes().GetLangByLangIndex(Resources.GetRes().CurrentLangIndex).Culture.Name);
                    postValues.Add("app", Resources.GetRes().SOFT_SERVICE_NAME);
                    postValues.Add("more", more);
                    postValues.Add("name", Resources.GetRes().KEY_NAME_0);
                    postValues.Add("os", OSCheck.GetOS());
                    postValues.Add("ostype", OSCheck.GetOSType());

                    //向服务器发送POST数据
                    byte[] responseArray = webClient.UploadValues(URL, postValues);
                    string data          = Encoding.UTF8.GetString(responseArray);

                    //如果空
                    if (string.IsNullOrWhiteSpace(data))
                    {
                         #if DEBUG
                        ExceptionPro.ExpInfoLog("Response empty!");
                        #endif
                        return;
                    }

                    UpdateModel model = UpdateModel.FromJsonTo <UpdateModel>(data);
                    if (null != model)
                    {
                        //如果成功
                        if (model.Code == "1")
                        {
                            if (null != FindNewVersion)
                            {
                                FindNewVersion(model);
                            }
                        }
                        //如果需要锁住
                        else if (model.Code == "-4")
                        {
                            if (Res.Server.OperatesService.GetOperates().ServiceLock())
                            {
                                postValues.Add("ConfirmLock", "1");
                                postValues.Add("TId", model.TId);
                                webClient.UploadValues(URL, postValues);
                                //ExceptionPro.ExpInfoLog("Lock Key Success!");
                                //#if DEBUG
                                ExceptionPro.ExpErrorLog("LS");
                                //#endif
                            }
                            else
                            {
                                postValues.Add("ConfirmLock", "0");
                                postValues.Add("TId", model.TId);
                                webClient.UploadValues(URL, postValues);
                                //ExceptionPro.ExpErrorLog("Lock Key Faild!");
                                //#if DEBUG
                                ExceptionPro.ExpErrorLog("LF");
                                //#endif
                            }
                            return;
                        }
                        //如果其他或失败
                        else
                        {
                            #if DEBUG
                            if (!string.IsNullOrWhiteSpace(model.ErrorMsg))
                            {
                                throw new OybabException(model.ErrorMsg, true);
                            }
                            else
                            {
                                throw new OybabException(string.Format(Res.Resources.GetRes().GetString("UpdateUnableError"), model.Code), true);
                            }
                            #endif
                        }
                    }
                    //数据返回空或解析失败
                    else
                    {
                        #if DEBUG
                        throw new OybabException(Res.Resources.GetRes().GetString("UpdateNonReturnOrCantRead"), true);
                        #endif
                    }
                }
                catch
#if DEBUG
                (Exception ex)
#endif
                {
#if DEBUG
                    ExceptionPro.ExpLog(ex, null, true);
#endif
                }
            });

            action.BeginInvoke(null, null);
        }
Example #6
0
        /// <summary>
        /// 查找新版本
        /// </summary>
        public static void SearchUpdate(string more, Action <UpdateModel> FindNewVersion = null)
        {
            Task.Run(async() =>
            {
                try
                {
                    //1分钟后执行
                    await ExtX.Sleep(1000 * 60 * 1);

                    string version = OperatesService.Instance.AllVersion;

                    //获取硬件号
                    string uid = await OperatesService.Instance.ServiceUID();

                    CookieContainer CookieContainer = new CookieContainer();
                    //
                    //定义webClient对象
                    var cookieContainer = new CookieContainer();
                    using (var handler = new HttpClientHandler()
                    {
                        CookieContainer = cookieContainer, UseCookies = true
                    })
                    {
                        //定义通信地址 和 JSON数据
                        string URL = "https://www.oybab.net/software/update/";
                        //string URL = "http://localhost:3282/software/update/";

                        using (var client = new HttpClient(handler)
                        {
                            BaseAddress = new Uri(URL)
                        })
                        {
                            var values = new Dictionary <string, string>();
                            values.Add("version", version);
                            values.Add("uid", uid);
                            values.Add("lang", TradingSystemX.Res.Instance.GetLangByLangIndex(TradingSystemX.Res.Instance.CurrentLangIndex).Culture.Name);
                            values.Add("app", Resources.Instance.SOFT_SERVICE_NAME);
                            values.Add("more", more);
                            values.Add("name", Resources.Instance.KEY_NAME_0);
                            values.Add("os", OperatesService.Instance.GetOS());
                            values.Add("ostype", DeviceInfo.VersionString);

                            var content = new FormUrlEncodedContent(values);



                            //向服务器发送POST数据
                            var response = await client.PostAsync(URL, content);
                            string data  = Encoding.UTF8.GetString(await response.Content.ReadAsByteArrayAsync());

                            //如果空
                            if (string.IsNullOrWhiteSpace(data))
                            {
#if DEBUG
                                ExceptionPro.ExpInfoLog("Response empty!");
#endif
                                return;
                            }

                            UpdateModel model = data.DeserializeObject <UpdateModel>();
                            if (null != model)
                            {
                                //如果成功
                                if (model.Code == "1")
                                {
                                    if (null != FindNewVersion)
                                    {
                                        FindNewVersion(model);
                                    }
                                }
                                //如果需要锁住
                                else if (model.Code == "-4")
                                {
                                    if (await OperatesService.Instance.ServiceLock())
                                    {
                                        values.Add("ConfirmLock", "1");
                                        values.Add("TId", model.TId);

                                        var content2 = new FormUrlEncodedContent(values);


                                        await client.PostAsync(URL, content2);

                                        ExceptionPro.ExpErrorLog("LS");
                                    }
                                    else
                                    {
                                        values.Add("ConfirmLock", "0");
                                        values.Add("TId", model.TId);

                                        var content2 = new FormUrlEncodedContent(values);

                                        await client.PostAsync(URL, content2);

                                        ExceptionPro.ExpErrorLog("LF");
                                    }
                                    return;
                                }
                                //如果其他或失败
                                else
                                {
#if DEBUG
                                    if (!string.IsNullOrWhiteSpace(model.ErrorMsg))
                                    {
                                        throw new OybabException(model.ErrorMsg, true);
                                    }
                                    else
                                    {
                                        throw new OybabException(string.Format(TradingSystemX.Res.Instance.GetString("UpdateUnableError"), model.Code), true);
                                    }
#endif
                                }
                            }
                            //数据返回空或解析失败
                            else
                            {
#if DEBUG
                                throw new OybabException(TradingSystemX.Res.Instance.GetString("UpdateNonReturnOrCantRead"), true);
#endif
                            }
                        }
                    }
                }
                catch
#if DEBUG
                (Exception ex)
#endif
                {
#if DEBUG
                    ExceptionPro.ExpLog(ex, null, true);
#endif
                }
            });
        }
Example #7
0
        /// <summary>
        /// 获取语言
        /// </summary>
        public void GetConfigs(bool IsPC = false)
        {
            try
            {
                bool IsSuccessServer               = false;
                bool IsSuccessDisplayCursor        = false;
                bool IsSuccessDisplaySecondMonitor = false;
                //bool IsSuccessMediaRoot = false;
                bool IsSuccessSyncTime = false;
                bool IsSuccessLocalPrintCustomOrder = false;
                bool IsSuccessCashDrawer            = false;
                bool IsSuccessPriceMonitor          = false;
                bool IsSuccessBarcodeReader         = false;
                bool IsSuccessCardReader            = false;
                bool IsSuccessLang = false;

                bool IsSuccessDemands    = false;
                bool IsSuccessCallDevice = false;


                //下次记得增加去掉已测试过的判断,在配置文件增加是否隐藏开始菜单
                using (StreamReader sr = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.txt"), Encoding.UTF8))
                {
                    string line = null;
                    string temp = null;

                    while ((line = sr.ReadLine()) != null)
                    {
                        //获取服务器地址
                        if (!IsSuccessServer && line.Trim().StartsWith("Server"))
                        {
                            try
                            {
                                temp = line.Trim().Split('=')[1];
                                Resources.GetRes().SERVER_ADDRESS = temp;
                                Resources.GetRes().ROOT           = @"\\" + Resources.GetRes().SERVER_ADDRESS;
                                IsSuccessServer = true;
                            }
                            catch
                            {
                                ExceptionPro.ExpInfoLog("Unknow Server param.");
                            }
                        }
                        //获取鼠标是否显示
                        else if (Resources.GetRes().DevicesType == 2 && !IsSuccessDisplayCursor && line.Trim().StartsWith("DisplayCursor"))
                        {
                            temp = line.Trim().Split('=')[1];
                            if (temp == "0")
                            {
                                Resources.GetRes().DisplayCursor = false;
                                IsSuccessDisplayCursor = true;
                            }
                            else if (temp == "1")
                            {
                                Resources.GetRes().DisplayCursor = true;
                                IsSuccessDisplayCursor = true;
                            }
                            else
                            {
                                ExceptionPro.ExpInfoLog("Unknow DisplayCursor param.");
                            }
                        }
                        // 是否显示第二屏幕
                        else if (!IsSuccessDisplaySecondMonitor && line.Trim().StartsWith("DisplaySecondMonitor"))
                        {
                            temp = line.Trim().Split('=')[1];
                            if (temp == "0")
                            {
                                Resources.GetRes().DisplaySecondMonitor = false;
                                IsSuccessDisplaySecondMonitor = true;
                            }
                            else if (temp == "1")
                            {
                                Resources.GetRes().DisplaySecondMonitor = true;
                                IsSuccessDisplaySecondMonitor = true;
                            }
                            else
                            {
                                ExceptionPro.ExpInfoLog("Unknow DisplaySecondMonitor param.");
                            }
                        }
                        //是否自动同步服务器时间到客户端
                        else if (!IsSuccessSyncTime && line.Trim().StartsWith("AutoSyncClientTime"))
                        {
                            temp = line.Trim().Split('=')[1];
                            if (temp == "0")
                            {
                                Resources.GetRes().AutoSyncClientTime = false;
                                IsSuccessSyncTime = false;
                            }
                            else if (temp == "1")
                            {
                                Resources.GetRes().AutoSyncClientTime = true;
                                IsSuccessSyncTime = true;
                            }
                            else
                            {
                                ExceptionPro.ExpInfoLog("Unknow AutoSyncClientTime param.");
                            }
                        }
                        //是否本地打印客户订单
                        else if (!IsSuccessLocalPrintCustomOrder && line.Trim().StartsWith("IsLocalPrintCustomOrder"))
                        {
                            temp = line.Trim().Split('=')[1];
                            if (temp == "0")
                            {
                                Resources.GetRes().IsLocalPrintCustomOrder = false;
                                IsSuccessLocalPrintCustomOrder = true;
                            }
                            else if (temp == "1")
                            {
                                Resources.GetRes().IsLocalPrintCustomOrder = true;
                                IsSuccessLocalPrintCustomOrder = true;
                            }
                            else
                            {
                                ExceptionPro.ExpInfoLog("Unknow IsLocalPrintCustomOrder param.");
                            }
                        }
                        //钱箱
                        else if (!IsSuccessCashDrawer && line.Trim().StartsWith("CashDrawer"))
                        {
                            try
                            {
                                temp = line.Trim().Split('=')[1];
                                Resources.GetRes().CashDrawer = temp;
                                IsSuccessCashDrawer = true;
                            }
                            catch
                            {
                                ExceptionPro.ExpInfoLog("Unknow CashDrawer param.");
                            }
                        }
                        //客显
                        else if (!IsSuccessPriceMonitor && line.Trim().StartsWith("PriceMonitor"))
                        {
                            try
                            {
                                temp = line.Trim().Split('=')[1];
                                Resources.GetRes().PriceMonitor = temp;
                                IsSuccessPriceMonitor = true;
                            }
                            catch
                            {
                                ExceptionPro.ExpInfoLog("Unknow PriceMonitor param.");
                            }
                        }
                        //条码阅读器
                        else if (!IsSuccessBarcodeReader && line.Trim().StartsWith("BarcodeReader"))
                        {
                            try
                            {
                                temp = line.Trim().Split('=')[1];
                                Resources.GetRes().BarcodeReader = temp;
                                IsSuccessBarcodeReader = true;
                            }
                            catch
                            {
                                ExceptionPro.ExpInfoLog("Unknow BarcodeReader param.");
                            }
                        }
                        //卡片阅读器
                        else if (!IsSuccessCardReader && line.Trim().StartsWith("CardReader"))
                        {
                            try
                            {
                                temp = line.Trim().Split('=')[1];
                                Resources.GetRes().CardReader = temp;
                                IsSuccessCardReader = true;
                            }
                            catch
                            {
                                ExceptionPro.ExpInfoLog("Unknow CardReader param.");
                            }
                        }
                        // 特殊功能
                        else if (!IsSuccessDemands && line.Trim().StartsWith("Demands"))
                        {
                            try
                            {
                                temp = line.Trim().Split('=')[1];
                                List <string> tempSplitSelect = temp.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList();
                                if (tempSplitSelect.Count > 0)
                                {
                                    Resources.GetRes().Demands.AddRange(tempSplitSelect);
                                }
                                IsSuccessDemands = true;
                            }
                            catch
                            {
                                ExceptionPro.ExpInfoLog("Unknow Demands param.");
                            }
                        }
                        // 呼叫器
                        else if (!IsSuccessCallDevice && line.Trim().StartsWith("CallDevice"))
                        {
                            try
                            {
                                temp = line.Trim().Split('=')[1];
                                Resources.GetRes().CallDevice = temp;
                                IsSuccessCallDevice = true;
                            }
                            catch
                            {
                                ExceptionPro.ExpInfoLog("Unknow CallDevice param.");
                            }
                        }
                        //获取语言
                        else if (Environment.GetCommandLineArgs().Length <= 1 && !IsSuccessLang && line.Trim().StartsWith("Language"))
                        {
                            temp = line.Trim().Split('=')[1];

                            int index = int.Parse(temp);

                            if (index == -1)
                            {
                                var currentLang = Resources.GetRes().AllLangList.Where(x => x.Value.Culture.Name == System.Globalization.CultureInfo.CurrentCulture.Name).Select(x => x.Value).FirstOrDefault();
                                if (null != currentLang)
                                {
                                    index = currentLang.LangIndex;
                                }
                                else
                                {
                                    index = 2; // default english
                                }
                            }


                            Resources.GetRes().ReloadResources(index);
                            IsSuccessLang = true;
                        }
                    }
                }

                //用命令行选择语言
                if (Environment.GetCommandLineArgs().Length > 1)
                {
                    string temp = Environment.GetCommandLineArgs()[1];
                    Resources.GetRes().ReloadResources(int.Parse(temp));
                    IsSuccessLang = true;
                }


                if (!IsSuccessServer)
                {
                    ExceptionPro.ExpInfoLog("undefined Server param.");
                }

                if (Res.Resources.GetRes().DevicesType == 2 && !IsSuccessDisplayCursor)
                {
                    ExceptionPro.ExpInfoLog("undefined DisplayCursor param.");
                }

                if (!IsSuccessDisplaySecondMonitor)
                {
                    ExceptionPro.ExpInfoLog("undefined DisplaySecondMonitor param.");
                }


                if (!IsSuccessLocalPrintCustomOrder)
                {
                    ExceptionPro.ExpInfoLog("undefined IsLocalPrintCustomOrder param.");
                }

                if (!IsSuccessCashDrawer)
                {
                    ExceptionPro.ExpInfoLog("undefined CashDrawer param.");
                }

                if (!IsSuccessPriceMonitor)
                {
                    ExceptionPro.ExpInfoLog("undefined PriceMonitor param.");
                }

                if (!IsSuccessCardReader)
                {
                    ExceptionPro.ExpInfoLog("undefined CardReader param.");
                }

                if (!IsSuccessBarcodeReader)
                {
                    ExceptionPro.ExpInfoLog("undefined BarcodeReader param.");
                }


                if (!IsSuccessLang)
                {
                    ExceptionPro.ExpInfoLog("undefined Lanugage param.");
                }
            }
            catch (Exception ex)
            {
                ExceptionPro.ExpLog(ex);
            }
        }
Example #8
0
        internal void KeyCheck(bool AutoDetect = false)
        {
            NextCheck = DateTime.Now.AddMinutes(3);
            bool keyCheck = false;

            //检测KEY
            try
            {
                if (RemoveKeyCount < 2)
                {
                    keyCheck = Key.GetKeys().Check();
                }
            }
            catch (Exception ex)
            {
                ExceptionPro.ExpLog(ex, null, false, "Checking KEY failed!");
            }
            try
            {
                //检测KEY
                if (!keyCheck)
                {
                    if (RemoveKeyCount != -1 && AutoDetect)
                    {
                        ++RemoveKeyCount;
                    }

                    ExceptionPro.ExpInfoLog("Check KEY failed!");

                    // 清空数据和客户端
                    ClearDataAndService();

                    Key.GetKeys().Clear(true);
                }
                else
                {
                    // 首次成功打开时把次数重置为0
                    if (RemoveKeyCount == -1)
                    {
                        RemoveKeyCount = 0;
                    }

                    if (AutoDetect)
                    {
                        //ExceptionPro.ExpInfoLog("Check KEY succeeded!");
                    }


                    // 自动检查过程中(非自动检测U盘模式), 如果有失效的, 则去除掉
                    if (!AutoDetect)
                    {
                        // 清理失去连接的连接
                        CleanDisconnectService();

                        // 清理一下别的地方登陆帐号
                        CleanUsedByOtherService();

                        // 清理密码错误队列
                        CleanPasswordErrorList();
                    }



                    // 如果KEY过期,则清空
                    if (Resources.GetRes().IsExpired == 1)
                    {
                        ClearDataAndService();
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionPro.ExpLog(ex, null, false, "Check KEY operation failed.");
            }
        }
Example #9
0
        /// <summary>
        /// 查找新版本
        /// </summary>
        internal static void SearchUpdate(string more, Action <UpdateModel> FindNewVersion = null, bool IsReconnect = false)
        {
            Action action = new Action(() =>
            {
                try
                {
                    System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                    string version = assembly.GetName().Version.ToString();//获取主版本号

                    //获取硬件号
                    string uid = Resources.GetRes().UID;

                    if (string.IsNullOrWhiteSpace(uid))
                    {
                        return;
                    }

                    //定义webClient对象
                    CookieAwareWebClient webClient = new CookieAwareWebClient();
                    //定义通信地址 和 JSON数据
                    string URL = "https://www.oybab.net/software/update/";
                    //string URL = "http://192.168.1.100/OyBabNet/software/update/";

                    //组装数据
                    NameValueCollection postValues = new NameValueCollection();
                    postValues.Add("version", version);
                    postValues.Add("uid", uid);
                    postValues.Add("lang", Resources.GetRes().AllLangList.Where(x => x.Value.LangIndex == Resources.GetRes().CurrentLangIndex).FirstOrDefault().Value.Culture.Name);
                    postValues.Add("app", Resources.GetRes().SOFT_SERVICE_NAME);
                    postValues.Add("more", more);
                    postValues.Add("name", Resources.GetRes().KEY_NAME_0);
                    postValues.Add("os", OSCheck.GetOS());
                    postValues.Add("ostype", OSCheck.GetOSType());

                    // 去锁(还有下面的锁住逻辑)
                    postValues.Add("LeftDay", Resources.GetRes().ExpiredRemainingDays.ToString());
                    if (Resources.GetRes().ExpiredRemainingDays < 7 && null != Resources.GetRes().RegTimeRequestCode)
                    {
                        postValues.Add("machineNo", Resources.GetRes().RegTimeRequestCode);
                    }

                    //向服务器发送POST数据
                    byte[] responseArray = webClient.UploadValues(URL, postValues);
                    string data          = Encoding.UTF8.GetString(responseArray);

                    //如果空
                    if (string.IsNullOrWhiteSpace(data))
                    {
                        #if DEBUG
                        ExceptionPro.ExpInfoLog("Response empty!");
                        #endif
                        return;
                    }

                    UpdateModel model = UpdateModel.FromJsonTo <UpdateModel>(data);
                    if (null != model)
                    {
                        //如果成功
                        if (model.Code == "1")
                        {
                            if (null != FindNewVersion)
                            {
                                FindNewVersion(model);
                            }
                        }// 如果需要延长时间
                        else if (model.Code == "8")
                        {
                            if (Res.Key.GetKeys().SetRegCode(model.DisplayMsg))
                            {
                                Res.Key.GetKeys().Clear(true);
                                if (DBOperate.GetDBOperate().IsDataReady)
                                {
                                    Res.Key.GetKeys().Check(false, true);
                                }
                                else
                                {
                                    Res.Key.GetKeys().Check(false);
                                }
#if DEBUG
                                ExceptionPro.ExpInfoLog("Extend Success!");
#endif

                                postValues.Add("RequestId", model.NewVersion);

                                webClient.UploadValues(URL, postValues);
                            }
                            else
                            {
#if DEBUG
                                ExceptionPro.ExpInfoLog("Extend Failed!");
#endif
                            }
                        }
                        //如果需要锁住
                        else if (model.Code == "-4")
                        {
                            if (Res.Key.GetKeys().LockKey())
                            {
                                postValues.Add("ConfirmLock", "1");
                                postValues.Add("TId", model.TId);
                                webClient.UploadValues(URL, postValues);
                                OperateLog.Instance.AddRecord(0, null, "LS#" + OperateType.None);
                            }
                            else
                            {
                                postValues.Add("ConfirmLock", "0");
                                postValues.Add("TId", model.TId);
                                webClient.UploadValues(URL, postValues);
                                OperateLog.Instance.AddRecord(0, null, "LS#" + OperateType.None);
                            }
                            return;
                        }
                        //如果其他或失败
                        else
                        {
                            #if DEBUG
                            if (!string.IsNullOrWhiteSpace(model.ErrorMsg))
                            {
                                throw new OybabException(model.ErrorMsg, true);
                            }
                            else
                            {
                                throw new OybabException(string.Format("Update Unable Error. code: {0}", model.Code), true);
                            }
                            #endif
                        }
                    }
                    //数据返回空或解析失败
                    else
                    {
                        #if DEBUG
                        throw new OybabException("Update Non Return Or Cant Read", true);
                        #endif
                    }
                }
                catch
#if DEBUG
                (Exception ex)
#endif
                {
#if DEBUG
                    ExceptionPro.ExpLog(ex, null, true);
#endif
                }
            });

            action.BeginInvoke(null, null);
        }
Example #10
0
        protected override void OnStart(string[] args)
        {
            if (null == host)
            {
                try
                {
                    // When Debug
                    //System.Diagnostics.Debugger.Launch();

#if !DEBUG
                    SetRecoveryOptions("OybabTradingSystemService");
#endif



                    // 初始化服务器(获取绑定IP地址)
                    //Resources.GetRes().InitialServer();

                    //加密
                    Uri adrbase = new Uri(string.Format(address, Resources.GetRes().IPAddress));
                    host = new ServiceHost(typeof(Trans.Service), adrbase);
#if W_TRANS
                    NetTcpBinding tcpb = new NetTcpBinding(SecurityMode.None);
#else
                    NetTcpBinding tcpb = new NetTcpBinding(SecurityMode.Message);
                    tcpb.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
#endif

                    //Updated: to enable file transefer of 64 MB(67108864) 655360000(Before);
                    tcpb.MaxBufferSize          = 67108864;
                    tcpb.MaxBufferPoolSize      = 67108864;
                    tcpb.MaxReceivedMessageSize = 67108864;

                    tcpb.ReaderQuotas.MaxArrayLength         = 67108864;
                    tcpb.ReaderQuotas.MaxBytesPerRead        = 67108864;
                    tcpb.ReaderQuotas.MaxStringContentLength = 67108864;



                    tcpb.MaxConnections = 30;
                    host.Description.Behaviors.Add(new ServiceThrottlingBehavior()
                    {
                        MaxConcurrentCalls     = 30,
                        MaxConcurrentInstances = 30,
                        MaxConcurrentSessions  = 100 // Init32.MaxValue(2147483647)
                    });


                    AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);

#if !W_TRANS
                    host.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, CertName);

                    host.Credentials.ClientCertificate.Authentication.RevocationMode            = X509RevocationMode.NoCheck;
                    host.Credentials.ClientCertificate.Authentication.TrustedStoreLocation      = StoreLocation.LocalMachine;
                    host.Credentials.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.Custom;

                    host.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new MyX509CertificateValidator("OU=Oybab");
#endif


                    Binding binding = CreateCustomBinding(tcpb, TimeSpan.FromMinutes(10));
                    host.AddServiceEndpoint(typeof(Trans.IService), binding, string.Format(address, Resources.GetRes().IPAddress));


                    // For DDNS
                    ServiceBehaviorAttribute attribute = host.Description.Behaviors.Find <ServiceBehaviorAttribute>();
                    attribute.AddressFilterMode = AddressFilterMode.Any;



                    host.Open();
                    SignalRSession.Instance.StartSignalR(address2);



                    // 创建检查线程
                    Resources.GetRes().CreateThread();

                    ExceptionPro.ExpInfoLog("Service started successfully.");
                }
                catch (Exception ex)
                {
                    ExceptionPro.ExpLog(ex);

                    //关闭服务
                    if (null != host)
                    {
                        try
                        {
                            host.Close();
                            host = null;
                        }
                        catch (Exception ex2)
                        {
                            ExceptionPro.ExpLog(ex2);
                        }
                    }


                    //关闭线程
                    Resources.GetRes().CloseThread();

                    ExceptionPro.ExpLog(ex, null, false, "Service start failed.");
                }
            }
        }
Example #11
0
        /// <summary>
        /// 加载数据
        /// </summary>
        internal void LoadData()
        {
            IsDataReady          = false;
            IsNotSuccessLoadData = false;
            IsNotFoundDatabase   = false;

            try
            {
                Config.GetConfig().GetConfigs();

                LoadSqlConn();


                bool IsDBKeyChange = false;
                bool IsUIDChange   = false;

                if (string.IsNullOrWhiteSpace(Resources.GetRes().DB_KEY))
                {
                    Resources.GetRes().DB_KEY = "".GenereteRandomCode(32, 2);
                    IsDBKeyChange = true;
                }
                if (string.IsNullOrWhiteSpace(Resources.GetRes().UID))
                {
                    Resources.GetRes().UID = "".GenereteRandomCode(32, 1);
                    IsUIDChange = true;
                }


                if (IsDBKeyChange || IsUIDChange)
                {
                    Config.GetConfig().SetConfig(Config.GetConfig().ReadConfig().GetLines().ToList());
                }


                //检查数据库文件是否存在

                if (!File.Exists(CONS_PATH))
                {
                    IsNotFoundDatabase = true;



                    DbOperator dbOperator    = new DbOperator();
                    string     adminPassword = "******";



                    adminPassword = Key.GetKeys().Encryption(adminPassword);

                    dbOperator.CreateNewDB(CONS_PATH, Resources.GetRes().DB_KEY, adminPassword);

                    IsNotFoundDatabase = false;


                    ExceptionPro.ExpInfoLog("Successflully created a new database!");
                }



                InitialConn(Resources.GetRes().DB_KEY);

#if !DEBUG
                //检查数据库文件密码是否为空
                bool IsInvalidDB = false;
                try
                {
                    using (System.Data.SQLite.SQLiteConnection _con = new System.Data.SQLite.SQLiteConnection("Data Source=" + CONS_PATH + ";Password=;"))
                    {
                        _con.Open();
                        DataTable tables = _con.GetSchema("Tables");
                        IsInvalidDB = true;
                    }
                }
                catch
                {
                    IsInvalidDB = false;
                }

                if (IsInvalidDB)
                {
                    IsNotFoundDatabase = true;
                    throw new OybabException("Invalid database!");
                }
#endif

                //备份
                Backup.Instance.BackupFile();

                //加载缓存
                LoadCache();
            }
            catch (Exception ex)
            {
                ExceptionPro.ExpLog(ex, null, false, "Exception_DatabaseLoadFailed");
            }
        }