Exemplo n.º 1
0
        /// <summary>获取提供者工厂</summary>
        /// <param name="assemblyFile"></param>
        /// <param name="className"></param>
        /// <param name="ignoreError"></param>
        /// <returns></returns>
        public static DbProviderFactory GetProviderFactory(String assemblyFile, String className, Boolean ignoreError = false)
        {
            try
            {
                var links = new List <String>();
                var name  = Path.GetFileNameWithoutExtension(assemblyFile);
                if (!name.IsNullOrEmpty())
                {
                    var linkName = name;
#if __CORE__
                    if (Runtime.Linux)
                    {
                        linkName += Environment.Is64BitProcess ? ".linux-x64" : ".linux-x86";
                        links.Add(linkName);
                        links.Add(name + ".linux");
                    }
                    else
                    {
                        linkName += Environment.Is64BitProcess ? ".win-x64" : ".win-x86";
                        links.Add(linkName);
                        links.Add(name + ".win");
                    }

                    linkName = name + ".st";
#else
                    if (Environment.Is64BitProcess)
                    {
                        linkName += "64";
                    }
                    var ver = Environment.Version;
                    if (ver.Major >= 4)
                    {
                        linkName += "Fx" + ver.Major + ver.Minor;
                    }
#endif
                    links.Add(linkName);
                    // 有些数据库驱动不区分x86/x64,并且逐步以Fx4为主,所以来一个默认
                    if (!links.Contains(name))
                    {
                        links.Add(name);
                    }
                }

                var type = PluginHelper.LoadPlugin(className, null, assemblyFile, links.Join(","));

                // 反射实现获取数据库工厂
                var file   = assemblyFile;
                var plugin = NewLife.Setting.Current.GetPluginPath();
                file = plugin.CombinePath(file);

                // 如果还没有,就写异常
                if (type == null)
                {
                    if (assemblyFile.IsNullOrEmpty())
                    {
                        return(null);
                    }
                    if (!File.Exists(file))
                    {
                        throw new FileNotFoundException("缺少文件" + file + "!", file);
                    }
                }

                if (type == null)
                {
                    XTrace.WriteLine("驱动文件{0}无效或不适用于当前环境,准备删除后重新下载!", assemblyFile);

                    try
                    {
                        File.Delete(file);
                    }
                    catch (UnauthorizedAccessException) { }
                    catch (Exception ex) { XTrace.Log.Error(ex.ToString()); }

                    type = PluginHelper.LoadPlugin(className, null, file, links.Join(","));

                    // 如果还没有,就写异常
                    if (!File.Exists(file))
                    {
                        throw new FileNotFoundException("缺少文件" + file + "!", file);
                    }
                }
                if (type == null)
                {
                    return(null);
                }

                var asm = type.Assembly;
                if (DAL.Debug)
                {
                    DAL.WriteLog("{2}驱动{0} 版本v{1}", asm.Location, asm.GetName().Version, name ?? className.TrimEnd("Client", "Factory"));
                }

                var field = type.GetFieldEx("Instance");
                if (field == null)
                {
                    return(Activator.CreateInstance(type) as DbProviderFactory);
                }

                return(Reflect.GetValue(null, field) as DbProviderFactory);
            }
            catch
            {
                if (ignoreError)
                {
                    return(null);
                }

                throw;
            }
        }
Exemplo n.º 2
0
        /// <summary>执行更新</summary>
        /// <param name="ur"></param>
        /// <returns></returns>
        public Boolean ProcessUpgrade(UpgradeInfo ur)
        {
            XTrace.WriteLine("执行更新:{0} {1}", ur.Version, ur.Source);

            var dest = ".";
            var url  = ur.Source;

            try
            {
                // 需要下载更新包
                if (!url.IsNullOrEmpty())
                {
                    var fileName = Path.GetFileName(url);
                    if (!fileName.EndsWithIgnoreCase(".zip"))
                    {
                        fileName = Rand.NextString(8) + ".zip";
                    }
                    fileName = "Update".CombinePath(fileName).EnsureDirectory(true);

                    // 清理
                    //NewLife.Net.Upgrade.DeleteBuckup(dest);
                    var ug = new Upgrade {
                        Log = XTrace.Log
                    };
                    ug.DeleteBackup(dest);

                    // 下载
                    var sw     = Stopwatch.StartNew();
                    var client = new HttpClient();
                    client.DownloadFileAsync(url, fileName).Wait();

                    sw.Stop();
                    XTrace.WriteLine("下载 {0} 到 {1} 完成,耗时 {2} 。", url, fileName, sw.Elapsed);

                    // 解压
                    var source = fileName.TrimEnd(".zip");
                    if (Directory.Exists(source))
                    {
                        Directory.Delete(source, true);
                    }
                    source.EnsureDirectory(false);
                    fileName.AsFile().Extract(source, true);

                    // 更新覆盖之前,再次清理exe/dll/pdb
                    foreach (var item in dest.AsDirectory().GetAllFiles("*.exe;*.dll;*.pdb", true))
                    {
                        WriteLog("Delete {0}", item);
                        try
                        {
                            item.Delete();
                        }
                        catch
                        {
                            var del = item.FullName + $".{Rand.Next(100000, 999999)}.del";
                            item.MoveTo(del);
                        }
                    }

                    // 覆盖
                    ug.CopyAndReplace(source, dest);
                    if (Directory.Exists(source))
                    {
                        Directory.Delete(source, true);
                    }
                }

                // 升级处理命令,可选
                var cmd = ur.Executor?.Trim();
                if (!cmd.IsNullOrEmpty())
                {
                    XTrace.WriteLine("执行更新命令:{0}", cmd);

                    var si = new ProcessStartInfo
                    {
                        UseShellExecute = true,
                    };
                    var p = cmd.IndexOf(' ');
                    if (p < 0)
                    {
                        si.FileName = cmd;
                    }
                    else
                    {
                        si.FileName  = cmd.Substring(0, p);
                        si.Arguments = cmd.Substring(p + 1);
                    }

                    Process.Start(si);
                }

                return(true);
            }
            catch (Exception ex)
            {
                XTrace.WriteLine("更新失败!");
                XTrace.WriteException(ex);

                return(false);
            }
        }
Exemplo n.º 3
0
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            XTrace.WriteLine("StopAsync");

            return(base.StopAsync(cancellationToken));
        }
Exemplo n.º 4
0
        static void Test3()
        {
            if (Console.ReadLine() == "1")
            {
                var svr = new ApiServer(1234)
                          //var svr = new ApiServer("http://*:1234")
                {
                    Log = XTrace.Log,
                    //EncoderLog = XTrace.Log,
                    StatPeriod = 10,
                };

                var ns = svr.EnsureCreate() as NetServer;
                ns.EnsureCreateServer();
                var ts = ns.Servers.FirstOrDefault(e => e is TcpServer);
                //ts.ProcessAsync = true;

                svr.Start();

                Console.ReadKey();
            }
            else
            {
                var client = new ApiClient("tcp://127.0.0.1:1234")
                {
                    Log = XTrace.Log,
                    //EncoderLog = XTrace.Log,
                    StatPeriod = 10,

                    UsePool = true,
                };
                client.Open();

                Task.Run(() =>
                {
                    var sw = Stopwatch.StartNew();
                    try
                    {
                        for (var i = 0; i < 10; i++)
                        {
                            client.InvokeAsync <Object>("Api/All", new { state = 111 }).Wait();
                        }
                    }
                    catch (Exception ex)
                    {
                        XTrace.WriteException(ex.GetTrue());
                    }
                    sw.Stop();
                    XTrace.WriteLine("总耗时 {0:n0}ms", sw.ElapsedMilliseconds);
                });

                Task.Run(() =>
                {
                    var sw = Stopwatch.StartNew();
                    try
                    {
                        for (var i = 0; i < 10; i++)
                        {
                            client.InvokeAsync <Object>("Api/All", new { state = 222 }).Wait();
                        }
                    }
                    catch (Exception ex)
                    {
                        XTrace.WriteException(ex.GetTrue());
                    }
                    sw.Stop();
                    XTrace.WriteLine("总耗时 {0:n0}ms", sw.ElapsedMilliseconds);
                });

                Task.Run(() =>
                {
                    var sw = Stopwatch.StartNew();
                    try
                    {
                        for (var i = 0; i < 10; i++)
                        {
                            client.InvokeAsync <Object>("Api/Info", new { state = 333 }).Wait();
                        }
                    }
                    catch (Exception ex)
                    {
                        XTrace.WriteException(ex.GetTrue());
                    }
                    sw.Stop();
                    XTrace.WriteLine("总耗时 {0:n0}ms", sw.ElapsedMilliseconds);
                });

                Task.Run(() =>
                {
                    var sw = Stopwatch.StartNew();
                    try
                    {
                        for (var i = 0; i < 10; i++)
                        {
                            client.InvokeAsync <Object>("Api/Info", new { state = 444 }).Wait();
                        }
                    }
                    catch (Exception ex)
                    {
                        XTrace.WriteException(ex.GetTrue());
                    }
                    sw.Stop();
                    XTrace.WriteLine("总耗时 {0:n0}ms", sw.ElapsedMilliseconds);
                });

                Console.ReadKey();
            }
        }
