Esempio n. 1
0
        private void NewTask(Int64 time)
        {
            try
            {
                var token = new CancellationTokenSource();
                var obj   = new New()
                {
                    time = time
                };

                Task.Factory.StartNew(m =>
                {
                    SpinWait.SpinUntil(() => false, Convert.ToInt32(time));
                }, obj, token.Token)
                .ContinueWith((m, n) =>
                {
                }, obj, token.Token);
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
        }
Esempio n. 2
0
        static Builder()
        {
            var oc = ObjectContainer.Current;

            foreach (var item in typeof(Builder).GetAllSubclasses(true))
            {
                try
                {
                    //var obj = item.CreateInstance() as Builder;
                    //oc.Register<Builder>(obj, obj.Name);

                    var name = item.GetDisplayName() ?? item.Name;
                    oc.Register(typeof(Builder), item, null, name);
                }
                catch (Exception ex)
                {
                    if (XTrace.Debug)
                    {
                        XTrace.WriteException(ex);
                    }
                }
            }
        }
Esempio n. 3
0
File: Program.cs Progetto: xchit/X
        private static void Main(String[] args)
        {
            //Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;

            //XTrace.Log = new NetworkLog();
            XTrace.UseConsole();
#if DEBUG
            XTrace.Debug = true;
#endif
            while (true)
            {
                var sw = Stopwatch.StartNew();
#if !DEBUG
                try
                {
#endif
                Test3();
#if !DEBUG
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex?.GetTrue());
            }
#endif

                sw.Stop();
                Console.WriteLine("OK! 耗时 {0}", sw.Elapsed);
                //Thread.Sleep(5000);
                GC.Collect();
                GC.WaitForPendingFinalizers();
                var key = Console.ReadKey(true);
                if (key.Key != ConsoleKey.C)
                {
                    break;
                }
            }
        }
 /// <summary>初始化生活技能</summary>
 /// <param name="rid">武将表id</param>
 public static tg_role_life_skill InitSkill(Int64 rid)
 {
     try
     {
         if (rid <= 0)
         {
             return(null);
         }
         var skill = new tg_role_life_skill
         {
             rid            = rid,
             sub_archer     = CommonHelper.EnumLifeType(LifeSkillType.ARCHER),
             sub_artillery  = CommonHelper.EnumLifeType(LifeSkillType.ARTILLERY),
             sub_ashigaru   = CommonHelper.EnumLifeType(LifeSkillType.ASHIGARU),
             sub_build      = CommonHelper.EnumLifeType(LifeSkillType.BUILD),
             sub_calculate  = CommonHelper.EnumLifeType(LifeSkillType.CALCULATE),
             sub_craft      = CommonHelper.EnumLifeType(LifeSkillType.CRAFT),
             sub_eloquence  = CommonHelper.EnumLifeType(LifeSkillType.ELOQUENCE),
             sub_equestrian = CommonHelper.EnumLifeType(LifeSkillType.EQUESTRIAN),
             sub_etiquette  = CommonHelper.EnumLifeType(LifeSkillType.ETIQUETTE),
             sub_martial    = CommonHelper.EnumLifeType(LifeSkillType.MARTIAL),
             sub_medical    = CommonHelper.EnumLifeType(LifeSkillType.MEDICAL),
             sub_mine       = CommonHelper.EnumLifeType(LifeSkillType.MINE),
             sub_ninjitsu   = CommonHelper.EnumLifeType(LifeSkillType.NINJITSU),
             sub_reclaimed  = CommonHelper.EnumLifeType(LifeSkillType.RECLAIMED),
             sub_tactical   = CommonHelper.EnumLifeType(LifeSkillType.TACTICAL),
             sub_tea        = CommonHelper.EnumLifeType(LifeSkillType.TEA)
         };
         skill.Save();
         return(skill);
     }
     catch (Exception ex)
     {
         XTrace.WriteException(ex);
         return(null);
     }
 }
Esempio n. 5
0
        /// <summary>
        /// 启动Xml序列化到磁盘的进程
        /// </summary>
        private static void StartXmlWriterThread()
        {
            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    Thread.Sleep(3000);

                    if (s_needWriteToDisk) // 如果需要序列化
                    {
                        try
                        {
                            if (File.Exists(s_xmlFilePath))
                            {
                                File.Delete(s_xmlFilePath);
                            }

                            NewLife.Xml.XmlWriterX xml = new NewLife.Xml.XmlWriterX();
                            using (XmlWriter writer = XmlWriter.Create(s_xmlFilePath))
                            {
                                xml.Writer = writer;
                                xml.WriteObject(s_dictAssemblyType, typeof(Dictionary <String, AssemblyType>), null);
                            }
                            s_needWriteToDisk = false;

                            XTrace.WriteLine("已将代理程序集和端口类列表序列化到磁盘上AssemblyType.xml。");
                        }
                        catch (Exception ex)
                        {
                            XTrace.WriteException(ex);
                        }
                    }
                }
            });

            thread.Start();
        }
