Exemple #1
0
        public static void BackgroundAction(object target, Action backgroundAction, Action befoe, Action callback, EndMode endMode, TaskImplMode taskMode)
        {
            var context = new BackgroundActionContext(endMode, () => { backgroundAction(); return null; });
            var container = target == null ? backgroundAction.Target.As<IExtendedPresenter>() : target.As<IExtendedPresenter>();
            var task = container.GetMetadata<IBackgroundThreadTask>();
            if (task == null)
            {
                task = TaskImplFactory.CreateTask(taskMode);
                if (taskMode != TaskImplMode.UIThread)
                {
                    container.WasShutdown += (s, e) => task.Dispose();
                    container.AddMetadata(task);
                }
            }

            //Before
            if (!befoe.IsNull())
                befoe();

            //Action
            task.Enqueue(context);

            //After
            if (!callback.IsNull())
                Application.Current.Dispatcher.BeginInvoke(callback, DispatcherPriority.ContextIdle);
        }
Exemple #2
0
        public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action, bool hidden)
            : base(prototype, description, count, hidden)
        {
            if(action.IsNull())
                throw new ArgumentNullException("action");

            this.action = action;
        }
Exemple #3
0
		public static Action<Yuv> FromYuv(Action<Bgr> action)
		{
			Convert.YuvToBgrInitialize();
			return action.IsNull() ? (Action<Yuv>)null : color => action(new Bgr(
				(byte)(Function.Integer.Clamp((Convert.yuvToBgr[2][color.Y] + Convert.yuvToBgr[2][256 + color.U] + Convert.yuvToBgr[2][512 + color.V]) >> 8, 0, 255)),
				(byte)(Function.Integer.Clamp((Convert.yuvToBgr[1][color.Y] + Convert.yuvToBgr[1][256 + color.U] + Convert.yuvToBgr[1][512 + color.V]) >> 8, 0, 255)),
				(byte)(Function.Integer.Clamp((Convert.yuvToBgr[0][color.Y] + Convert.yuvToBgr[0][256 + color.U] + Convert.yuvToBgr[0][512 + color.V]) >> 8, 0, 255))
				));
		}
Exemple #4
0
        /// <summary>
        /// 更换IP 
        /// </summary>
        /// <param name="netType">0表示路由 1表示拨号连接</param>
        /// <param name="msg">通知输出消息</param>
        /// <param name="done">完成时执行</param>
        /// <param name="index">第几次执行</param>
        /// <returns></returns>
        public static string ChangeIP(int netType, Action<string> msg = null, Pub.Class.Action done = null, int index = 0)
        {
            string name = GetNetName(netType);
            setting = SendSettingHelper.SelectByID(1);

            if (setting.IsNull()) {
                if (!msg.IsNull()) msg("请修改发送设置!");
                if (!done.IsNull()) done();
                return "";
            } else {
                if (index == setting.MaxRetryCount) {
                    if (!done.IsNull()) done();
                    return "";
                }
                if (!msg.IsNull()) msg((index + 1).ToString());

                //清空多少分钟前的历史IP
                if (Data.Pool("ConnString").DBType == "SqlServer") {
                    "delete from IpHistory where CreateTime < DateAdd(MINUTE , -{0}, getdate())".FormatWith(setting.DeleteInterval).ToSQL().ToExec();
                } else if (Data.Pool("ConnString").DBType == "SQLite" || Data.Pool("ConnString").DBType == "MonoSQLite") {
                    "delete from IpHistory where datetime(CreateTime) < datetime('now','localtime', '-{0} minute')".FormatWith(setting.DeleteInterval).ToSQL().ToExec();
                }
                if (!msg.IsNull()) msg("正在重启" + name + "......");
                IController connect;
                switch (netType) {
                    case 1: connect = new ModelController(); break;
                    case 2: connect = new TianYiController(); break;
                    default: connect = new RouteController(); break;
                }
                string error = connect.Reset();
                if (!error.IsNullEmpty()) {
                    if (!msg.IsNull()) msg("重启" + name + "失败:" + error);
                    return ChangeIP(netType, msg, done, index + 1);
                } else {
                    if (!msg.IsNull()) msg("已重启" + name + ",正在检测是否联网......");
                    bool isTrue = NetHelper.CheckNetwork(msg);
                    if (!isTrue) return ChangeIP(netType, msg, done, index + 1);

                    if (!msg.IsNull()) msg("已联接网络,正在获取IP......");
                    string ip = IPHelper.GetIpFast();

                    if (!msg.IsNull()) msg("获取到IP:" + ip);
                    if (IpHistoryHelper.IsExistByID(ip)) {
                        if (!msg.IsNull()) msg("检测到IP:" + ip + "最近已使用!");
                        return ChangeIP(netType, msg, done, index + 1);
                    } else {
                        IpHistoryHelper.Insert(new IpHistory() { IP = ip, CreateTime = DateTime.Now.ToDateTime().ToDateTime() });
                    };
                    return ip;
                }
            }
        }