Exemplo n.º 5
0
        public virtual ActionResult LoginInfo(String code, String state)
        {
            var name = state + "";
            var p    = name.IndexOf('_');

            if (p > 0)
            {
                name  = state.Substring(0, p);
                state = state.Substring(p + 1);
            }

            var prov   = Provider;
            var client = prov.GetClient(name);

            client.WriteLog("LoginInfo name={0} code={1} state={2}", name, code, state);

            // 构造redirect_uri,部分提供商(百度)要求获取AccessToken的时候也要传递
            var redirect = prov.GetRedirect(Request);

            client.Authorize(redirect);

            var returnUrl = prov.GetReturnUrl(Request, false);

            try
            {
                // 获取访问令牌
                var html = client.GetAccessToken(code);

                // 如果拿不到访问令牌或用户信息,则重新跳转
                if (client.AccessToken.IsNullOrEmpty() && client.OpenID.IsNullOrEmpty() && client.UserID == 0)
                {
                    // 如果拿不到访问令牌,刷新一次,然后报错
                    if (state.EqualIgnoreCase("refresh"))
                    {
                        if (client.Log == null)
                        {
                            XTrace.WriteLine(html);
                        }

                        throw new InvalidOperationException("内部错误,无法获取令牌");
                    }

                    XTrace.WriteLine("拿不到访问令牌,重新跳转 code={0} state={1}", code, state);

                    return(RedirectToAction("Login", new { name = client.Name, r = returnUrl, state = "refresh" }));
                }

                // 获取OpenID。部分提供商不需要
                if (!client.OpenIDUrl.IsNullOrEmpty())
                {
                    client.GetOpenID();
                }
                // 获取用户信息
                if (!client.UserUrl.IsNullOrEmpty())
                {
                    client.GetUserInfo();
                }

#if __CORE__
                var url = prov.OnLogin(client, HttpContext.RequestServices);
#else
                var url = prov.OnLogin(client, HttpContext);
#endif

                // 标记登录提供商
                SetSession("Cube_Sso", client.Name);
                SetSession("Cube_Sso_Client", client);

                if (!returnUrl.IsNullOrEmpty())
                {
                    url = returnUrl;
                }

                return(Redirect(url));
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex.GetTrue());
                //throw;

                if (!state.EqualIgnoreCase("refresh"))
                {
                    return(RedirectToAction("Login", new { name = client.Name, r = returnUrl, state = "refresh" }));
                }

#if __CORE__
                return(View("CubeError", ex));
#else
                var inf = new HandleErrorInfo(ex, "Sso", nameof(LoginInfo));
                return(View("CubeError", inf));
#endif
            }
        }
Exemplo n.º 6
0
        private static void Test4()
        {
            var v = Rand.NextBytes(32);

            Console.WriteLine(v.ToBase64());

            ICache ch = null;

            //ICache ch = new DbCache();
            //ch.Set(key, v);
            //v = ch.Get<Byte[]>(key);
            //Console.WriteLine(v.ToBase64());
            //ch.Remove(key);

            Console.Clear();

            Console.Write("选择要测试的缓存:1,MemoryCache;2,DbCache;3,Redis ");
            var select = Console.ReadKey().KeyChar;

            switch (select)
            {
            case '1':
                ch = new MemoryCache();
                break;

            case '2':
                ch = new DbCache();
                break;

            case '3':
                var rds = new Redis("127.0.0.1", null, 9)
                {
                    Counter = new PerfCounter(),
                    Tracer  = new DefaultTracer {
                        Log = XTrace.Log
                    },
                };
                ch = rds;
                break;
            }

            var mode = false;

            Console.WriteLine();
            Console.Write("选择测试模式:1,顺序;2,随机 ");
            if (Console.ReadKey().KeyChar != '1')
            {
                mode = true;
            }

            var batch = 0;

            Console.WriteLine();
            Console.Write("选择输入批大小[0]:");
            batch = Console.ReadLine().ToInt();

            Console.Clear();

            //var batch = 0;
            //if (mode) batch = 1000;

            var rs = ch.Bench(mode, batch);

            XTrace.WriteLine("总测试数据:{0:n0}", rs);
            if (ch is Redis rds2)
            {
                XTrace.WriteLine(rds2.Counter + "");
            }
        }