Esempio n. 6
0
            /// <summary>处理每一个定时器</summary>
            /// <param name="timer"></param>
            static void ProcessItem(TimerX timer)
            {
                try
                {
                    timer.Calling = true;

                    Action <Object> callback = timer.Callback;
                    callback(timer.State ?? timer);
                }
                catch (ThreadAbortException) { throw; }
                catch (ThreadInterruptedException) { throw; }
                // 如果用户代码没有拦截错误,则这里拦截,避免出错了都不知道怎么回事
                catch (Exception ex) { XTrace.WriteException(ex); }
                finally
                {
                    // 再次读取周期,因为任何函数可能会修改
                    var p = timer.Period;

                    timer.Timers++;
                    timer.NextTime = DateTime.Now.AddMilliseconds(p);
                    timer.Calling  = false;

                    // 清理一次性定时器
                    if (p <= 0)
                    {
                        lock (timers)
                        {
                            timers.Remove(timer);
                            timer.Dispose();
                        }
                    }
                    if (p < period)
                    {
                        period = p;
                    }
                }
            }
Esempio n. 7
0
        /// <summary>
        /// 订阅
        /// </summary>
        /// <param name="subscribeAppName">消费者名称</param>
        public void Subscribe(string subscribeAppName)
        {
            SubscribeAppName = subscribeAppName;
            _Cts             = new CancellationTokenSource();

            if (_Redis == null || _Queue == null)
            {
                OnDisconnected("订阅时列队对像为Null。");
            }

            //尝试创建消费组
            try
            {
                _Queue.Group = subscribeAppName;
                _Queue.GroupCreate(subscribeAppName);
            }
            catch (Exception err)
            {
                //遇到其它非消费组名已经存在的错误消息时,停止消费并提示消息
                if (err.Message.IndexOf(ConsumeGroupExistErrMsgKeyWord) < 0)
                {
                    if (XTrace.Debug)
                    {
                        XTrace.WriteException(err);
                    }
                    OnStopSubscribe(err.Message);
                    return;
                }
            }

#if NET40
            var thread = new Thread(s => getSubscribe(subscribeAppName));
            thread.Start();
#else
            Task.Run(() => getSubscribe(subscribeAppName), _Cts.Token);
#endif
        }
Esempio n. 8
0
        public ASObject CommandStart(TGGSession session, ASObject data)
        {
            try
            {
#if DEBUG
                XTrace.WriteLine("{0}:{1}", "SINGLE_FIGHT_NPC", "一将讨挑战");
#endif
                var npcid    = Convert.ToInt32(data.FirstOrDefault(m => m.Key == "id").Value.ToString());
                var mainrole = session.Player.Role.Kind;

                var basenpc = Variable.BASE_NPCSINGLE.FirstOrDefault(m => m.id == npcid);
                if (basenpc == null)
                {
                    return(Result((int)ResultType.BASE_TABLE_ERROR)); //验证基表信息
                }
                var cost = RuleConvert.GetCostPower();                //固定消耗体力

                if (!CheckPower(mainrole, cost))
                {
                    return(Result((int)ResultType.BASE_ROLE_POWER_ERROR));
                }
                var fight = NpcChallenge(session.Player.User.id, npcid, FightType.SINGLE_FIGHT);      //获得战斗结果Vo

                if (fight == null)
                {
                    return(Result((int)ResultType.FIGHT_ERROR));                      //验证战斗是否出错
                }
                //判断挑战结果信息
                return(ChallengeResult(session, basenpc.prop, basenpc.count, fight, cost));
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
                return(new ASObject());
            }
        }
Esempio n. 9
0
        static void Main(String[] args)
        {
            XTrace.UseConsole();

            var set = XCode.Setting.Current;

            if (set.IsNew)
            {
                //set.SQLiteDbPath = "..\\Data";
                set.SaveAsync();
            }

            try
            {
                Test2();
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }

            Console.WriteLine("OK!");
            Console.ReadKey();
        }
Esempio n. 10
0
        /// <summary>武将宅购买挑战次数</summary>
        public ASObject CommandStart(TGGSession session, ASObject data)
        {
            try
            {
#if DEBUG
                XTrace.WriteLine("{0}:{1}", "TRAIN_HOME_FIGHT_BUY", "武将宅购买挑战次数");
#endif
                var ext = session.Player.UserExtend;

                var f    = Variable.BASE_RULE.FirstOrDefault(m => m.id == "17020");
                var b    = Variable.BASE_RULE.FirstOrDefault(m => m.id == "17021");
                var cost = Variable.BASE_RULE.FirstOrDefault(m => m.id == "17023");
                if (f == null || b == null || cost == null)
                {
                    return(Error((int)ResultType.BASE_TABLE_ERROR));
                }

                var fcount = Convert.ToInt32(f.value);
                if (ext.fight_count < fcount)
                {
                    return(Error((int)ResultType.TRAIN_HOME_FIGHT_ERROR));                             //挑战次数未用完
                }
                var bcount = Convert.ToInt32(b.value);
                if (ext.fight_buy >= bcount)
                {
                    return(Error((int)ResultType.TRAIN_HOME_BUY_LACK));
                }

                return(BuyFight(session.Player.User.id, cost.value, f.value));
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
                return(new ASObject());
            }
        }