Exemple #5
0
            // == EXPENSIVE == //
            // Only use to test while loop logic so Unity doesn't brick on you //
            // =============== //
            #region SafeWhile
            public static void SafeWhile(System.Func <bool> predicate, System.Action action, int maxIterations = 1000, bool logWarning = true, UnityEngine.Object logContext = null)
            {
                if (predicate.IsNull())
                {
                    Debug.LogWarning($"SafeWhile loop exited due to a null predicate", logContext); return;
                }
                if (action.IsNull())
                {
                    Debug.LogWarning($"SafeWhile loop exited due to a null action", logContext); return;
                }

                SafeWhile(() =>
                {
                    bool _valid = predicate.Invoke();

                    if (_valid)
                    {
                        action?.Invoke();
                    }

                    return(_valid);
                }, maxIterations, logWarning, logContext);
            }
		public static void CopyToStreamAsync(this Stream source, Stream destination,
			Action<Stream, Stream, Exception> completed, Action<uint> progress,
			uint bufferSize, uint? maximumDownloadSize, TimeSpan? timeout)
		{
			byte[] buffer = new byte[bufferSize];

			Action<Exception> done = exception =>
				{
					if (completed != null)
					{
						completed(source, destination, exception);
					}
				};

			int maxDownloadSize = maximumDownloadSize.HasValue
				? (int)maximumDownloadSize.Value
				: int.MaxValue;
			int bytesDownloaded = 0;
            IAsyncResult asyncResult = source.BeginRead(buffer, 0, new[] {maxDownloadSize, buffer.Length}.Min(), null, null);
			Action<IAsyncResult, bool> endRead = null;
			endRead = (innerAsyncResult, innerIsTimedOut) =>
				{
					try
					{
						int bytesRead = source.EndRead(innerAsyncResult);
						if(innerIsTimedOut)
						{
							done(new TimeoutException());
						}

						int bytesToWrite = new[] { maxDownloadSize - bytesDownloaded, buffer.Length, bytesRead }.Min();
						destination.Write(buffer, 0, bytesToWrite);
						bytesDownloaded += bytesToWrite;

						if (!progress.IsNull() && bytesToWrite > 0)
						{
							progress((uint)bytesDownloaded);
						}

						if (bytesToWrite == bytesRead && bytesToWrite > 0)
						{
							asyncResult = source.BeginRead(buffer, 0, new[] { maxDownloadSize, buffer.Length }.Min(), null, null);
							// ReSharper disable PossibleNullReferenceException
							// ReSharper disable AccessToModifiedClosure
							asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout);
							// ReSharper restore AccessToModifiedClosure
							// ReSharper restore PossibleNullReferenceException
						}
						else
						{
							done(null);
						}
					}
					catch (Exception exc)
					{
						done(exc);
					}
				};

			asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout);
        }
            private static JwtBasedSecurityMessageHandler CreateSubjectUnderTest(
                bool forceAuthentication,
                HttpResponseMessage response,
                JwtSecurityTokenHandler tokenHandler,
                JwtValidationOptions options = null,
                Action<HttpRequestMessage, IPrincipal> assignPrincipalAction = null)
            {
                IPrincipal principal;

                if (assignPrincipalAction.IsNull())
                    assignPrincipalAction = (r, p) => principal = p;

                var sut = new JwtBasedSecurityMessageHandler(
                    options ?? new JwtValidationOptions(), forceAuthentication);

                sut.InnerHandler = new TestHandler(response);
                sut.SetSecurityTokenHandlerFactory(() => tokenHandler);
                sut.SetAssignPrincipalFactory(assignPrincipalAction);

                return sut;
            }
 public static Task RunAsync(this Action action, Action continueWith = null)
 {
     if (continueWith.IsNull()) continueWith = () => { };
     return Executor.Invoke(action, continueWith);
 }