Exemplo n.º 7
0
        private static void ylog(Session session)
        {
            string str;
            string str1;

            if (session.url.IndexOf("ylog.huya.com/g.gif") != -1)
            {
                try
                {
                    if (session.RequestHeaders.HTTPMethod != "GET")
                    {
                        object[] objArray = JsonConvert.DeserializeObject <object[]>(session.GetRequestBodyAsString());
                        for (int i = 0; i < (int)objArray.Length; i++)
                        {
                            dynamic item = objArray[i];
                            if (item.eid_desc != (dynamic)null)
                            {
                                XTrace.WriteLine(string.Format("POST ylog  eid=[{0}] eid_desc=[{1}]", item.eid, HttpHelper.URLDecode(item.eid_desc.ToString(), Encoding.UTF8)));
                            }
                            else if (item.eid != (dynamic)null)
                            {
                                XTrace.WriteLine(string.Format("POST ylog  eid=[{0}]", item.eid));
                            }
                            else if (item.rid == (dynamic)null)
                            {
                                XTrace.WriteLine(string.Format("POST ylog  {0}", JsonConvert.SerializeObject(item)));
                            }
                            else
                            {
                                XTrace.WriteLine(string.Format("POST ylog  rid=[{0}]", item.rid));
                            }
                        }
                    }
                    else
                    {
                        Tuple <string, IEnumerable <KeyValuePair <string, string> > > data = XHttpHelper.UrlToData(session.fullUrl);
                        IEnumerable <KeyValuePair <string, string> > pa = data.Item2;
                        if (pa == null)
                        {
                            XTrace.WriteLine(string.Concat("GET ylog 参数为空  ", data.Item1));
                        }
                        else
                        {
                            NullableDictionary <string, string> dic = XHttpHelper.EumKV2Dic(pa);
                            if (dic["eid_desc"] != null)
                            {
                                string[] strArrays = new string[] { "Get ylog  eid=[", dic["eid"], "] eid_desc=[", null, null };
                                string   str2      = dic["eid_desc"];
                                if (str2 != null)
                                {
                                    str1 = str2.ToString();
                                }
                                else
                                {
                                    str1 = null;
                                }
                                strArrays[3] = HttpHelper.URLDecode(str1, Encoding.UTF8);
                                strArrays[4] = "]";
                                XTrace.WriteLine(string.Concat(strArrays));
                            }
                            else if (dic["eid"] != null)
                            {
                                XTrace.WriteLine(string.Concat("GET ylog  eid=[", dic["eid"], "]"));
                            }
                            else if (dic["rid"] == null)
                            {
                                XTrace.WriteLine(string.Concat("GET ylog  ", string.Join <KeyValuePair <string, string> >(" ", pa)));
                            }
                            else
                            {
                                XTrace.WriteLine(string.Concat("GET ylog  rid=[", dic["rid"], "]"));
                            }
                        }
                        return;
                    }
                }
                catch (Exception exception)
                {
                    Exception ex = exception;
                    XTrace.WriteLine(string.Concat("分析虎牙记录请求出错 ", ex.Message, " ", session.url));
                }
            }
            else if (session.url.IndexOf("huya.com/d.gif") != -1)
            {
                if (session.RequestHeaders.HTTPMethod == "GET")
                {
                    Tuple <string, IEnumerable <KeyValuePair <string, string> > > data = XHttpHelper.UrlToData(session.fullUrl);
                    IEnumerable <KeyValuePair <string, string> > pa = data.Item2;
                    if (pa == null)
                    {
                        XTrace.WriteLine(string.Concat("GET ylog 参数为空  ", data.Item1));
                    }
                    else
                    {
                        NullableDictionary <string, string> dic = XHttpHelper.EumKV2Dic(pa);
                        if (dic["eid_desc"] != null)
                        {
                            string[] strArrays1 = new string[] { "Get ylog  eid=[", dic["eid"], "] eid_desc=[", null, null };
                            string   str3       = dic["eid_desc"];
                            if (str3 != null)
                            {
                                str = str3.ToString();
                            }
                            else
                            {
                                str = null;
                            }
                            strArrays1[3] = HttpHelper.URLDecode(str, Encoding.UTF8);
                            strArrays1[4] = "]";
                            XTrace.WriteLine(string.Concat(strArrays1));
                        }
                        else if (dic["eid"] != null)
                        {
                            XTrace.WriteLine(string.Concat("GET ylog  eid=[", dic["eid"], "]"));
                        }
                        else if (dic["rid"] == null)
                        {
                            XTrace.WriteLine(string.Concat("GET ylog  ", string.Join <KeyValuePair <string, string> >(" ", pa)));
                        }
                        else
                        {
                            XTrace.WriteLine(string.Concat("GET ylog  rid=[", dic["rid"], "]"));
                        }
                    }
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>检查并初始化数据。参数等待时间为0表示不等待</summary>
        /// <param name="ms">等待时间,-1表示不限,0表示不等待</param>
        /// <returns>如果等待,返回是否收到信号</returns>
        public Boolean WaitForInitData(Int32 ms = 1000)
        {
            // 已初始化
            if (hasCheckInitData)
            {
                return(true);
            }

            //!!! 一定一定小心堵塞的是自己
            if (initThread == Thread.CurrentThread.ManagedThreadId)
            {
                return(true);
            }

            if (!Monitor.TryEnter(_wait_lock, ms))
            {
                //if (DAL.Debug) DAL.WriteLog("开始等待初始化{0}数据{1}ms,调用栈:{2}", name, ms, XTrace.GetCaller());
                if (DAL.Debug)
                {
                    DAL.WriteLog("等待初始化{0}数据{1:n0}ms失败", ThisType.Name, ms);
                }
                return(false);
            }
            initThread = Thread.CurrentThread.ManagedThreadId;
            try
            {
                // 已初始化
                if (hasCheckInitData)
                {
                    return(true);
                }

                var name = ThisType.Name;
                if (name == TableName)
                {
                    name = String.Format("{0}@{1}", ThisType.Name, ConnName);
                }
                else
                {
                    name = String.Format("{0}#{1}@{2}", ThisType.Name, TableName, ConnName);
                }

                // 如果该实体类是首次使用检查模型,则在这个时候检查
                try
                {
                    CheckModel();
                }
                catch { }

                // 输出调用者,方便调试
                //if (DAL.Debug) DAL.WriteLog("初始化{0}数据,调用栈:{1}", name, XTrace.GetCaller());
                //if (DAL.Debug) DAL.WriteLog("初始化{0}数据", name);

                //var init = Config.GetConfig<Boolean>("XCode.InitData", true);
                var init = Setting.Current.InitData;
                if (init)
                {
                    try
                    {
                        var entity = Operate.Default as EntityBase;
                        if (entity != null)
                        {
                            entity.InitData();
                        }
                    }
                    catch (Exception ex)
                    {
                        if (XTrace.Debug)
                        {
                            XTrace.WriteLine("初始化数据出错!" + ex.ToString());
                        }
                    }
                }

                return(true);
            }
            finally
            {
                initThread       = 0;
                hasCheckInitData = true;
                Monitor.Exit(_wait_lock);
            }
        }
Exemplo n.º 9
0
        /// <summary>使用连接字符串初始化</summary>
        /// <param name="config"></param>
        public override void Init(String config)
        {
            if (config.IsNullOrEmpty())
            {
                return;
            }

            if (config == _configOld)
            {
                return;
            }
            if (!_configOld.IsNullOrEmpty())
            {
                XTrace.WriteLine("Redis[{0}]连接字符串改变!", Name);
            }

            var dic =
                config.Contains(',') && !config.Contains(';') ?
                config.SplitAsDictionary("=", ",", true) :
                config.SplitAsDictionary("=", ";", true);

            if (dic.Count > 0)
            {
                Server   = dic["Server"]?.Trim();
                UserName = dic["UserName"]?.Trim();
                Password = dic["Password"]?.Trim();
                Db       = dic["Db"].ToInt();

                if (Server.IsNullOrEmpty() && dic.TryGetValue("[0]", out var svr))
                {
                    Server = svr;
                }

                // 连接字符串可能独立写了port
                var port = dic["Port"].ToInt();
                if (port > 0 && !Server.Contains(":"))
                {
                    Server += ":" + port;
                }

                if (dic.TryGetValue("Timeout", out var str))
                {
                    Timeout = str.ToInt();
                }
                else if (dic.TryGetValue("responseTimeout", out str))
                {
                    Timeout = str.ToInt();
                }
                else if (dic.TryGetValue("connectTimeout", out str))
                {
                    Timeout = str.ToInt();
                }

                if (dic.TryGetValue("ThrowOnFailure", out str))
                {
                    ThrowOnFailure = str.ToBoolean();
                }

                if (dic.TryGetValue("MaxMessageSize", out str) && str.ToInt(-1) >= 0)
                {
                    MaxMessageSize = str.ToInt();
                }

                if (dic.TryGetValue("Expire", out str) && str.ToInt(-1) >= 0)
                {
                    Expire = str.ToInt();
                }
            }

            // 更换Redis连接字符串时,清空原连接池
            if (!_configOld.IsNullOrEmpty())
            {
                _Pool = null;
            }

            _configOld = config;
        }
Exemplo n.º 10
0
        /// <summary>检查是否安装了语音库</summary>
        void CheckVoice()
        {
            if (_type == null)
            {
                return;
            }

            try
            {
                var synth = _type.CreateInstance(new Object[0]);
                var vs    = synth.Invoke("GetInstalledVoices") as IList;
                if (vs != null && vs.Count > 0)
                {
                    var flag = false;
                    foreach (var item in vs)
                    {
                        if (XTrace.Debug)
                        {
                            XTrace.WriteLine("语音库:{0}", item.GetValue("VoiceInfo").GetValue("Description"));
                        }

                        if ((Boolean)item.GetValue("Enabled"))
                        {
                            flag = true;
                        }
                    }
                    if (flag)
                    {
                        return;
                    }
                }
            }
            catch { }

            var url = Setting.Current.PluginServer;

            XTrace.WriteLine("没有找到语音运行时,准备联网获取 {0}", url);

            var dir = ".".GetFullPath();

            if (Runtime.IsWeb)
            {
                dir = dir.CombinePath("Bin");
            }
            dir.EnsureDirectory();

            var client = new WebClientX(true, true);

            client.Log = XTrace.Log;

            var file2 = client.DownloadLinkAndExtract(url, "SpeechRuntime", dir);

            if (!file2.IsNullOrEmpty())
            {
                // 安装语音库
                var msi = "SpeechPlatformRuntime_x{0}.msi".F(Runtime.Is64BitOperatingSystem ? 64 : 86);
                msi = dir.CombinePath(msi);
                if (File.Exists(msi))
                {
                    XTrace.WriteLine("正在安装语音平台运行时 {0}", msi);
                    "msiexec".Run("/i \"" + msi + "\" /passive /norestart", 5000);
                }

                msi = "MSSpeech_TTS_zh-CN_HuiHui.msi";
                msi = dir.CombinePath(msi);
                if (File.Exists(msi))
                {
                    XTrace.WriteLine("正在安装微软TTS中文语音库 {0}", msi);
                    "msiexec".Run("/i \"" + msi + "\" /passive /norestart", 5000);
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>移除过期的缓存项</summary>
        void RemoveNotAlive(Object state)
        {
            var tx = TimerX.Current;

            if (tx != null && tx.Period == 60_000)
            {
                tx.Period = Period * 1000;
            }

            var dic = _cache;

            if (_count == 0 && !dic.Any())
            {
                return;
            }

            // 过期时间升序,用于缓存满以后删除
            var slist = new SortedList <DateTime, IList <String> >();

            // 超出个数
            if (Capacity <= 0 || _count <= Capacity)
            {
                slist = null;
            }

            // 60分钟之内过期的数据,进入LRU淘汰
            var now = TimerX.Now;
            var exp = now.AddSeconds(3600);
            var k   = 0;

            // 这里先计算,性能很重要
            var list = new List <String>();

            foreach (var item in dic)
            {
                var ci = item.Value;
                if (ci.ExpiredTime <= now)
                {
                    list.Add(item.Key);
                }
                else
                {
                    k++;
                    if (slist != null && ci.ExpiredTime < exp)
                    {
                        if (!slist.TryGetValue(ci.VisitTime, out var ss))
                        {
                            slist.Add(ci.VisitTime, ss = new List <String>());
                        }

                        ss.Add(item.Key);
                    }
                }
            }

            // 如果满了,删除前面
            if (slist != null && slist.Count > 0 && _count - list.Count > Capacity)
            {
                var over = _count - list.Count - Capacity;
                for (var i = 0; i < slist.Count && over > 0; i++)
                {
                    var ss = slist.Values[i];
                    if (ss != null && ss.Count > 0)
                    {
                        foreach (var item in ss)
                        {
                            if (over <= 0)
                            {
                                break;
                            }

                            list.Add(item);
                            over--;
                            k--;
                        }
                    }
                }

                XTrace.WriteLine("[{0}]满,{1:n0}>{2:n0},删除[{3:n0}]个", Name, _count, Capacity, list.Count);
            }

            foreach (var item in list)
            {
                _cache.Remove(item);
            }

            // 修正
            _count = k;
        }
Exemplo n.º 12
0
        void DetectSqlServer(Object state)
        {
            var item = (String)state;

            try
            {
                var dal = DAL.Create(item);
                if (dal.DbType != DatabaseType.SqlServer)
                {
                    return;
                }

                var sw = Stopwatch.StartNew();

                DataTable dt = null;

                // 列出所有数据库
                //Boolean old = DAL.ShowSQL;
                //DAL.ShowSQL = false;
                //try
                //{
                if (dal.Db.CreateMetaData().MetaDataCollections.Contains("Databases"))
                {
                    dt = dal.Db.CreateSession().GetSchema("Databases", null);
                }
                //}
                //finally { DAL.ShowSQL = old; }

                if (dt == null)
                {
                    return;
                }

                var dbprovider = dal.DbType.ToString();
                var builder    = new DbConnectionStringBuilder();
                builder.ConnectionString = dal.ConnStr;

                // 统计库名
                var n          = 0;
                var names      = new List <String>();
                var sysdbnames = new String[] { "master", "tempdb", "model", "msdb" };
                foreach (DataRow dr in dt.Rows)
                {
                    String dbname = dr[0].ToString();
                    if (Array.IndexOf(sysdbnames, dbname) >= 0)
                    {
                        continue;
                    }

                    String connName = String.Format("{0}_{1}", item, dbname);

                    builder["Database"] = dbname;
                    DAL.AddConnStr(connName, builder.ToString(), null, dbprovider);
                    n++;

                    try
                    {
                        String ver = dal.Db.ServerVersion;
                        names.Add(connName);
                    }
                    catch
                    {
                        if (DAL.ConnStrs.ContainsKey(connName))
                        {
                            DAL.ConnStrs.Remove(connName);
                        }
                    }
                }


                sw.Stop();
                XTrace.WriteLine("发现远程数据库{0}个,耗时:{1}!", n, sw.Elapsed);

                if (names != null && names.Count > 0)
                {
                    var list = new List <String>();
                    foreach (var elm in DAL.ConnStrs)
                    {
                        if (!String.IsNullOrEmpty(elm.Value))
                        {
                            list.Add(elm.Key);
                        }
                    }
                    list.AddRange(names);

                    this.Invoke(SetDatabaseList, list);
                }
            }
            catch
            {
                //if (item == localName) DAL.ConnStrs.Remove(localName);
            }
        }
Exemplo n.º 13
0
        static SevenZip()
        {
            var p = "";

            #region 附近文件
            if (p.IsNullOrEmpty())
            {
                var f = "../7z/7z.exe".GetFullPath();
                if (File.Exists(f))
                {
                    p = f;
                }

                f = "7z/7z.exe".GetFullPath();
                if (File.Exists(f))
                {
                    p = f;
                }
            }
            #endregion

            #region 注册表
            //if (p.IsNullOrEmpty())
            //{
            //    var reg = Registry.LocalMachine.OpenSubKey("Software\\7-Zip");
            //    if (reg == null) reg = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\7-Zip");
            //    if (reg != null)
            //    {
            //        var d = reg.GetValue("Path") + "";
            //        var f = d.CombinePath("7z.exe");
            //        if (File.Exists(f)) p = f;
            //    }
            //}
            #endregion

            #region X组件缓存
            var cache = Path.GetPathRoot(".".GetFullPath()).CombinePath(@"\X\7z").GetFullPath();
            if (p.IsNullOrEmpty())
            {
                var f = cache.CombinePath("7z.exe");
                if (File.Exists(f))
                {
                    p = f;
                }
            }
            #endregion

            #region 自动下载
            if (p.IsNullOrEmpty())
            {
                XTrace.WriteLine("准备下载7z扩展包");

                var url    = Setting.Current.PluginServer;
                var client = new WebClientX(true, true)
                {
                    Log = XTrace.Log
                };
                var dir  = cache;
                var file = client.DownloadLinkAndExtract(url, "7z", dir);
                if (Directory.Exists(dir))
                {
                    var f = dir.CombinePath("7z.exe");
                    if (File.Exists(f))
                    {
                        p = f;
                    }
                }
            }
            #endregion

            if (!p.IsNullOrEmpty())
            {
                _7z = p.GetFullPath();
            }

            XTrace.WriteLine("7Z目录 {0}", _7z);
        }
Exemplo n.º 14
0
        public ASObject CommandStart(TGGSession session, ASObject data)
        {
#if DEBUG
            XTrace.WriteLine("{0}:{1}工作任务领取", "WORK_ACCEPT", session.Player.User.player_name);
#endif
            var id     = Convert.ToInt64(data.FirstOrDefault(q => q.Key == "id").Value);
            var userid = session.Player.User.id;
            var mytask = tg_task.FindByid(id);
            var now    = (DateTime.Now.Ticks - 621355968000000000) / 10000;
            if (mytask == null || mytask.task_state != (int)TaskStateType.TYPE_UNRECEIVED || mytask.task_type != (int)TaskType.WORK_TASK)
            {
                return(BuildData((int)ResultType.TASK_VOCATION_NOTASK, 0, null));
            }
            var usertask = tg_task.GetTaskQueryByType(userid, (int)TaskType.WORK_TASK);
            if (usertask.Any(q => q.task_state == (int)TaskStateType.TYPE_REWARD || q.task_state == (int)TaskStateType.TYPE_UNFINISHED))
            {
                return(BuildData((int)ResultType.WORK_IS_STARTED, 0, null));
            }
            var baseinfo = Variable.BASE_TASKVOCATION.FirstOrDefault(q => q.id == mytask.task_id);
            if (baseinfo == null)
            {
                return(BuildData((int)ResultType.TASK_VOCATION_NOTASK, 0, null));
            }
            //技能验证
            if (!CheckSkill(baseinfo, session.Player.Role))
            {
                return(BuildData((int)ResultType.TASK_SKILL_LACK, 0, null));
            }
            //验证体力
            if (!PowerOperate(session.Player.Role.Kind, userid))
            {
                return(BuildData((int)ResultType.BASE_ROLE_POWER_ERROR, 0, null));
            }
            //验证冷却时间
            if (!CheckTime(baseinfo.coolingTime, userid))
            {
                return(BuildData((int)ResultType.WORK_TIME_WRONG, 0, null));
            }
            mytask.task_state = (int)TaskStateType.TYPE_UNFINISHED;

            if (mytask.task_step_type == (int)TaskStepType.RAISE_COIN)
            {
                var time = 0;
                var t    = Variable.BASE_TASKVOCATION.FirstOrDefault(m => m.id == mytask.task_id);
                if (t == null)
                {
                    time = 0;
                }
                else
                {
                    time = t.time * 1000;
                }

                Int64 timeStamp = now;
                var   starttime = timeStamp;
                var   stoptime  = timeStamp + time;
                mytask.task_starttime = starttime;
                mytask.task_endtime   = stoptime;
            }

            TaskThreadStart(mytask);//接受任务启动线程
            var workinfo    = Common.GetInstance().GetWorkInfo(userid);
            var coolingtime = workinfo == null ? 0 : workinfo.CoolingTime;
            mytask.task_endtime = now + baseinfo.limitTime * 1000;
            Common.GetInstance().LimitTimeThreading(baseinfo.limitTime, mytask);

            workinfo.LimitTime = mytask.task_endtime;
            mytask.Update();
            return(BuildData((int)ResultType.SUCCESS, coolingtime, mytask));
        }
Exemplo n.º 15
0
        public object DoPayOrder(string ordernum, string random = "", string timeStamp = "", string signature = "")
        {
            if (!AutoCheckQueryStringSignature())
            {
                return(reJson);
            }

            //获取订单
            Order entity = Order.Find(Order._.OrderNum == ordernum);

            if (entity == null)
            {
                reJson.code    = 40000;
                reJson.message = "系统找不到本订单!";
                return(reJson);
            }
            //判断订单状态
            if (entity.OrderStatus == Utils.OrdersState[3])
            {
                reJson.code    = 40000;
                reJson.message = "已完成订单不允许支付!";
                return(reJson);
            }
            if (entity.PaymentStatus != Utils.PaymentState[0])
            {
                reJson.code    = 40000;
                reJson.message = "当前订单支付状态不允许支付!";
                return(reJson);
            }
            //获取用户并判断是否是已经注册用户
            Member my = Member.FindById(entity.UId);

            if (my == null || string.IsNullOrEmpty(my.WeixinAppOpenId))
            {
                reJson.code    = 40000;
                reJson.message = "用户状态错误,无法使用本功能!";
                return(reJson);
            }
            //开始生成支付订单
            OnlinePayOrder model = new OnlinePayOrder();

            model.OrderId       = entity.Id;
            model.OrderNum      = entity.OrderNum;
            model.PayId         = 1;
            model.PaymentNotes  = "微信支付";
            model.PaymentStatus = Utils.PaymentState[0];
            model.PayOrderNum   = Utils.GetOrderNum();//在线支付订单的订单号
            model.PayType       = "微信支付";
            model.TotalPrice    = entity.TotalPay;
            model.TotalQty      = entity.TotalQty;
            model.UId           = entity.UId;
            model.IP            = Utils.GetIP();
            model.IsOK          = 0;
            model.AddTime       = DateTime.Now;
            model.Insert();

            //写入日志
            OrderLog log = new OrderLog();

            log.AddTime  = DateTime.Now;
            log.OrderId  = entity.Id;
            log.OrderNum = entity.OrderNum;
            log.UId      = entity.UId;
            log.Actions  = "用户使用微信支付;支付订单号:" + model.PayOrderNum;
            log.Insert();

            Core.Config cfg        = Core.Config.GetSystemConfig();
            string      appId      = cfg.WXAppId;     // ConfigurationManager.AppSettings["WeixinAppId"];
            string      appSecrect = cfg.WXAppSecret; // ConfigurationManager.AppSettings["WeixinAppSecrect"];
            string      wxmchId    = cfg.MCHId;       // ConfigurationManager.AppSettings["WeixinMCHId"];
            string      wxmchKey   = cfg.MCHKey;      // ConfigurationManager.AppSettings["WeixinMCHKey"];



            TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, Utils.GetServerUrl() + "/wxpayment/notify");

            TenPayV3Info.TenPayV3Notify = Utils.GetServerUrl() + "/wxpayment/notify";
            XTrace.WriteLine("微信支付异步通知地址:" + TenPayV3Info.TenPayV3Notify);
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);
            var            sp_billno         = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(26);//最多32位
            var            nonceStr          = TenPayV3Util.GetNoncestr();
            string         rtimeStamp        = Utils.GetTimeStamp();

            //创建请求统一订单接口参数
            var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, entity.Title, model.PayOrderNum, (int)(entity.TotalPay * 100), Utils.GetIP(), TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, my.WeixinAppOpenId, TenPayV3Info.Key, nonceStr);

            //返回给微信的请求
            RequestHandler res = new RequestHandler(null);

            try
            {
                //调用统一订单接口
                var result = TenPayV3.Unifiedorder(xmlDataInfo);
                XTrace.WriteLine("微信支付统一下单返回:" + JsonConvert.SerializeObject(result));

                if (result.return_code == "FAIL")
                {
                    reJson.code    = 40005;
                    reJson.message = result.return_msg;
                    return(reJson);
                }
                string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key);
                //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3
                //paySign = MD5(appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111)
                string paySign = Utils.MD5($"appId={TenPayV3Info.AppId}&nonceStr={nonceStr}&package=prepay_id={result.prepay_id}&signType=MD5&timeStamp={rtimeStamp}&key={TenPayV3Info.Key}").ToUpper();

                string package = $"prepay_id={result.prepay_id}";

                dynamic detail = new { timeStamp = rtimeStamp, nonceStr = nonceStr, package = package, signType = "MD5", paySign = paySign };

                reJson.code    = 0;
                reJson.message = "下单成功!";
                reJson.detail  = detail;
                return(reJson);
            }
            catch (Exception ex)
            {
                res.SetParameter("return_code", "FAIL");
                res.SetParameter("return_msg", "统一下单失败");
                XTrace.WriteLine($"统一下单失败:{ex.Message}");

                reJson.code    = 40005;
                reJson.message = "统一下单失败,请联系管理员!";
                return(reJson);
            }
        }
Exemplo n.º 16
0
        /// <summary>创建连接客户端</summary>
        /// <returns></returns>
        protected virtual RedisClient OnCreate()
        {
            var svr = Server?.Trim();

            if (svr.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(Server));
            }

            var svrs = _servers;

            if (svrs == null)
            {
                var ss   = svr.Split(",");
                var uris = new NetUri[ss.Length];
                for (var i = 0; i < ss.Length; i++)
                {
                    var svr2 = ss[i];
                    if (!svr2.Contains("://"))
                    {
                        svr2 = "tcp://" + svr2;
                    }

                    var uri = new NetUri(svr2);
                    if (uri.Port == 0)
                    {
                        uri.Port = 6379;
                    }
                    uris[i] = uri;
                }
                svrs = _servers = uris;
            }

            // 一定时间后,切换回来主节点
            var idx = _idxServer;

            if (idx > 0)
            {
                var now = DateTime.Now;
                if (_nextTrace.Year < 2000)
                {
                    _nextTrace = now.AddSeconds(300);
                }
                if (now > _nextTrace)
                {
                    _nextTrace = DateTime.MinValue;

                    idx = _idxServer = 0;
                }
            }

            if (idx != _idxLast)
            {
                XTrace.WriteLine("Redis使用 {0}", svrs[idx % svrs.Length]);

                _idxLast = idx;
            }

            var rc = new RedisClient(this, svrs[idx % svrs.Length])
            {
                Log = Log
            };

            //if (rds.Db > 0) rc.Select(rds.Db);

            return(rc);
        }
Exemplo n.º 17
0
 public void Set(string key, string value)
 {
     XTrace.WriteLine($"设置验证码:{key}------>{value}");
     _cache.Set(key, value);
 }
Exemplo n.º 18
0
        /// <summary>检查并初始化数据。参数等待时间为0表示不等待</summary>
        /// <param name="ms">等待时间,-1表示不限,0表示不等待</param>
        /// <returns>如果等待,返回是否收到信号</returns>
        public Boolean WaitForInitData(Int32 ms = 3000)
        {
            // 已初始化
            if (hasCheckInitData)
            {
                return(true);
            }

            var tid = Thread.CurrentThread.ManagedThreadId;

            //!!! 一定一定小心堵塞的是自己
            if (initThread == tid)
            {
                return(true);
            }

            if (!Monitor.TryEnter(_wait_lock, ms))
            {
                //if (DAL.Debug) DAL.WriteLog("等待初始化{0}数据{1}ms,调用栈:{2}", ThisType.Name, ms, XTrace.GetCaller(1, 8));
                if (DAL.Debug)
                {
                    DAL.WriteLog("等待初始化{0}数据{1:n0}ms失败 initThread={2}", ThisType.Name, ms, initThread);
                }
                return(false);
            }
            //initThread = tid;
            try
            {
                // 已初始化
                if (hasCheckInitData)
                {
                    return(true);
                }

                var name = ThisType.Name;
                if (name == TableName)
                {
                    name = String.Format("{0}@{1}", ThisType.Name, ConnName);
                }
                else
                {
                    name = String.Format("{0}#{1}@{2}", ThisType.Name, TableName, ConnName);
                }

                var task = Task.Factory.StartNew(() =>
                {
                    initThread = Thread.CurrentThread.ManagedThreadId;

                    // 如果该实体类是首次使用检查模型,则在这个时候检查
                    try
                    {
                        CheckModel();
                    }
                    catch (Exception ex) { XTrace.WriteException(ex); }

                    //var init = Setting.Current.InitData;
                    var init = this == Default;
                    if (init)
                    {
                        //BeginTrans();
                        try
                        {
                            if (Operate.Default is EntityBase entity)
                            {
                                entity.InitData();
                                //// 异步执行初始化,只等一会,避免死锁
                                //var task = TaskEx.Run(() => entity.InitData());
                                //if (!task.Wait(ms) && DAL.Debug) DAL.WriteLog("{0}未能在{1:n0}ms内完成数据初始化 Task={2}", ThisType.Name, ms, task.Id);
                            }

                            //Commit();
                        }
                        catch (Exception ex)
                        {
                            if (XTrace.Debug)
                            {
                                XTrace.WriteLine("初始化数据出错!" + ex.ToString());
                            }

                            //Rollback();
                        }
                    }
                });
                task.Wait(3_000);

                return(true);
            }
            finally
            {
                initThread       = 0;
                hasCheckInitData = true;
                Monitor.Exit(_wait_lock);
            }
        }
Exemplo n.º 19
0
        /// <summary>从内容中分析得到地区并保存。以民政部颁布的行政区划代码为准</summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static IList <Area> ParseAndSave(String html)
        {
            var all = Parse(html).ToList();

            // 预备好所有三级数据
            var list = FindAll(_.ID > 10_00_00 & _.ID < 99_99_99);

            var rs = new List <Area>();

            foreach (var item in all)
            {
                // 查找是否已存在
                var r = list.Find(e => e.ID == item.ID);
                if (r == null && item.ID > 99_99_99)
                {
                    r = FindByID(item.ID);
                }

                if (r == null)
                {
                    r = item;

                    // 找到它的上级
                    var pid = GetParent(item.ID);

                    // 部分区县由省直管,中间没有第二级
                    if (pid > 0 && !list.Any(e => e.ID == pid) && !all.Any(e => e.ID == pid))
                    {
                        var pid2 = GetParent(pid);
                        var r2   = all.Find(e => e.ID == pid2);
                        if (r2 != null)
                        {
                            var r3 = new Area
                            {
                                ID       = pid,
                                ParentID = pid2,
                                Enable   = true,
                            };

                            // 直辖市处理市辖区
                            if (r2.Name.EqualIgnoreCase("北京", "天津", "上海", "重庆") && r3.ID != 500200)
                            {
                                r3.Name = "市辖区";
                            }
                            else
                            {
                                r3.Name = "直辖县";
                            }

                            r3.FixLevel();
                            r3.FixName();
                            rs.Add(r3);
                            list.Add(r3);
                        }
                        else
                        {
                            XTrace.WriteLine("无法识别地区的父级 {0} {1}", item.ID, item.Name);
                        }
                    }

                    r.ParentID = pid;
                    r.Enable   = true;
                }
                else
                {
                    r.FullName = item.FullName;
                }

                r.FixLevel();
                r.FixName();

                rs.Add(r);
            }

            rs.Save(true);

            return(rs);
        }
Exemplo n.º 20
0
        /// <summary>为Xml模型文件生成实体类</summary>
        /// <param name="tables">模型文件</param>
        /// <param name="output">输出目录</param>
        /// <param name="nameSpace">命名空间</param>
        /// <param name="connName">连接名</param>
        /// <param name="baseClass">基类</param>
        /// <param name="chineseFileName">是否中文名称</param>
        /// <param name="ignoreNameCase">忽略表名、字段名大小写(true 当前表名与类名称相同时,则自动省略该属性,反之 false)</param>
        public static Int32 BuildTables(IList <IDataTable> tables, String output = null, String nameSpace = null, String connName = null, String baseClass = null, Boolean chineseFileName = true, Boolean ignoreNameCase = true)
        {
            if (tables == null || tables.Count == 0)
            {
                return(0);
            }

            output = output.GetBasePath();

            // 连接名
            if (connName.IsNullOrEmpty() && !nameSpace.IsNullOrEmpty() && nameSpace.Contains("."))
            {
                connName = nameSpace.Substring(nameSpace.LastIndexOf(".") + 1);
            }

            XTrace.WriteLine("代码生成:{0} 输出:{1} 命名空间:{2} 连接名:{3} 基类:{4}", tables.Count, output, nameSpace, connName, baseClass);

            var count = 0;

            foreach (var item in tables)
            {
                var builder = new EntityBuilder
                {
                    Table       = item,
                    AllTables   = tables,
                    GenericType = item.Properties["RenderGenEntity"].ToBoolean()
                };

                // 命名空间
                var str = item.Properties["Namespace"];
                if (str.IsNullOrEmpty())
                {
                    str = nameSpace;
                }
                builder.Namespace = str;

                // 连接名
                str = item.ConnName;
                if (str.IsNullOrEmpty())
                {
                    str = connName;
                }
                builder.ConnName = str;

                // 基类
                str = item.Properties["BaseClass"];
                if (str.IsNullOrEmpty())
                {
                    str = baseClass;
                }
                builder.BaseClass = str;

                // 名称忽略大小写(默认忽略)
                if (item.IgnoreNameCase.IsNullOrEmpty() && !ignoreNameCase)
                {
                    item.IgnoreNameCase = ignoreNameCase + "";
                }
                item.Properties.Remove("NameIgnoreCase");

                if (Debug)
                {
                    builder.Log = XTrace.Log;
                }

                builder.Execute();

                // 输出目录
                str            = item.Properties["Output"];
                str            = str.IsNullOrEmpty() ? output : str.GetBasePath();
                builder.Output = str;
                builder.Save(null, true, chineseFileName);

                builder.Business = true;
                builder.Execute();
                builder.Save(null, false, chineseFileName);

                count++;
            }

            return(count);
        }
Exemplo n.º 21
0
        public static Int32 Run(this String cmd, String?arguments = null, Int32 msWait = 0, Action <String?>?output = null, Action <Process>?onExit = null, String?working = null)
        {
            if (XTrace.Debug)
            {
                XTrace.WriteLine("Run {0} {1} {2}", cmd, arguments, msWait);
            }

            var p  = new Process();
            var si = p.StartInfo;

            si.FileName = cmd;
            if (arguments != null)
            {
                si.Arguments = arguments;
            }
            si.WindowStyle = ProcessWindowStyle.Hidden;
            if (!String.IsNullOrWhiteSpace(working))
            {
                si.WorkingDirectory = working;
            }
            // 对于控制台项目,这里需要捕获输出
            if (msWait > 0)
            {
                si.UseShellExecute        = false;
                si.RedirectStandardOutput = true;
                si.RedirectStandardError  = true;
                if (output != null)
                {
                    p.OutputDataReceived += (s, e) => output(e.Data);
                    p.ErrorDataReceived  += (s, e) => output(e.Data);
                }
                else if (NewLife.Runtime.IsConsole)
                {
                    p.OutputDataReceived += (s, e) => { if (e.Data != null)
                                                        {
                                                            XTrace.WriteLine(e.Data);
                                                        }
                    };
                    p.ErrorDataReceived += (s, e) => { if (e.Data != null)
                                                       {
                                                           XTrace.Log.Error(e.Data);
                                                       }
                    };
                }
            }
            if (onExit != null)
            {
                p.Exited += (s, e) => { if (s is Process proc)
                                        {
                                            onExit(proc);
                                        }
                }
            }
            ;

            p.Start();
            if (msWait > 0 && (output != null || NewLife.Runtime.IsConsole))
            {
                p.BeginOutputReadLine();
                p.BeginErrorReadLine();
            }

            if (msWait == 0)
            {
                return(-1);
            }

            // 如果未退出,则不能拿到退出代码
            if (msWait < 0)
            {
                p.WaitForExit();
            }
            else if (!p.WaitForExit(msWait))
            {
                return(-1);
            }

            return(p.ExitCode);
        }

        #endregion
    }