Esempio n. 11
0
        private static void Main(String[] args)
        {
            MachineInfo.RegisterAsync();
            //XTrace.Log = new NetworkLog();
            XTrace.UseConsole();
#if DEBUG
            XTrace.Debug = true;
#endif
            while (true)
            {
                var sw = Stopwatch.StartNew();
#if !DEBUG
                try
                {
#endif
                Test1();
#if !DEBUG
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex?.GetTrue());
            }
#endif

                sw.Stop();
                Console.WriteLine("OK! 耗时 {0}", sw.Elapsed);
                //Thread.Sleep(5000);
                GC.Collect();
                GC.WaitForPendingFinalizers();
                var key = Console.ReadKey(true);
                if (key.Key != ConsoleKey.C)
                {
                    break;
                }
            }
        }
Esempio n. 12
0
        void OnPreLoad(object sender, EventArgs e)
        {
            try
            {
                if (!CheckLogin())
                {
                    Response.StatusCode        = 403;
                    Response.StatusDescription = "没有登录!";
                    Response.Write("没有登录!");
                    Response.End();
                }
                else if (!CheckPermission())
                {
                    Response.StatusCode = 403;
                    //Response.SubStatusCode = 15;
                    var msg = String.Format("[{0}]没有权限访问[{1}]!页面:{2}", CurrentAdmin, PermissionName, CurrentMenu);
                    Response.StatusDescription = msg;
                    Response.Write(msg);
                    Response.End();
                }
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }

            //if (!Page.IsPostBack) CheckAddAndDeletePermission();
            // 感谢 @波波(136879642),因为页面上可能关闭ViewState,所以这里每次都要检查

            //chenqi 当页面不再验证权限是,此方法不被执行
            if (ValidatePermission)
            {
                CheckAddAndDeletePermission();
            }
        }