Exemple #9
0
        private void sendAsync(Opcode opcode, Stream stream, Action completed)
        {
            Action<Opcode, Stream> action = send;

            AsyncCallback callback = (ar) =>
            {
                try {
                    action.EndInvoke(ar);
                    if (!completed.IsNull())
                        completed();
                }
                catch (Exception ex) {
                    onError(ex.Message);
                }
                finally {
                    stream.Close();
                }
            };

            action.BeginInvoke(opcode, stream, callback, null);
        }
            private static AclBasedSecurityMessageHandler CreateSubjectUnderTest(
                HttpResponseMessage response,
                ISubscriberRepository subscriberRepository,
                bool forceAuthentication = false,
                Action<HttpRequestMessage, IPrincipal> assignPrincipalFactory = null)
            {
                IPrincipal principal;
                if (assignPrincipalFactory.IsNull())
                    assignPrincipalFactory = (r, p) => principal = p;

                var sut = new AclBasedSecurityMessageHandler(forceAuthentication);

                sut.InnerHandler = new TestHandler(response);
                sut.SetSubscriberRepositoryFactory(
                    (config, request) => subscriberRepository ?? Mock.Of<ISubscriberRepository>());
                sut.SetAssignPrincipalFactory(assignPrincipalFactory);

                return sut;
            }
Exemple #11
0
 /// <summary>
 /// 检查网络是否可用
 /// </summary>
 public static bool CheckNetwork(Action<string> msg = null, int index = 0)
 {
     if (index == setting.MaxRetryCount) {
         if (!msg.IsNull()) msg("无法连接网络!");
         return false;
     }
     Thread.Sleep(1000);
     try {
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
         request.Timeout = 3000;
         request.GetResponse().Close();
         if (!msg.IsNull()) msg("已联网!");
         return true;
     } catch {
         if (!msg.IsNull()) msg((index + 1).ToString() + "次未联网,继续尝试检测是否联网.....");
         return CheckNetwork(msg, index + 1);
     }
 }
Exemple #12
0
		public static Action<Bgr> FromBgr(Action<Yuv> action)
		{
			Convert.BgrToYuvInititalize();
			return action.IsNull() ? (Action<Bgr>)null : color => action(new Yuv(
				(byte)Function.Integer.Clamp(((Convert.bgrToYuv[0][color.Red] + Convert.bgrToYuv[0][256 + color.Green] + Convert.bgrToYuv[0][512 + color.Blue]) >> 8), 0, 255),
				(byte)Function.Integer.Clamp(((Convert.bgrToYuv[1][color.Red] + Convert.bgrToYuv[1][256 + color.Green] + Convert.bgrToYuv[1][512 + color.Blue]) >> 8) + 128, 0, 255),
				(byte)Function.Integer.Clamp(((Convert.bgrToYuv[2][color.Red] + Convert.bgrToYuv[2][256 + color.Green] + Convert.bgrToYuv[2][512 + color.Blue]) >> 8) + 128, 0, 255)
				));
		}
Exemple #13
0
		public static Action<Monochrome> FromY(Action<Bgr> action)
		{
			Convert.YuvToBgrInitialize();
			return action.IsNull() ? (Action<Monochrome>)null : value => action(new Bgr(value, value, value));
		}
Exemple #14
0
		public static Action<Yuv> FromYuv(Action<Monochrome> action)
		{
			return action.IsNull() ? (Action<Yuv>)null : color => action(color.Y);
		}
Exemple #15
0
		public static Action<Bgr> FromBgr(Action<Monochrome> action)
		{
			Convert.BgrToYuvInititalize();
			return action.IsNull() ? (Action<Bgr>)null : color => action((Monochrome)(byte)Function.Integer.Clamp(((Convert.bgrToYuv[0][color.Red] + Convert.bgrToYuv[0][256 + color.Green] + Convert.bgrToYuv[0][512 + color.Blue]) >> 8), 0, 255));
		}
Exemple #16
0
		public static Action<Monochrome> FromY(Action<Yuv> action)
		{
			return action.IsNull() ? (Action<Monochrome>)null : (Monochrome value) => action(new Yuv(value, 128, 128));
		}