Exemplo n.º 22
0
        /// <summary>为Xml模型文件生成实体类</summary>
        /// <param name="xmlFile">模型文件</param>
        /// <param name="output">输出目录</param>
        /// <param name="nameSpace">命名空间</param>
        /// <param name="connName">连接名</param>
        /// <param name="chineseFileName">中文文件名</param>
        /// <param name="ignoreNameCase">忽略表名、字段名大小写(true 当前表名与类名称相同时,则自动省略该属性,反之 false)</param>
        public static Int32 Build(String xmlFile = null, String output = null, String nameSpace = null, String connName = null, Boolean?chineseFileName = null, Boolean?ignoreNameCase = null)
        {
            if (xmlFile.IsNullOrEmpty())
            {
                var di = ".".GetBasePath().AsDirectory();
                XTrace.WriteLine("未指定模型文件,准备从目录中查找第一个xml文件 {0}", di.FullName);
                // 选当前目录第一个
                xmlFile = di.GetFiles("*.xml", SearchOption.TopDirectoryOnly).FirstOrDefault()?.FullName;
            }

            if (xmlFile.IsNullOrEmpty())
            {
                throw new Exception("找不到任何模型文件!");
            }

            xmlFile = xmlFile.GetBasePath();
            if (!File.Exists(xmlFile))
            {
                throw new FileNotFoundException("指定模型文件不存在!", xmlFile);
            }

            // 导入模型
            var xml  = File.ReadAllText(xmlFile);
            var atts = new NullableDictionary <String, String>(StringComparer.OrdinalIgnoreCase)
            {
                ["xmlns"]             = "http://www.newlifex.com/Model2020.xsd",
                ["xmlns:xs"]          = "http://www.w3.org/2001/XMLSchema-instance",
                ["xs:schemaLocation"] = "http://www.newlifex.com http://www.newlifex.com/Model2020.xsd"
            };

            // 导入模型
            var tables = ModelHelper.FromXml(xml, DAL.CreateTable, atts);

            if (tables.Count == 0)
            {
                return(0);
            }

            // 输出
            if (!output.IsNullOrEmpty())
            {
                atts["Output"] = output;
            }
            else
            {
                output = atts["Output"];
            }
            if (output.IsNullOrEmpty())
            {
                output = Path.GetDirectoryName(xmlFile);
            }

            // 命名空间
            if (!nameSpace.IsNullOrEmpty())
            {
                atts["NameSpace"] = nameSpace;
            }
            else
            {
                nameSpace = atts["NameSpace"];
            }
            if (nameSpace.IsNullOrEmpty())
            {
                nameSpace = Path.GetFileNameWithoutExtension(xmlFile);
            }

            // 连接名
            if (!connName.IsNullOrEmpty())
            {
                atts["ConnName"] = connName;
            }
            else
            {
                connName = atts["ConnName"];
            }
            if (connName.IsNullOrEmpty() && !nameSpace.IsNullOrEmpty())
            {
                connName = nameSpace.Split(".").LastOrDefault(e => !e.EqualIgnoreCase("Entity"));
            }

            // 基类
            var baseClass = "";

            if (!baseClass.IsNullOrEmpty())
            {
                atts["BaseClass"] = baseClass;
            }
            else
            {
                baseClass = atts["BaseClass"];
            }

            // 中文文件名
            if (chineseFileName != null)
            {
                atts["ChineseFileName"] = chineseFileName.Value ? "True" : "False";
            }
            else
            {
                chineseFileName = atts["ChineseFileName"].ToBoolean(true);
            }

            // 忽略表名/字段名称大小写
            if (ignoreNameCase != null)
            {
                atts["IgnoreNameCase"] = ignoreNameCase.Value ? "True" : "False";
            }
            else
            {
                var str = atts["IgnoreNameCase"];
                if (str.IsNullOrEmpty())
                {
                    str = atts["NameIgnoreCase"];
                }
                ignoreNameCase = str.ToBoolean();
            }

            XTrace.WriteLine("代码生成源:{0}", xmlFile);

            var rs = BuildTables(tables, output, nameSpace, connName, baseClass, chineseFileName.Value, ignoreNameCase.Value);

            // 确保输出空特性
            if (atts["Output"].IsNullOrEmpty())
            {
                atts["Output"] = "";
            }
            if (atts["NameSpace"].IsNullOrEmpty())
            {
                atts["NameSpace"] = "";
            }
            if (atts["ConnName"].IsNullOrEmpty())
            {
                atts["ConnName"] = "";
            }
            if (atts["BaseClass"].IsNullOrEmpty())
            {
                atts["BaseClass"] = "Entity";
            }
            if (atts["IgnoreNameCase"].IsNullOrEmpty())
            {
                atts["IgnoreNameCase"] = true + "";
            }
            atts.Remove("NameIgnoreCase");

            // 更新xsd
            atts["xmlns"]             = atts["xmlns"].Replace("ModelSchema", "Model2020");
            atts["xs:schemaLocation"] = atts["xs:schemaLocation"].Replace("ModelSchema", "Model2020");

            // 保存模型文件
            var xml2 = ModelHelper.ToXml(tables, atts);

            if (xml != xml2)
            {
                File.WriteAllText(xmlFile, xml2);
            }

            return(rs);
        }