Esempio n. 13
0
        public virtual ActionResult UserInfo(String access_token)
        {
            if (access_token.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(access_token));
            }

            var         sso  = OAuthServer.Instance;
            IManageUser user = null;

            var msg = "";

            try
            {
                user = Provider?.GetUser(sso, access_token);
                if (user == null)
                {
                    throw new Exception("用户不存在");
                }

                var rs = Provider.GetUserInfo(sso, access_token, user);
                return(Json(rs, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                msg = ex.GetTrue().Message;

                XTrace.WriteLine($"UserInfo {access_token}");
                XTrace.WriteException(ex);
                return(Json(new { error = ex.GetTrue().Message }, JsonRequestBehavior.AllowGet));
            }
            finally
            {
                sso.WriteLog("UserInfo {0} access_token={1} msg={2}", user, access_token, msg);
            }
        }
Esempio n. 14
0
        private static ITransport CreateRS232Transport(string host, int e, int timeout)
        {
            var key = "RS232://{0}:{1}".F(host, e);
            var sp  = new SerialTransport
            {
                PortName = host,
                BaudRate = e
            };

            try
            {
                sp.Open();
                sp.Serial.ReadTimeout = timeout;
                sp.Disconnected      += (s, de) =>
                {
                    lock (TransportsCache)
                    {
                        if (TransportsCache.ContainsKey(key))
                        {
                            lock (TransportsCache)
                            {
                                if (TransportsCache.ContainsKey(key))
                                {
                                    TransportsCache.Remove(key);
                                }
                            }
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
            return(sp);
        }
Esempio n. 15
0
        static void Main()
        {
            XTrace.UseWinForm();

            StringHelper.EnableSpeechTip = XConfig.Current.SpeechTip;

            // 参数启动
            var args = Environment.GetCommandLineArgs();

            if (args != null && args.Length > 1)
            {
                try
                {
                    StartWithParameter(args);
                }
                catch (Exception ex)
                {
                    XTrace.WriteException(ex);
                }
                return;
            }

            if (!Runtime.Mono)
            {
                new TimerX(s => Runtime.ReleaseMemory(), null, 5000, 10000);
            }

            if (XConfig.Current.IsNew)
            {
                "学无先后达者为师,欢迎使用新生命码神工具!".SpeechTip();
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FrmMDI());
        }
        /// <summary>
        /// InvokeAsync
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception e)
            {
                //记录系统的异常信息
                XTrace.WriteException(e);

                // 如果已经开始响应到客户端,直接抛出异常,否则下面写入响应也会抛异常
                if (context.Response.HasStarted)
                {
                    throw;
                }

                var data = new ApiResult <String>();

                if (e is ApiException apiexc)
                {
                    data.Status = apiexc.Status;
                    data.Msg    = apiexc.Message;
                    context.Response.StatusCode = 200;
                }
                else
                {
                    data.Status = 500;
                    data.Msg    = e.Message;
                    context.Response.StatusCode = (Int32)HttpStatusCode.InternalServerError;
                }

                context.Response.Headers.Add(HeaderNames.ContentType, "application/json;charset=utf8");
                await context.Response.WriteAsync(JsonConvert.SerializeObject(data), Encoding.UTF8);
            }
        }
Esempio n. 17
0
        /// <summary>字符串转换为计算公式,并得出计算结果</summary>
        /// <param name="expression">字符串计算公式</param>
        public static object EvalExpress(string expression)
        {
            expression = UConvert.ToDbc(expression);
            try
            {
#if DEBUG
                XTrace.WriteLine(expression);
#endif
                return(NEvalExecute(expression));
            }
            catch
            {
                try
                {
                    return(expression.Contains("Math") ? XcodeScriptExecute(expression)
                     : new DataTable().Compute(expression, ""));
                }
                catch (Exception ex)
                {
                    XTrace.WriteException(ex);
                    return(XcodeScriptExecute(expression));
                }
            }
        }
Esempio n. 18
0
        private TResult ExecuteByCache <T1, T2, T3, TResult>(T1 k1, T2 k2, T3 k3, Func <T1, T2, T3, TResult> callback)
        {
            if (Db.Readonly)
            {
                throw new InvalidOperationException($"数据连接[{ConnName}]只读,禁止执行{k1}");
            }

            CheckDatabase();

            var rs = Invoke(k1, k2, k3, callback, "Execute");

            var st = GetCache();

            if (st != null)
            {
                st?.Clear();

                // 删除文件缓存
                var dataDir = NewLife.Setting.Current.DataPath.CombinePath(ConnName);
                if (Directory.Exists(dataDir))
                {
                    try
                    {
                        Directory.Delete(dataDir, true);
                    }
                    catch (Exception ex)
                    {
                        XTrace.WriteException(ex);
                    }
                }
            }

            Interlocked.Increment(ref _ExecuteTimes);

            return(rs);
        }
Esempio n. 19
0
        /// <summary>游艺园忍术游戏进入</summary>
        public ASObject CommandStart(TGGSession session, ASObject data)
        {
            try
            {
#if DEBUG
                XTrace.WriteLine("{0}:{1}", "GAMES_NINJUTSU_ENTER", "游艺园忍术游戏进入");
#endif
                var player = session.Player;
                var game   = player.Game;

                if (game.GameType == (int)GameType.ACTIONGAME)     //闯关模式
                {
                    //验证剩余次数
                    var b = Common.GetInstance().CheckCount((int)GameEnterType.猜宝游戏, player.UserExtend);
                    if (!b)
                    {
                        return(Result((int)ResultType.GAME_COUNT_FAIL));
                    }
                }
                if (game.Ninjutsu.ninjutsu_pass == 0)
                {
                    game.Ninjutsu.ninjutsu_pass = 1;
                }

                var position = RNG.Next(0, 3);
                session.Player.Position.position = position;    //获得色子位置

                return(new ASObject(Common.GetInstance().NinjaEnterData((int)ResultType.SUCCESS, position)));
            }

            catch (Exception ex)
            {
                XTrace.WriteException(ex);
                return(new ASObject());
            }
        }
Esempio n. 20
0
        static void Main(String[] args)
        {
            XTrace.UseConsole();

            try
            {
                Console.Write("模式(1生产者,2消费者):");
                if (Console.ReadLine() == "1")
                {
                    Test1();
                }
                else
                {
                    Test2();
                }
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }

            Console.WriteLine("OK!");
            Console.ReadKey();
        }
Esempio n. 21
0
        /// <summary>执行后,包装结果和异常</summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Result != null)
            {
                if (context.Result is ObjectResult obj)
                {
                    context.Result = new JsonResult(new { code = 0, data = obj.Value });
                }
                else if (context.Result is EmptyResult)
                {
                    context.Result = new JsonResult(new { code = 0, data = new { } });
                }
            }
            else if (context.Exception != null && !context.ExceptionHandled)
            {
                var ex = context.Exception.GetTrue();
                if (ex is NewLife.Remoting.ApiException aex)
                {
                    context.Result = new JsonResult(new { code = aex.Code, data = aex.Message });
                }
                else
                {
                    context.Result = new JsonResult(new { code = 500, data = ex.Message });
                }

                context.ExceptionHandled = true;

                // 输出异常日志
                if (XTrace.Debug)
                {
                    XTrace.WriteException(ex);
                }
            }

            base.OnActionExecuted(context);
        }
Esempio n. 22
0
        private static ITransport CreateNetTransport(TransportTypeEnum type, string host, int e, int timeout)
        {
            IPAddress ip;

            lock (_hostCache)
            {
                if (_hostCache.ContainsKey(host))
                {
                    ip = _hostCache[host];
                }
                else
                {
                    try
                    {
                        ip = NetHelper.ParseAddress(host);
                        _hostCache.TryAdd(host, ip);
                    }
                    catch (Exception ex)
                    {
                        XTrace.WriteException(ex);
                        return(null);
                    }
                }
            }

            var session = new NetUri(string.Format("{0}://{1}:{2}", type.ToString(), ip, e)).CreateRemote();

            session.Log    = XTrace.Log;
            session.Error += Session_Error;
            //if (session.GetType() == typeof(TcpSession))
            //{
            //    var se = session as SessionBase;
            //    se.Timeout = timeout;
            //}
            return(session as ITransport);
        }
Esempio n. 23
0
        /// <summary>遍历获取所有类型映射</summary>
        /// <param name="asm"></param>
        /// <param name="baseVirtualPath"></param>
        /// <returns></returns>
        public static IDictionary <String, Type> GetTypeMappings(Assembly asm, String baseVirtualPath)
        {
            // 部分程序集反射时容易抛出异常,这里吃掉异常,避免影响魔方启动
            Type[] types = null;
            try
            {
                types = asm.GetTypes();
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
            if (types == null || types.Length == 0)
            {
                return(new Dictionary <String, Type>());
            }

            return((
                       from type in asm.GetTypes()
                       where type.As <WebPageRenderingBase>()
                       let pageVirtualPath = type.GetCustomAttributes(false).OfType <PageVirtualPathAttribute>().FirstOrDefault()
                                             where pageVirtualPath != null
                                             select new KeyValuePair <String, Type>(CombineVirtualPaths(baseVirtualPath, pageVirtualPath.VirtualPath), type)).ToDictionary(t => t.Key, t => t.Value, StringComparer.OrdinalIgnoreCase));
        }
Esempio n. 24
0
        /// <summary> 玩家下线操作 </summary>
        private void PlayerOffline(view_scene_user scene)
        {
            try
            {
                var             userid   = scene.user_id;
                var             scenekey = (int)ModuleNumber.SCENE + "_" + userid;
                view_scene_user scenevalue;
                Variable.SCENCE.TryRemove(scenekey, out scenevalue); //从内存中移除

#if DEBUG
                XTrace.WriteLine("玩家{0}下线时的场景:{1}  坐标:{1},{2}", Player.User.player_name, scene.scene_id, scene.X, scene.Y);
#endif
                var prison = tg_prison.GetPrisonByUserId(userid);
                if (prison != null)
                {
                    PrisonOut(userid);
                    tg_scene.GetSceneUpdate(scene); //保存到数据库
                    return;                         //监狱内下线
                }
                if (Variable.Activity.ScenePlayer.Keys.Contains(string.Format("{0}_{1}", (int)ModuleNumber.BUILDING, userid)) ||
                    Variable.Activity.ScenePlayer.Keys.Contains(string.Format("{0}_{1}", (int)ModuleNumber.SIEGE, userid)))
                {
                    ActivityOut(userid);
                    scene.model_number = (int)ModuleNumber.SCENE;
                    tg_scene.GetSceneUpdate(scene); //保存到数据库
                    return;
                }
                scene.model_number = (int)ModuleNumber.SCENE;
                tg_scene.GetSceneUpdate(scene); //保存到数据库
                NormalOut(scene);               //正常场景下线
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
        }
Esempio n. 25
0
        static void TestTask(Int32 tid)
        {
            try
            {
                XTrace.WriteLine("TestTask {0} Start", tid);
                using (var tran = Role.Meta.CreateTrans())
                {
                    var role = new Role();
                    role.Name = "R" + DateTime.Now.Millisecond;
                    role.Save();
                    XTrace.WriteLine("role.ID={0}", role.ID);

                    Thread.Sleep(3000);

                    role      = new Role();
                    role.Name = "R" + DateTime.Now.Millisecond;
                    role.Save();
                    XTrace.WriteLine("role.ID={0}", role.ID);

                    Thread.Sleep(3000);

                    if (tid == 2)
                    {
                        tran.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
            finally
            {
                XTrace.WriteLine("TestTask {0} End", tid);
            }
        }
Esempio n. 26
0
        /// <summary>在程序集中查找类型</summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        Type GetTypeInternal(String typeName)
        {
            var type = Asm.GetType(typeName);

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

            // 如果没有包含圆点,说明其不是FullName
            if (!typeName.Contains("."))
            {
                try
                {
                    var types = Asm.GetTypes();
                    if (types != null && types.Length > 0)
                    {
                        foreach (var item in types)
                        {
                            if (item.Name == typeName)
                            {
                                return(item);
                            }
                        }
                    }
                }
                catch (ReflectionTypeLoadException ex)
                {
                    if (XTrace.Debug)
                    {
                        //XTrace.WriteException(ex);
                        XTrace.WriteLine("加载[{0}]{1}的类型时发生个{2}错误!", this, Location, ex.LoaderExceptions.Length);

                        foreach (var item in ex.LoaderExceptions)
                        {
                            XTrace.WriteException(item);
                        }
                    }

                    return(null);
                }
                catch (Exception ex)
                {
                    if (XTrace.Debug)
                    {
                        XTrace.WriteException(ex);
                    }

                    return(null);
                }

                // 遍历所有类型,包括内嵌类型
                foreach (var item in Types)
                {
                    if (item.Name == typeName)
                    {
                        return(item);
                    }
                }
            }

            return(null);
        }
Esempio n. 27
0
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            // if (this.lstFarm.SelectedItems.Count == 0) return;

            if (this.txtName.Text.Trim().Equals(""))
            {
                MessageBox.Show("名称不能为空,请输入");
                this.txtName.Focus();
                return;
            }

            //if (this.txtCode1.Text.Trim().Equals(""))
            //{
            //    MessageBox.Show("编码1不能为空,请输入");
            //    this.txtName.Focus();
            //    return;
            //}
            //if (this.txtCode2.Text.Trim().Equals(""))
            //{
            //    MessageBox.Show("编码2不能为空,请输入");
            //    this.txtName.Focus();
            //    return;
            //}
            //if (this.txtCode3.Text.Trim().Equals(""))
            //{
            //    MessageBox.Show("编码3不能为空,请输入");
            //    this.txtName.Focus();
            //    return;
            //}
            //if (this.txtCompanySerialNum.Text.Trim().Equals(""))
            //{
            //    MessageBox.Show("公司不能为空,请输入");
            //    this.txtName.Focus();
            //    return;
            //}
            //List<Facility> facilityList = (from item in this.lstFacility.Items.Cast<ListViewItem>() where item.Checked select item.Tag as Facility).ToList();//设施列表

            if (this.farmId != 0)
            {
                try
                {
                    #region 更新基地

                    var farm = Farm.FindByID(this.farmId);
                    if (farm == null)
                    {
                        farm       = new Farm();
                        farm.Code1 = this.txtCode1.Text;
                    }

                    farm.Code1            = this.txtCode1.Text.Trim();
                    farm.Code2            = this.txtCode2.Text.Trim();
                    farm.Code3            = this.txtCode3.Text.Trim();
                    farm.Name             = this.txtName.Text.Trim();
                    farm.CompanySerialnum = this.txtCompanySerialNum.Text.Trim();
                    farm.Address          = this.txtAddress.Text.Trim();
                    //PhotoUrl = this.pbPhotoUrl.Text,
                    farm.Lotitude      = this.txtLotitude.Text;
                    farm.Latitude      = this.txtLatitude.Text;
                    farm.Area          = Convert.ToInt32(this.txtArea.Text.Trim());
                    farm.ContactMan    = this.txtContactMan.Text.Trim();
                    farm.ContactPhone  = this.txtContactPhone.Text.Trim();
                    farm.ContactMobile = this.txtContactMobile.Text.Trim();
                    //Status = Convert.ToBoolean(this.cbStatus.SelectedValue),
                    farm.Status = this.rbtOnlineStatus.Checked;
                    //CreateTime = this.dtCreateTime.Value,
                    farm.UpdateTime = Convert.ToDateTime(DateTime.Now.ToString("G"));
                    farm.APIKey     = this.txtAPIKey.Text;
                    //Upload = Convert.ToBoolean(this.cbUpLoad.SelectedValue),
                    //Upload=this.rbtUpLoad.Checked,
                    //Version = Convert.ToInt32(this.txtVersion.Text),
                    ////Introduce = this.lstIntroduce.Text,
                    farm.Remark = this.txtPwd.Text;

                    farm.Save();
                    this.farmId = farm.ID;

                    #endregion 更新基地

                    //MessageBox.Show("更新成功");
                }
                catch (Exception ex)
                {
                    XTrace.WriteException(ex);
                    MessageBox.Show("更新失败");
                    return;
                }
            }
            else
            {
                try
                {
                    // 保存
                    var farm = new Farm();

                    farm.Code1            = this.txtCode1.Text.Trim();
                    farm.Code2            = this.txtCode2.Text.Trim();
                    farm.Code3            = this.txtCode3.Text.Trim();
                    farm.Name             = this.txtName.Text.Trim();
                    farm.CompanySerialnum = this.txtCompanySerialNum.Text.Trim();
                    farm.Address          = this.txtAddress.Text.Trim();
                    //PhotoUrl = this.pbPhotoUrl.Text,
                    farm.Lotitude      = this.txtLotitude.Text;
                    farm.Latitude      = this.txtLatitude.Text;
                    farm.Area          = Convert.ToInt32(this.txtArea.Text.Trim());
                    farm.ContactMan    = this.txtContactMan.Text.Trim();
                    farm.ContactPhone  = this.txtContactPhone.Text.Trim();
                    farm.ContactMobile = this.txtContactMobile.Text.Trim();
                    //Status = Convert.ToBoolean(this.cbStatus.SelectedValue),
                    farm.Status = this.rbtOnlineStatus.Checked;
                    //CreateTime = this.dtCreateTime.Value,
                    farm.UpdateTime = Convert.ToDateTime(DateTime.Now.ToString("G"));
                    farm.APIKey     = this.txtAPIKey.Text;
                    //Upload = Convert.ToBoolean(this.cbUpLoad.SelectedValue),
                    //Upload=this.rbtUpLoad.Checked,
                    //Version = Convert.ToInt32(this.txtVersion.Text),
                    ////Introduce = this.lstIntroduce.Text,
                    farm.Remark = this.txtPwd.Text;

                    farm.Save();
                    this.farmId = farm.ID;
                    //this.InitFacilityListView();
                    //MessageBox.Show("保存成功");
                }
                catch (Exception ex)
                {
                    XTrace.WriteException(ex);
                    MessageBox.Show("新增失败");
                    return;
                }
            }

            try
            {
                var facilityListChecked   = new List <Facility>();
                var facilityListUnchecked = new List <Facility>();
                foreach (ListViewItem item in this.lstFacility.Items)
                {
                    if (item.Checked == false)
                    {
                        var facility = item.Tag as Facility; //设施
                        facilityListUnchecked.Add(facility);
                    }
                    else
                    {
                        //facilityListChecked = (from i in this.lstFacility.Items.Cast<ListViewItem>() where i.Checked select i.Tag as Facility).ToList();//显示数据
                        foreach (ListViewItem lvi in lstFacility.Items)
                        {
                            if (lvi.Checked)
                            {
                                facilityListChecked.Add(lvi.Tag as Facility);
                            }
                        }
                    }
                }

                var farm = Farm.FindByID(farmId);

                //未选中的设施不能删除,只删除编码
                foreach (var item in facilityListUnchecked)
                {
                    if (item.FarmID == this.farmId)
                    {
                        item.Code1  = "";
                        item.FarmID = 0;
                        item.Update();
                        //删除映射关系
                        item.FacilitySensorDeviceUnits.Delete(true);
                        item.FacilityControlDeviceUnits.Delete(true);
                        item.FacilityCameras.Delete(true);
                    }
                }

                //更新基地设施
                foreach (var item in facilityListChecked)
                {
                    #region 更新设施

                    //Facility fac = new Facility();
                    //fac.ID = item.ID;
                    //fac.FarmID = this.farmId;
                    var fac = Facility.FindByID(item.ID);
                    fac.FarmID = farm.ID;
                    if (this.txtCode1.Text.IsNullOrWhiteSpace())
                    {
                        fac.Code1 = "";
                    }
                    else if (!this.txtCode1.Text.IsNullOrWhiteSpace() && !(fac.Code1 + "").StartsWith(farm.Code1))
                    {
                        fac.Code1 = fac.GetCode1();
                    }
                    fac.Update();

                    #endregion 更新设施

                    #region 设施下的采集设备的更新

                    IEnumerable <FacilitySensorDeviceUnit> facilitySensorDeviceUnits =
                        FacilitySensorDeviceUnit.FindAllByFacilityID(fac.ID).ToList().OrderBy(fas => fas.ID);
                    if (facilitySensorDeviceUnits.Count() > 0)
                    {
                        foreach (var fas in facilitySensorDeviceUnits)
                        {
                            if (fac.Code1.IsNullOrWhiteSpace())
                            {
                                fas.Code1 = "";
                            }
                            else if (!fac.Code1.IsNullOrWhiteSpace() && !(fas.Code1 + "").StartsWith(fac.Code1))
                            {
                                //XTrace.WriteLine("-->" + fas.Code1 + " -- " + fas.GetCode1());
                                fas.Code1 = fas.GetCode1();
                                //XTrace.WriteLine("<--" + fas.Code1);
                            }
                            fas.Save();
                        }
                    }

                    #endregion 设施下的采集设备的更新

                    #region 设施下的控制设备的更新

                    IEnumerable <FacilityControlDeviceUnit> facilityControlDeviceUnits =
                        FacilityControlDeviceUnit.FindAllByFacilityID(fac.ID).ToList().OrderBy(fas => fas.ID);
                    if (facilityControlDeviceUnits.Count() > 0)
                    {
                        foreach (var fas in facilityControlDeviceUnits)
                        {
                            if (fac.Code1.IsNullOrWhiteSpace())
                            {
                                fas.Code1 = "";
                            }
                            else if (!fac.Code1.IsNullOrWhiteSpace() && !(fas.Code1 + "").StartsWith(fac.Code1))
                            {
                                fas.Code1 = fas.GetCode1();
                            }
                            fas.Update();
                        }
                    }

                    #endregion 设施下的控制设备的更新

                    #region 设施下的摄像机设备的更新

                    IEnumerable <FacilityCamera> facilityCameras =
                        FacilityCamera.FindAllByFacilityID(fac.ID).ToList().OrderBy(fas => fas.ID);
                    if (facilityCameras.Count() > 0)
                    {
                        foreach (var fas in facilityCameras)
                        {
                            if (fac.Code1.IsNullOrWhiteSpace())
                            {
                                fas.Code1 = "";
                            }
                            else if (!fac.Code1.IsNullOrWhiteSpace() && !(fas.Code1 + "").StartsWith(fac.Code1))
                            {
                                fas.Code1 = fas.GetCode1();
                            }
                            fas.Update();
                        }
                    }

                    #endregion 设施下的摄像机设备的更新
                }

                this.InitFacilityListView();
                this.InitList();
                MessageBox.Show("操作成功");
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
                MessageBox.Show("更新设备编码失败");
                return;
            }
            this.farmId = 0;
        }
Esempio n. 28
0
        static void Test3()
        {
            //XTrace.WriteLine("IsConsole={0}", Runtime.IsConsole);
            //Console.WriteLine("IsConsole={0}", Runtime.IsConsole);
            //XTrace.WriteLine("MainWindowHandle={0}", Process.GetCurrentProcess().MainWindowHandle);

            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:335,tcp://127.0.0.1:1234")
                {
                    Log = XTrace.Log,
                    //EncoderLog = XTrace.Log,
                    StatPeriod = 10,

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

                TaskEx.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);
                });

                TaskEx.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);
                });

                TaskEx.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);
                });

                TaskEx.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();
            }
        }