Exemplo n.º 23
0
        static void Test6()
        {
            // 缓存默认实现Cache.Default是MemoryCache,可修改
            //var ic = Cache.Default;
            //var ic = new MemoryCache();

            // 实例化Redis,默认端口6379可以省略,密码有两种写法
            //var ic = Redis.Create("127.0.0.1", 7);
            //var ic = Redis.Create("[email protected]:6379", 7);
            var ic = Redis.Create("server=127.0.0.1:6379;password=newlife", 7);

            ic.Log = XTrace.Log; // 调试日志。正式使用时注释

            var user = new User {
                Name = "NewLife", CreateTime = DateTime.Now
            };

            ic.Set("user", user, 3600);
            var user2 = ic.Get <User>("user");

            XTrace.WriteLine("Json: {0}", ic.Get <String>("user"));
            if (ic.ContainsKey("user"))
            {
                XTrace.WriteLine("存在!");
            }
            ic.Remove("user");

            var dic = new Dictionary <String, Object>
            {
                ["name"]  = "NewLife",
                ["time"]  = DateTime.Now,
                ["count"] = 1234
            };

            ic.SetAll(dic, 120);

            var vs = ic.GetAll <String>(dic.Keys);

            XTrace.WriteLine(vs.Join(",", e => $"{e.Key}={e.Value}"));

            var flag = ic.Add("count", 5678);

            XTrace.WriteLine(flag ? "Add成功" : "Add失败");
            var ori   = ic.Replace("count", 777);
            var count = ic.Get <Int32>("count");

            XTrace.WriteLine("count由{0}替换为{1}", ori, count);

            ic.Increment("count", 11);
            var count2 = ic.Decrement("count", 10);

            XTrace.WriteLine("count={0}", count2);

            //var inf = ic.GetInfo();
            //foreach (var item in inf)
            //{
            //    Console.WriteLine("{0}:\t{1}", item.Key, item.Value);
            //}

            for (var i = 0; i < 20; i++)
            {
                try
                {
                    ic.Set("k" + i, i, 30);
                }
                catch (Exception ex)
                {
                    //XTrace.WriteException(ex);
                    XTrace.WriteLine(ex.Message);
                }
                Thread.Sleep(3_000);
            }

            //ic.Bench();
        }
Exemplo n.º 24
0
        /// <summary>获取可用于生成权限菜单的Action集合</summary>
        /// <param name="menu">该控制器所在菜单</param>
        /// <returns></returns>
        protected virtual IDictionary <MethodInfo, Int32> ScanActionMenu(IMenu menu)
        {
            var dic = new Dictionary <MethodInfo, Int32>();

            var type = GetType();

            // 添加该类型下的所有Action
            foreach (var method in type.GetMethods())
            {
                if (method.IsStatic || !method.IsPublic)
                {
                    continue;
                }

                if (!typeof(ActionResult).IsAssignableFrom(method.ReturnType))
                {
                    continue;
                }

                if (method.GetCustomAttribute <HttpPostAttribute>() != null)
                {
                    continue;
                }
                if (method.GetCustomAttribute <AllowAnonymousAttribute>() != null)
                {
                    continue;
                }

                var att = method.GetCustomAttribute <EntityAuthorizeAttribute>();
                if (att == null)
                {
                    dic.Add(method, 0);
                }
                else
                {
                    var name = att.ResourceName;
                    var pm   = (Int32)att.Permission;
                    if (name.IsNullOrEmpty() || name == type.Name.TrimEnd("Controller"))
                    {
                        dic.Add(method, pm);
                    }
                    else
                    {
                        // 指定了资源名称,也就是专有菜单
                        var nodeName = method.Name;
                        var dis      = method.GetDisplayName();
                        var node     = menu.Parent.FindByPath(nodeName);
                        if (node == null)
                        {
                            XTrace.WriteLine("为控制器{0}添加独立菜单{1}[{2}]", type.FullName, nodeName, name);
                            node = menu.Parent.Add(nodeName, dis, menu.Url + "/" + nodeName);
                        }

                        // 权限名
                        if (pm >= 0x10)
                        {
                            node.Permissions[pm] = dis ?? method.Name;
                        }
                        else if (att.Permission.ToString().Contains("|"))
                        {
                            node.Permissions[pm] = att.Permission.GetDescription();
                        }
                        else
                        {
                            // 附加的独立Action菜单,遍历所有权限位
                            var n = 1;
                            for (int i = 0; i < 8; i++)
                            {
                                var v = (PermissionFlags)n;
                                if (att.Permission.Has(v))
                                {
                                    node.Permissions[n] = v.GetDescription();
                                }

                                n <<= 1;
                            }
                        }

                        node.Save();
                    }
                }
            }

            return(dic);
        }