Esempio n. 29
0
        /// <summary>处理脚本文件</summary>
        static void ProcessFile()
        {
            var cfg = Config;

            // 加上源文件路径
            Console.Title = Title + " " + cfg.File;

            ScriptEngine se = null;

            while (true)
            {
                try
                {
                    if (se == null)
                    {
                        var file = cfg.File;
                        if (!File.Exists(file))
                        {
                            throw new FileNotFoundException(String.Format("文件{0}不存在!", file), file);
                        }

                        //if (Config.Debug) Console.WriteLine("脚本:{0}", file);

                        // 增加源文件路径,便于调试纠错
                        if (!Path.IsPathRooted(file))
                        {
                            file = Path.Combine(Environment.CurrentDirectory, file);
                        }
                        file = file.GetFullPath();

                        se = Script.ProcessFile(file);
                        if (se == null)
                        {
                            return;
                        }
                    }
                    else
                    {
                        // 多次执行
                        Script.Run(se);
                    }
                }
                catch (Exception ex)
                {
                    // 获取内部异常
                    if (ex is TargetInvocationException)
                    {
                        ex = (ex as TargetInvocationException).InnerException;
                    }

                    XTrace.WriteException(ex);
                    //if (!Config.Debug) Console.WriteLine(ex.ToString());
                }
                finally
                {
                    // 处理文件已完成,自动更新任务下载完成后可马上执行更新
                    _CodeFile = false;
                }

                // 此时执行自动更新
                var up = _upgrade;
                if (up != null)
                {
                    _upgrade = null;
                    up.Update();
                }

                // 暂停,等待客户查看输出
                if (cfg.NoStop)
                {
                    return;
                }

                //Console.WriteLine("任意键退出……");
                var key = Console.ReadKey(true);
                // 如果按下m键,重新打开菜单
                if (key.KeyChar == 'm')
                {
                    //Main(new String[0]);
                    // 输出版权信息
                    ShowCopyright();

                    // 显示帮助菜单
                    ShowHelp();

                    ProcessUser();

                    // 处理用户输入本来就是一个循环,里面退出以后,这里也应该跟着退出
                    return;
                }

                // 再次执行
                if (key.KeyChar == 'c')
                {
                    continue;
                }

                // 是否卸载流程
                if (key.KeyChar == 'u')
                {
                    RegHelper.Uninstall(false);
                    return;
                }

                break;
            }
        }