Exemplo n.º 25
0
        /// <summary>心跳</summary>
        /// <returns></returns>
        public async Task <Object> Ping()
        {
            try
            {
                var inf = GetHeartInfo();

                var rs = await PingAsync(inf);

                if (rs != null)
                {
                    // 由服务器改变采样频率
                    if (rs.Period > 0)
                    {
                        _timer.Period = rs.Period * 1000;
                    }

                    var dt = rs.Time.ToDateTime();
                    if (dt.Year > 2000)
                    {
                        // 计算延迟
                        var ts = DateTime.UtcNow - dt;
                        var ms = (Int32)ts.TotalMilliseconds;
                        if (Delay > 0)
                        {
                            Delay = (Delay + ms) / 2;
                        }
                        else
                        {
                            Delay = ms;
                        }
                    }

                    // 推队列
                    if (rs.Commands != null && rs.Commands.Length > 0)
                    {
                        foreach (var item in rs.Commands)
                        {
                            CommandQueue.Publish(item.Command, item);
                        }
                    }

                    // 应用服务
                    if (rs.Services != null && rs.Services.Length > 0)
                    {
                        Manager.Add(rs.Services);
                        Manager.CheckService();
                    }
                }

                return(rs);
            }
            catch (Exception ex)
            {
                var ex2 = ex.GetTrue();
                if (ex2 is ApiException aex && (aex.Code == 402 || aex.Code == 403))
                {
                    XTrace.WriteLine("重新登录");
                    return(Login());
                }

                //XTrace.WriteLine(inf.ToJson());
                XTrace.WriteLine("心跳异常 {0}", (String)ex.GetTrue().Message);

                throw;
            }
        }