Esempio n. 30
0
        /// <summary>根据名称获取类型</summary>
        /// <param name="typeName">类型名</param>
        /// <param name="isLoadAssembly">是否从未加载程序集中获取类型。使用仅反射的方法检查目标类型,如果存在,则进行常规加载</param>
        /// <returns></returns>
        internal static Type GetType(String typeName, Boolean isLoadAssembly)
        {
            var type = Type.GetType(typeName);

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

            // 尝试本程序集
            var asms = new[] {
                AssemblyX.Create(Assembly.GetExecutingAssembly()),
                AssemblyX.Create(Assembly.GetCallingAssembly()),
                AssemblyX.Create(Assembly.GetEntryAssembly())
            };
            var loads = new List <AssemblyX>();

            foreach (var asm in asms)
            {
                if (asm == null || loads.Contains(asm))
                {
                    continue;
                }
                loads.Add(asm);

                type = asm.GetType(typeName);
                if (type != null)
                {
                    return(type);
                }
            }

            // 尝试所有程序集
            foreach (var asm in AssemblyX.GetAssemblies())
            {
                if (loads.Contains(asm))
                {
                    continue;
                }
                loads.Add(asm);

                type = asm.GetType(typeName);
                if (type != null)
                {
                    return(type);
                }
            }

            // 尝试加载只读程序集
            if (!isLoadAssembly)
            {
                return(null);
            }

            foreach (var asm in ReflectionOnlyGetAssemblies())
            {
                type = asm.GetType(typeName);
                if (type != null)
                {
                    // 真实加载
                    var file = asm.Asm.Location;
                    try
                    {
                        type = null;
                        var asm2  = Assembly.LoadFile(file);
                        var type2 = AssemblyX.Create(asm2).GetType(typeName);
                        if (type2 == null)
                        {
                            continue;
                        }
                        type = type2;
                        if (XTrace.Debug)
                        {
                            var root = ".".GetFullPath();
                            if (file.StartsWithIgnoreCase(root))
                            {
                                file = file.Substring(root.Length).TrimStart("\\");
                            }
                            XTrace.WriteLine("TypeX.GetType(\"{0}\") => {1}", typeName, file);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (XTrace.Debug)
                        {
                            XTrace.WriteException(ex);
                        }
                    }

                    return(type);
                }
            }

            return(null);
        }