Exemplo n.º 26
0
        /// <summary>写入</summary>
        /// <param name="writer"></param>
        /// <param name="value">数值</param>
        /// <param name="writeDefaultValueMember">是否写数值为默认值的成员。为了节省空间,默认不写。</param>
        public static void WriteXml(XmlWriter writer, Object value, Boolean writeDefaultValueMember = false)
        {
            var type = value.GetType();
            var def  = GetDefault(type);

            if (value is IDataColumn)
            {
                //var dc2 = def as IDataColumn;
                var value2 = value as IDataColumn;
                // 需要重新创建,因为GetDefault带有缓存
                var dc2 = type.CreateInstance() as IDataColumn;
                dc2.DataType = value2.DataType;
                dc2.Length   = value2.Length;
                def          = Fix(dc2, value2);
            }

            String name = null;

            // 基本类型,输出为特性
            foreach (var pi in type.GetProperties(true))
            {
                if (!pi.CanWrite)
                {
                    continue;
                }
                //if (pi.GetCustomAttribute<XmlIgnoreAttribute>(false) != null) continue;
                // 忽略ID
                if (pi.Name == "ID")
                {
                    continue;
                }
                // IDataIndex跳过默认Name
                if (value is IDataIndex && pi.Name.EqualIgnoreCase("Name"))
                {
                    var di = value as IDataIndex;
                    if (di.Name.EqualIgnoreCase(ModelResolver.Current.GetName(di)))
                    {
                        continue;
                    }
                }

                var code = Type.GetTypeCode(pi.PropertyType);

                var obj = value.GetValue(pi);
                // 默认值不参与序列化,节省空间
                if (!writeDefaultValueMember)
                {
                    var dobj = def.GetValue(pi);
                    if (Object.Equals(obj, dobj))
                    {
                        continue;
                    }
                    if (code == TypeCode.String && "" + obj == "" + dobj)
                    {
                        continue;
                    }
                }

                if (code == TypeCode.String)
                {
                    // 如果别名与名称相同,则跳过,不区分大小写
                    if (pi.Name == "Name")
                    {
                        name = (String)obj;
                    }
                    else if (pi.Name == "TableName" || pi.Name == "ColumnName")
                    {
                        if (name.EqualIgnoreCase((String)obj))
                        {
                            continue;
                        }
                    }
                }
                else if (code == TypeCode.Object)
                {
                    var ptype = pi.PropertyType;
                    if (ptype.IsArray || ptype.As <IEnumerable>() || obj is IEnumerable)
                    {
                        var sb  = new StringBuilder();
                        var arr = obj as IEnumerable;
                        foreach (var elm in arr)
                        {
                            if (sb.Length > 0)
                            {
                                sb.Append(",");
                            }
                            sb.Append(elm);
                        }
                        obj = sb.ToString();
                    }
                    else if (pi.PropertyType == typeof(Type))
                    {
                        obj = (obj as Type).Name;
                    }
                    else
                    {
                        // 其它的不支持,跳过
                        if (XTrace.Debug)
                        {
                            XTrace.WriteLine("不支持的类型[{0} {1}]!", pi.PropertyType.Name, pi.Name);
                        }

                        continue;
                    }
                    //if (item.Type == typeof(Type)) obj = (obj as Type).Name;
                }
                writer.WriteAttributeString(pi.Name, obj?.ToString());
            }

            if (value is IDataTable)
            {
                var table = value as IDataTable;
                // 写入扩展属性作为特性
                if (table.Properties.Count > 0)
                {
                    foreach (var item in table.Properties)
                    {
                        writer.WriteAttributeString(item.Key, item.Value);
                    }
                }
            }
            else if (value is IDataColumn)
            {
                var column = value as IDataColumn;
                // 写入扩展属性作为特性
                if (column.Properties.Count > 0)
                {
                    foreach (var item in column.Properties)
                    {
                        if (!item.Key.EqualIgnoreCase("DisplayName", "Precision", "Scale", "NumOfByte"))
                        {
                            writer.WriteAttributeString(item.Key, item.Value);
                        }
                    }
                }
            }
        }
Exemplo n.º 27
0
 static EntityModelBinderProvider()
 {
     XTrace.WriteLine("注册实体模型绑定器:{0}", typeof(EntityModelBinderProvider).FullName);
     ModelBinderProviders.BinderProviders.Add(new EntityModelBinderProvider());
 }
Exemplo n.º 28
0
        ///// <summary>输出日志</summary>
        ///// <param name="msg"></param>
        //public static void WriteLog(String msg) { DAL.WriteLog(msg); }

        /// <summary>输出日志</summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public static void WriteLog(String format, params Object[] args)
        {
            //DAL.WriteLog(format, args);
            XTrace.WriteLine(format, args);
        }
Exemplo n.º 29
0
        /// <summary>加载插件</summary>
        /// <param name="typeName"></param>
        /// <param name="disname"></param>
        /// <param name="dll"></param>
        /// <param name="linkName"></param>
        /// <param name="urls">提供下载地址的多个目标页面</param>
        /// <returns></returns>
        public static Type LoadPlugin(String typeName, String disname, String dll, String linkName, String urls = null)
        {
            var type = typeName.GetTypeEx(true);

            if (type != null)
            {
                return(type);
            }

            if (dll.IsNullOrEmpty())
            {
                return(null);
            }

            lock (typeName)
            {
                var set  = Setting.Current;
                var plug = set.GetPluginPath();

                var file = "";
                if (!dll.IsNullOrEmpty())
                {
                    // 先检查当前目录,再检查插件目录
                    file = dll.GetFullPath();
                    if (!File.Exists(file) && Runtime.IsWeb)
                    {
                        file = "Bin".GetFullPath().CombinePath(dll);
                    }
                    if (!File.Exists(file))
                    {
                        file = plug.CombinePath(dll);
                    }
                }

                if (urls.IsNullOrEmpty())
                {
                    urls = set.PluginServer;
                }

                // 如果本地没有数据库,则从网络下载
                if (!File.Exists(file))
                {
                    XTrace.WriteLine("{0}不存在或平台版本不正确,准备联网获取 {1}", disname ?? dll, urls);

                    var client = new WebClientX()
                    {
                        Log = XTrace.Log
                    };
                    var dir   = Path.GetDirectoryName(file);
                    var file2 = client.DownloadLinkAndExtract(urls, linkName, dir);
                    client.TryDispose();
                }
                if (!File.Exists(file))
                {
                    XTrace.WriteLine("未找到 {0} {1}", disname, dll);
                    return(null);
                }

                //return Assembly.LoadFrom(file).GetType(typeName);
                return(typeName.GetTypeEx(true));
            }
        }
Exemplo n.º 30
0
        protected override void InitData()
        {
            base.InitData();

            // InitData一般用于当数据表没有数据时添加一些默认数据,该实体类的任何第一次数据库操作都会触发该方法,默认异步调用
            // Meta.Count是快速取得表记录数
            if (Meta.Count > 0)
            {
                return;
            }

            // 需要注意的是,如果该方法调用了其它实体类的首次数据库操作,目标实体类的数据初始化将会在同一个线程完成
            if (XTrace.Debug)
            {
                XTrace.WriteLine("开始初始化{0}[{1}]数据……", typeof(Button).Name, Meta.Table.DataTable.DisplayName);
            }

            var add = new Button();

            add.Code         = "add";
            add.Name         = "添加";
            add.Icon         = "fa-plus";
            add.Location     = 1;
            add.JsEvent      = "viewModel.onDataAdding();";
            add.AllowUpdate  = true;
            add.AllowDelete  = true;
            add.Remark       = "添加";
            add.Sort         = 9999;
            add.CreateUserID = 1;
            add.CreateDate   = DateTime.Now;
            add.UpdateUserID = 1;
            add.UpdateDate   = DateTime.Now;
            add.Insert();

            var edit = new Button();

            edit.Code         = "edit";
            edit.Name         = "编辑";
            edit.Icon         = "fa-pencil-square-o";
            edit.Location     = 2;
            edit.JsEvent      = "viewModel.onDataUpdating(id);";
            edit.AllowUpdate  = true;
            edit.AllowDelete  = true;
            edit.Remark       = "编辑";
            edit.Sort         = 9997;
            edit.CreateUserID = 1;
            edit.CreateDate   = DateTime.Now;
            edit.UpdateUserID = 1;
            edit.UpdateDate   = DateTime.Now;
            edit.Insert();

            var delete = new Button();

            delete.Code         = "delete";
            delete.Name         = "删除";
            delete.Icon         = "fa-trash-o";
            delete.Location     = 2;
            delete.JsEvent      = "viewModel.onDataDeleting(id);";
            delete.AllowUpdate  = true;
            delete.AllowDelete  = true;
            delete.Remark       = "删除";
            delete.Sort         = 9996;
            delete.CreateUserID = 1;
            delete.CreateDate   = DateTime.Now;
            delete.UpdateUserID = 1;
            delete.UpdateDate   = DateTime.Now;
            delete.Insert();

            var detail = new Button();

            detail.Code         = "detail";
            detail.Name         = "查看";
            detail.Icon         = "fa-search-plus";
            detail.Location     = 2;
            detail.JsEvent      = "viewModel.onDataDetailing(id);";
            detail.AllowUpdate  = true;
            detail.AllowDelete  = true;
            detail.Remark       = "查看详情";
            detail.Sort         = 9998;
            detail.CreateUserID = 1;
            detail.CreateDate   = DateTime.Now;
            detail.UpdateUserID = 1;
            detail.UpdateDate   = DateTime.Now;
            detail.Insert();

            if (XTrace.Debug)
            {
                XTrace.WriteLine("完成初始化{0}[{1}]数据!", typeof(Button).Name, Meta.Table.DataTable.DisplayName);
            }
        }