示例#1
0
        /// <summary>
        /// 读取统计数据库数据回写到参数回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void StatisticsDateBase_Select_CallBack(IAsyncResult ar)
        {
            string[] Retusl = new string[3] {
                "0", "0", "0"
            };
            try
            {
                //可能发生错误,未处理
                Retusl = StatisticsDateBaseSelect?.EndInvoke(ar);
                if (string.IsNullOrEmpty(Retusl[0]))
                {
                    //查询不到数据,创建数据
                    StatisticsDataBaseInsert?.BeginInvoke(DateTime.Now, true, StatisticsDataBase_Insert_CallBack, null);
                }
            }
            catch
            {
                ;
            }

            Working.IN      = int.Parse(Retusl[0]);
            Working.OUT     = int.Parse(Retusl[1]);
            Working.BALANCE = int.Parse(Retusl[2]);

            SetStatisticsLable_Action?.BeginInvoke(Working.IN.ToString(), Working.OUT.ToString(), Working.BALANCE.ToString(), null, null);

            SetMessage_Action?.Invoke("StatisticsDateBaseSelect[回调|查询|读取统计数据库数据回写到参数回调函数]");
        }
示例#2
0
        static void ScanDouble()
        {
            // Delegates anlegen
            var dg1 = new Func<long, long, IEnumerable<long>>(mko.Algo.NumberTheory.PrimeFactors.scan);
            var dg2 = new Func<long, long, IEnumerable<long>>(mko.Algo.NumberTheory.PrimeFactors.scan);
            var dg3 = new Func<long, long, IEnumerable<long>>(mko.Algo.NumberTheory.PrimeFactors.scan);
            var dg4 = new Func<long, long, IEnumerable<long>>(mko.Algo.NumberTheory.PrimeFactors.scan);


            // Methoden asynchron mittels Delegates starten
            var ares1=  dg1.BeginInvoke(1, 2500000, null, null);
            var ares2=  dg2.BeginInvoke(2500001, 5000000, null, null);
            var ares3 = dg3.BeginInvoke(5000001, 75000000, null, null);
            var ares4 = dg4.BeginInvoke(7500001, 10000000, null, null);

            while (!ares1.IsCompleted && !ares2.IsCompleted && !ares3.IsCompleted && !ares4.IsCompleted)
            {
                Debug.Write(".");
                System.Threading.Thread.Sleep(200);
            }

            //ares1.AsyncWaitHandle.WaitOne();

            var res1 = dg1.EndInvoke(ares1);
            var res2 = dg2.EndInvoke(ares2);

        }
示例#3
0
文件: Form1.cs 项目: n-n-n/CsCodes
 /// AsynchronouseProngraingModel
 void apm()
 {
     before_work();
     var method = new Func<double>(() => { busy_work(); return 0; });
     method.BeginInvoke(ar =>
     {
         var result = method.EndInvoke(ar);// get return value
         this.BeginInvoke((Action)(() => { after_work(); }));
     }, null);
 }
示例#4
0
 /// <summary>异步传参数
 /// </summary>
 /// <param name="age"></param>
 public static void ybpara(int age)
 {
     //异步执行
     Func<people, string> FuncAsy = new Func<people, string>((pp) =>
     {
         return pp.Name;
     }
     );
     FuncAsy.BeginInvoke(new people("小李" + age, age), resual =>
     {
         //异步执行,从回调函数中获取返回结果
         Console.WriteLine(">>>>:{0}", FuncAsy.EndInvoke(resual));
         Console.WriteLine(">>>>:{0} end", age);
     }, null);
 }
示例#5
0
 /// <summary>异步
 /// </summary>
 /// <param name="age"></param>
 public static void yb(int age)
 {
     //异步执行
     Func<string> FuncAsy = new Func<string>(() =>
     {
         people tPeo = new people("异步小李", age);
         return tPeo.ToString();
     }
     );
     FuncAsy.BeginInvoke(resual =>
     {
         //异步执行,从回调函数中获取返回结果
         Console.WriteLine(">>>>:{0}", FuncAsy.EndInvoke(resual));
         Console.WriteLine(">>>>:{0} end", age);
     }, null);
 }
示例#6
0
 public static void LoadAsync(string filename, Action<IStorableContent, Exception> loadingCompletedCallback) {
   if (instance == null) throw new InvalidOperationException("ContentManager is not initialized.");
   var func = new Func<string, IStorableContent>(instance.LoadContent);
   func.BeginInvoke(filename, delegate(IAsyncResult result) {
     Exception error = null;
     IStorableContent content = null;
     try {
       content = func.EndInvoke(result);
       content.Filename = filename;
     }
     catch (Exception ex) {
       error = ex;
     }
     loadingCompletedCallback(content, error);
   }, null);
 }
示例#7
0
        static void Main(string[] args)
        {
            Func<int, int, int> additionDel = new Func<int, int, int>(Addition);
            int ret = additionDel.Invoke(1, 2);
            Console.WriteLine("From Sync invoke " + ret);
            object state = new Object();
            IAsyncResult _asyncresult = additionDel.BeginInvoke(1,2,null, null);
            //calling thread blocks until endInvokecompletes
            ret= additionDel.EndInvoke(_asyncresult);
            Console.WriteLine("From Aynsc EndInvoke " + ret);

             _asyncresult = additionDel.BeginInvoke(1, 2, new AsyncCallback(PrintCallBack), null);
            // ret = additionDel.EndInvoke(_asyncresult);
            // Console.WriteLine("From Aynsc EndInvoke On asyncCallback" + ret);

             Thread.Sleep(5000);

        }
示例#8
0
 public void RefreshAsync(Action<Exception> exceptionCallback) {
   var call = new Func<Exception>(delegate() {
     try {
       Refresh();
     }
     catch (Exception ex) {
       return ex;
     }
     return null;
   });
   call.BeginInvoke(delegate(IAsyncResult result) {
     Exception ex = call.EndInvoke(result);
     if (ex != null) exceptionCallback(ex);
   }, null);
 }
示例#9
0
 public NewsModel EndGetNews(IAsyncResult asyncResult)
 {
     return(operation.EndInvoke(asyncResult));
 }
示例#10
0
        public void Execute(ITracer tracer, Stream input, Stream output, string arguments, params object[] args)
        {
            using (GetProcessStep(tracer, arguments, args))
            {
                var process = CreateProcess(arguments, args);
                process.Start();

                Func <StreamReader, string>   reader     = (StreamReader streamReader) => streamReader.ReadToEnd();
                Action <Stream, Stream, bool> copyStream = (Stream from, Stream to, bool closeAfterCopy) =>
                {
                    try
                    {
                        from.CopyTo(to);
                        if (closeAfterCopy)
                        {
                            to.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        tracer.TraceError(ex);
                    }
                };

                IAsyncResult errorReader = reader.BeginInvoke(process.StandardError, null, null);
                IAsyncResult inputResult = null;

                if (input != null)
                {
                    // Copy into the input stream, and close it to tell the exe it can process it
                    inputResult = copyStream.BeginInvoke(input,
                                                         process.StandardInput.BaseStream,
                                                         true,
                                                         null,
                                                         null);
                }

                // Copy the exe's output into the output stream
                IAsyncResult outputResult = copyStream.BeginInvoke(process.StandardOutput.BaseStream,
                                                                   output,
                                                                   false,
                                                                   null,
                                                                   null);

                process.WaitForExit();

                // Wait for the input operation to complete
                if (inputResult != null)
                {
                    inputResult.AsyncWaitHandle.WaitOne();
                }

                // Wait for the output operation to be complete
                outputResult.AsyncWaitHandle.WaitOne();

                string error = reader.EndInvoke(errorReader);

                tracer.Trace("Process dump", new Dictionary <string, string>
                {
                    { "exitCode", process.ExitCode.ToString() },
                    { "type", "processOutput" }
                });

                if (process.ExitCode != 0)
                {
                    throw new CommandLineException(error)
                          {
                              ExitCode = process.ExitCode,
                              Error    = error
                          };
                }
            }
        }
示例#11
0
 /// <summary>
 /// 搜索频道
 /// </summary>
 public void Search()
 {
     this.IsLoading = true;
     var action = new Func<string, int, List<Logic.Models.SearchResult>>(this.SearchBLL.RemoteSearch);
     action.BeginInvoke(this.Keywords, 1, ar => 
     {
         var list = action.EndInvoke(ar);
         this.InvokeOnUIDispatcher(new Action(() =>
         {
             foreach (var item in list)
             {
                 this.SearchResultList.Add(item);
             }
             this.IsLoading = false;
         }));
     }, null);
 }
 public object Invoke(Delegate method, object[] args)
 {
     sawInvoke = true;
     action = () => method.DynamicInvoke(args);
     return action.EndInvoke(action.BeginInvoke(null, null));
 }
示例#13
0
 private void Execute(Func<string> worker, Action<string> completeMethod)
 {
     if (_handleCreated)
         worker.BeginInvoke(ar =>
         {
             var result = worker.EndInvoke(ar);
             BeginInvoke(completeMethod, result);
         }, null);
     else
         lock (_queuedExecutions)
             _queuedExecutions.Enqueue(new Tuple<Func<string>, Action<string>>(worker, completeMethod));
 }
示例#14
0
        /// <summary>
        /// 本方法 通过 启用2个异步处理.
        /// 
        /// 等待 2个 异步处理中的任意一个执行完毕. 然后返回结果.
        /// 
        /// 此方式主要用于像下面这种情况:
        /// (比如有两个排序算法,它们哪个快取决于数据源,我们一起执行并且只要有一个得到结果就继续)
        /// 
        /// </summary>
        public static void WaitAnyTest()
        {
            Console.WriteLine("==#{0}主线程处理开始:{1}",
                            Thread.CurrentThread.ManagedThreadId,
                            DateTime.Now.ToString("hh:mm:ss"));

            // 定义方法.
            var func = new Func<string, int, string>(AsyncOperation2);

            // 异步调用.
            var result1 = func.BeginInvoke("hello ", 2000, null, null);
            var result2 = func.BeginInvoke("world ", 3000, null, null);


            Thread.Sleep(1000);

            Console.WriteLine("==#{0}主线程处理结束,等待2个 异步处理中的任意一个执行完毕:{1}",
                            Thread.CurrentThread.ManagedThreadId,
                            DateTime.Now.ToString("hh:mm:ss"));


            // 等待 2个 异步处理中的任意一个执行完毕.
            WaitHandle.WaitAny(
                new WaitHandle[] { 
                    result1.AsyncWaitHandle, 
                    result2.AsyncWaitHandle });

            // 判断 result1 异步执行是否执行完毕.
            string r1 = result1.IsCompleted ? func.EndInvoke(result1) : string.Empty;

            // 判断 result2 异步执行是否执行完毕.
            string r2 = result2.IsCompleted ? func.EndInvoke(result2) : string.Empty;
            
            

            if (string.IsNullOrEmpty(r1))
            {
                // 如果 r1 为空, 说明 异步调用处理过程中,result2 处理完成了。 result1 处理未完成.
                Console.WriteLine("==#{0} : 异步处理结果:{1}  {2}",
                    Thread.CurrentThread.ManagedThreadId,
                    r2,
                    DateTime.Now.ToString("hh:mm:ss"));

                //  让 result1 处理完成,并释放资源.
                func.EndInvoke(result1);
            }

            if (string.IsNullOrEmpty(r2))
            {
                // 如果 r2 为空, 说明 异步调用处理过程中,result1 处理完成了。 result2 处理未完成.
                Console.WriteLine("==#{0} : 异步处理结果:{1}  {2}",
                    Thread.CurrentThread.ManagedThreadId,
                    r1,
                    DateTime.Now.ToString("hh:mm:ss"));

                //  让 result2 处理完成,并释放资源.
                func.EndInvoke(result2);
            }

            Console.WriteLine();
        }
示例#15
0
 //ThreadPoolで非同期処理実施し戻り値が使用するパターン
 //APM(Asynchronous Programming Model)
 private void button4_Click(object sender, EventArgs e)
 {
     this.button4.Enabled = false;
     var ayncMethod = new Func<string>(() =>
     {
         Thread.Sleep(3000);
         return "3秒経過";
     });
     ayncMethod.BeginInvoke(ar => 
     {
         var res = ayncMethod.EndInvoke(ar);
         this.BeginInvoke((Action)(()=>
         {
             this.button4.Enabled = true;
             this.button4.Text = res;
         }));
     },null);
 }
示例#16
0
        public TResult HandleRequest <TResult>(ProxyRequest <T, TResult> proxyRequest)
        {
            var cachePolicy = _cachePolicyProvider.GetPolicy(proxyRequest.Method, proxyRequest.Parameters);

            if (cachePolicy == null || cachePolicy.CacheDuration == 0)
            {
                return(GetRealResult(proxyRequest));
            }

            var cachedItem = _cacheProvider.GetItem(proxyRequest, cachePolicy) ?? new CachedObject <TResult>(CachedObjectState.None, null);

            if (cachedItem.State == CachedObjectState.Fresh)
            {
                return(cachedItem.Object);
            }

            if (cachedItem.State == CachedObjectState.Exception)
            {
                throw cachedItem.ThrownException;
            }

            var requestKey = new RequestKey(proxyRequest.Method, proxyRequest.Parameters);
            RequestWaitHandle <TResult> waitHandle;

            if (_syncronizer.ShouldWaitForHandle(requestKey, out waitHandle))
            {
                if (cachedItem.State == CachedObjectState.Stale)
                {
                    return(cachedItem.Object);
                }

                return(waitHandle.WaitForResult());
            }

            if (cachedItem.State == CachedObjectState.Stale)
            {
                Func <TResult> loader = () => GetRealResult(proxyRequest);

                loader.BeginInvoke(callback =>
                {
                    Exception asyncRequestThrownException = null;
                    var asyncResult = default(TResult);

                    try
                    {
                        asyncResult = loader.EndInvoke(callback);
                        _cacheProvider.StoreItem(proxyRequest, cachePolicy, asyncResult);
                    }
                    catch (Exception e)
                    {
                        if (cachePolicy.BubbleExceptions)
                        {
                            _cacheProvider.StoreException(proxyRequest, cachePolicy, e);
                            asyncRequestThrownException = e;
                        }
                        else
                        {
                            asyncResult = cachedItem.Object;
                            _cacheProvider.StoreItem(proxyRequest, cachePolicy, asyncResult);
                        }
                    }
                    finally
                    {
                        if (asyncRequestThrownException != null)
                        {
                            _syncronizer.ReleaseWithException <TResult>(requestKey, asyncRequestThrownException);
                        }
                        else
                        {
                            _syncronizer.Release(requestKey, asyncResult);
                        }
                    }
                }, null);

                return(cachedItem.Object);
            }

            //At this point nothing is in the cache.
            var       realInstanceResult = default(TResult);
            Exception thrownException    = null;

            try
            {
                realInstanceResult = GetRealResult(proxyRequest);
                _cacheProvider.StoreItem(proxyRequest, cachePolicy, realInstanceResult);
            }
            catch (Exception e)
            {
                thrownException = e;
                _cacheProvider.StoreException(proxyRequest, cachePolicy, thrownException);

                throw;
            }
            finally
            {
                if (thrownException != null)
                {
                    _syncronizer.ReleaseWithException <TResult>(requestKey, thrownException);
                }
                else
                {
                    _syncronizer.Release(requestKey, realInstanceResult);
                }
            }

            return(realInstanceResult);
        }
示例#17
0
        /// <summary>
        /// 简单异步调用测试.
        /// 
        /// 本方法 通过 启用2个异步处理.
        /// 
        /// 主线程 等待这2个异步处理都执行完毕后,输出这2个异步处理的执行结果.
        /// 
        /// </summary>
        public static void SimpleInvokeTest()
        {
            Console.WriteLine("==#{0}主线程处理开始:{1}",
                            Thread.CurrentThread.ManagedThreadId,
                            DateTime.Now.ToString("hh:mm:ss"));

            // 定义方法.
            var func = new Func<int, int, int>(AsyncOperation);

            // 异步调用1.
            var result1 = func.BeginInvoke(100, 200, null, null);
            // 异步调用2.
            var result2 = func.BeginInvoke(300, 400, null, null);

            // 主线程休眠 1000 毫秒.
            Thread.Sleep(1000);

            Console.WriteLine("==#{0}主线程处理结束:{1}",
                            Thread.CurrentThread.ManagedThreadId,
                            DateTime.Now.ToString("hh:mm:ss"));


            // 通过调用 EndInvoke 方法, 来获取 异步调用的处理结果.
            int result = func.EndInvoke(result1) + func.EndInvoke(result2);

            Console.WriteLine("==#{0}主线程获取的 异步操作结果:{1}",
                Thread.CurrentThread.ManagedThreadId,
                result);
            Console.WriteLine();
        }
示例#18
0
        /// <summary>
        /// 加载所有频道
        /// </summary>
        public void LoadChannels()
        {
            //在TabControl中,每切换一次都会触发UserControl的Loaded事件
            //此处应先做次判断,避免无谓的请求服务器
            if (this.AllChannel != null) return;
            this.HasErrors = false;
            var action = new Func<Logic.Models.ChannelList>(this.ChannelBLL.GetChannelList);
            action.BeginInvoke(ar =>
            {
                Logic.Models.ChannelList channelList = null;
                try
                {
                    channelList = action.EndInvoke(ar);
                }
                catch
                {
                    this.EventAggregator.GetEvent<LoadChannelFailedEvent>().Publish("加载频道失败!请检查网络设置!");
                    this.HasErrors = true;
                    return;
                }
                this.AllChannel = channelList;
                this.InvokeOnUIDispatcher(new Action(() =>
                {
                    foreach (var item in channelList.PersonalChannelList)
                    {
                        this.PersonalChannelList.Add(item);
                    }
                    foreach (var item in channelList.PublicChannelList)
                    {
                        this.PublicChannelList.Add(item);
                    }

                    //默认加载一个频道
                    this.CurrentChannel = this.PublicChannelList.OrderBy(t => Guid.NewGuid()).FirstOrDefault();
                }));

            }, null);
        }
示例#19
0
 /// <summary>
 /// 加载歌曲
 /// </summary>
 public void LoadSongList()
 {
     if (this.IsLoading) return;
     this.IsLoading = true;
     var action = new Func<Logic.Models.Channel, Logic.Models.Song, string, Logic.Models.SongList>(this.SongBLL.GetSongList);
     action.BeginInvoke(this.CurrentChannel, this.CurrentSong, "n", ar => 
     {
         this.IsLoading = false;
         Logic.Models.SongList songList = null;
         try
         {
             songList = action.EndInvoke(ar);
         }
         catch
         {
             this.EventAggregator.GetEvent<LoadSongListFailedEvent>().Publish("加载歌曲列表失败!请检查网络链接!");
         }
         if (songList == null) return;
         this.TempSongList.Clear();
         this.TempSongList.AddRange(songList.Songs);
         this.CurrentSong = this.TempSongList.FirstOrDefault();
     }, null);            
 }
示例#20
0
 public SimpleTabCompletionSource(Func<IEnumerable<string>> asyncCandidateFetcher)
 {
     candidates = new string[0];
     this.MinCharsBeforeCyclingBegins = 3;
     asyncCandidateFetcher.BeginInvoke((result) =>
     {
         try
         {
             candidates = asyncCandidateFetcher.EndInvoke(result);
         }
         catch (Exception)
         {
             // swallow these
         }
     }, null);
 }
示例#21
0
 public FahrenheitToCelsiusResponse EndFahrenheitToCelsius(IAsyncResult result)
 {
     return(farenheitToCelsius.EndInvoke(result));
 }
示例#22
0
        /// <summary>
        /// 本方法 通过 启用1个异步处理.
        /// 
        /// 然后通过 周期的去 查询 IsCompleted 。
        /// 来判断异步处理是否完成.
        /// 
        /// </summary>
        public static void IsCompletedTest()
        {

            Console.WriteLine("==#{0}主线程处理开始:{1}",
                            Thread.CurrentThread.ManagedThreadId,
                            DateTime.Now.ToString("hh:mm:ss"));

            // 定义方法.
            var func = new Func<int, int, int>(AsyncOperation);

            // 异步调用.
            var result = func.BeginInvoke(100, 200, null, null);



            Thread.Sleep(1000);

            Console.WriteLine("==#{0}主线程处理结束:{1}",
                            Thread.CurrentThread.ManagedThreadId,
                            DateTime.Now.ToString("hh:mm:ss"));


            while (!result.IsCompleted)
            {
                Console.WriteLine("==#{0}主线程等待异步处理执行完毕:{1}",
                                Thread.CurrentThread.ManagedThreadId,
                                DateTime.Now.ToString("hh:mm:ss"));
                Thread.Sleep(500);
            }

            int r = func.EndInvoke(result);

            Console.WriteLine("==#{0}主线程获取的 异步操作结果:{1}",
                Thread.CurrentThread.ManagedThreadId,
                r);

            Console.WriteLine();
        }
示例#23
0
 private void FooCallBack(IAsyncResult ar)
 {
     caller = (Func <int, int, int>)ar.AsyncState;; //获得BeginInvoke第4个参数
     int number = caller.EndInvoke(ar);             //获取运算的结果
 }
示例#24
0
 public override int EndRead(IAsyncResult asyncResult)
 {
     return(readFunction.EndInvoke(asyncResult));
 }
 /// <summary>
 /// 加载数据
 /// </summary>
 void LoadData()
 {
     if (IsLoading) return;
     this.IsLoading = true;
     var client = new WebService.WeatherWebServiceSoapClient();
     var func = new Func<DataSet>(client.getSupportDataSet);
     func.BeginInvoke(ar =>
     {
         var ds = func.EndInvoke(ar);
         InvokeOnUIDispatcher(new Action(() =>
         {
             this.InitZoneFromDataSet(ds);
             //this.CurrentZoneID = this.CurrentArea.ZoneID;
             //this.CurrentAreaID = this.CurrentArea.ID;
             this.IsLoading = false;
         }));
     }, null);
 }
示例#26
0
        private void EndRead(IAsyncResult asyncResult)
        {
            try
            {
                byte parameter;
                try
                {
                    parameter = _readByteDelegate.EndInvoke(asyncResult); //no data available
                }
                catch (IOException)
                {
                    Dispose();
                    return;
                }

                var size = _binaryReader.ReadInt32();

                var bytes = _binaryReader.ReadBytes(size);
                LastAnswer = DateTime.UtcNow;

                ushort administrationId;
                switch ((FromClientPackage)parameter)
                {
                case FromClientPackage.ResponseToAdministration:
                case FromClientPackage.ResponseToAdministrationCompressed:
                    administrationId = BitConverter.ToUInt16(bytes, 0);

                    Logger.Debug("Client CI-{0} sends command response to administration AI-{1}", Id, administrationId);
                    SendToAdministration?.Invoke(this,
                                                 new SendPackageToAdministrationEventArgs(administrationId, parameter,
                                                                                          new WriterCall(bytes, 2, bytes.Length - 2)));
                    break;

                case FromClientPackage.ResponseLoginOpen:
                    administrationId = BitConverter.ToUInt16(bytes, 0);
                    Logger.Debug("Client CI-{0} opened session with AI-{1}", Id, administrationId);

                    SendToAdministration?.Invoke(this,
                                                 new SendPackageToAdministrationEventArgs(administrationId,
                                                                                          (byte)FromClientPackage.ResponseLoginOpen, new WriterCall(BitConverter.GetBytes(Id))));
                    break;

                case FromClientPackage.SubmitExceptions:
                    //log handled in server
                    ExceptionsReveived?.Invoke(this,
                                               new ExceptionsReveivedEventArgs(
                                                   ExceptionInfosSerializer.Value.Deserialize <List <ExceptionInfo> >(LZF.Decompress(bytes, 0))));
                    break;

                case FromClientPackage.ServerPackage:
                    //log handled in server
                    ProcessServerPackage(ServerPackageSerializer.Value.Deserialize <ServerPackage>(bytes));
                    break;

                case FromClientPackage.ResponseStaticCommandResult:
                    var          dynamicCommandId = BitConverter.ToInt32(bytes, 0);
                    var          message          = "";
                    ActivityType activityType;

                    if (ComputerInformation.ClientVersion >= 19)
                    {
                        activityType = (ActivityType)bytes[4];
                    }
                    else
                    {
                        activityType = bytes[4] == 0 ? ActivityType.Succeeded : ActivityType.Failed;
                    }

                    if (ComputerInformation.ClientVersion >= 13)
                    {
                        message = Encoding.UTF8.GetString(bytes, 5, bytes.Length - 5);
                    }

                    ReceivedStaticCommandResult?.Invoke(this,
                                                        new DynamicCommandEvent
                    {
                        ClientId       = Id,
                        DynamicCommand = dynamicCommandId,
                        Timestamp      = DateTime.UtcNow,
                        Message        = message,
                        Status         = activityType
                    });
                    break;

                case FromClientPackage.PluginLoaded:
                    var pluginInfo = new PluginInfo
                    {
                        Guid     = new Guid(bytes.Take(16).ToArray()),
                        Version  = Encoding.ASCII.GetString(bytes, 16, bytes.Length - 16),
                        IsLoaded = true
                    };

                    Logger.Debug("Client CI-{0} loaded plugin {1:D} successfully", Id, pluginInfo.Guid);

                    ComputerInformation.Plugins.Add(pluginInfo);
                    PluginLoaded?.Invoke(this, new PluginLoadedEventArgs(pluginInfo));
                    break;

                case FromClientPackage.PluginLoadFailed:
                    Logger.Debug("Client CI-{0} was unable to load plugin", Id);

                    SendToAdministration?.Invoke(this,
                                                 new SendPackageToAdministrationEventArgs(BitConverter.ToUInt16(bytes, 0),
                                                                                          (byte)FromClientPackage.PluginLoadFailed, new WriterCall(2 + bytes.Length, writer =>
                    {
                        writer.Write(Id);
                        writer.Write(bytes, 2, bytes.Length - 2);
                    })));
                    break;

                case FromClientPackage.ResponseActiveWindow:
                    administrationId = BitConverter.ToUInt16(bytes, 0);

                    //+ 4 because of client id int, -2 because of administration id ushort
                    SendToAdministration?.Invoke(this,
                                                 new SendPackageToAdministrationEventArgs(administrationId,
                                                                                          (byte)FromClientPackage.ResponseActiveWindow, new WriterCall(bytes.Length + 2,
                                                                                                                                                       writer =>
                    {
                        writer.Write(Id);
                        writer.Write(bytes, 2, bytes.Length - 2);
                    })));
                    break;

                case FromClientPackage.ResponseScreenshot:
                    administrationId = BitConverter.ToUInt16(bytes, 0);
                    //+ 4 because of client id int, -2 because of administration id ushort
                    SendToAdministration?.Invoke(this,
                                                 new SendPackageToAdministrationEventArgs(administrationId,
                                                                                          (byte)FromClientPackage.ResponseScreenshot, new WriterCall(bytes.Length + 2,
                                                                                                                                                     writer =>
                    {
                        writer.Write(Id);
                        writer.Write(bytes, 2, bytes.Length - 2);
                    })));
                    break;

                case FromClientPackage.InitializePushFile:
                    //log handled in PushManager
                    _tcpServerInfo.PushManager.PushRequest(new Guid(bytes), this);
                    break;

                case FromClientPackage.PushHeader:
                    FilePush?.Invoke(this,
                                     new FilePushEventArgs(FilePushPackageType.Header, bytes,
                                                           new Guid(bytes.Take(16).ToArray())));
                    break;

                case FromClientPackage.PushFileData:
                    FilePush?.Invoke(this,
                                     new FilePushEventArgs(FilePushPackageType.Data, bytes,
                                                           new Guid(bytes.Take(16).ToArray())));
                    break;

                case FromClientPackage.StillAlive:
                    break;

                case FromClientPackage.RequestStaticCommandPlugin:
                    _tcpServerInfo.DynamicCommandManager.DynamicCommandPluginSender.RequestPlugin(this,
                                                                                                  BitConverter.ToInt32(bytes, 0));
                    break;

                case FromClientPackage.ResponseLibraryInformation:
                    Logger.Debug("Client CI-{0} requests more detailed information about library", Id);

                    SendToAdministration?.Invoke(this,
                                                 new SendPackageToAdministrationEventArgs(BitConverter.ToUInt16(bytes, 0),
                                                                                          (byte)FromClientPackage.ResponseLibraryInformation, new WriterCall(2 + bytes.Length, writer =>
                    {
                        writer.Write(Id);
                        writer.Write(bytes, 2, bytes.Length - 2);
                    })));
                    break;

                case FromClientPackage.ResponseLibraryLoadingResult:
                    Logger.Debug("Client CI-{0} responded with the result of the library loading operation", Id);

                    SendToAdministration?.Invoke(this,
                                                 new SendPackageToAdministrationEventArgs(BitConverter.ToUInt16(bytes, 0),
                                                                                          (byte)FromClientPackage.ResponseLibraryLoadingResult, new WriterCall(2 + bytes.Length, writer =>
                    {
                        writer.Write(Id);
                        writer.Write(bytes, 2, bytes.Length - 2);
                    })));
                    break;

                case FromClientPackage.CheckStillAlive:
                    break;     //do nothing, TCP already responded when this package is here

                default:
                    throw new ArgumentOutOfRangeException();
                }

                _readByteDelegate.BeginInvoke(EndRead, null);
            }
            catch (Exception ex)
            {
                if (IsDisposed)
                {
                    return;
                }

                Logger.Fatal(ex, "Error on reading data from client CI-{0}", Id);
                Dispose();
            }
        }
 public void TimeoutTest()
 {
     // Arrange.
     var func = new Func<ProcessExecutionResult>(() => ProcessRunner.RunProcess("cmd.exe", PauseArguments, Timeout));
     // Act.
     var result = func.BeginInvoke((a) => { }, null);
     result.AsyncWaitHandle.WaitOne(Timeout + AdditionalTimeout);
     // Assert.
     if (result.IsCompleted)
     {
         func.EndInvoke(result);
     }
 }
示例#28
0
 public object EndGetData(IAsyncResult result)
 {
     return(gd.EndInvoke(result));
 }
示例#29
0
 void onCallback(IAsyncResult ar)
 {
     Func <int, string, int> a = ar.AsyncState as Func <int, string, int>;
     int ret = a.EndInvoke(ar);
 }
示例#30
0
 public DataType2 EndGetNestedData(IAsyncResult result)
 {
     return(gnd.EndInvoke(result));
 }
 protected override bool OnEndWaitForChannel(IAsyncResult result)
 {
     return(_waitForChannelMethod.EndInvoke(result));
 }
示例#32
0
 public void ExecuteActionAsync(Action action) {
   var call = new Func<Exception>(delegate() {
     try {
       action();
     }
     catch (Exception ex) {
       return ex;
     }
     finally {
       HideProgressBar();
     }
     return null;
   });
   call.BeginInvoke(delegate(IAsyncResult result) {
     Exception ex = call.EndInvoke(result);
     if (ex != null) PluginInfrastructure.ErrorHandling.ShowErrorDialog(ex);
   }, null);
 }
示例#33
0
 protected override bool OnEndWaitForChannel(IAsyncResult result)
 {
     return(_onWaitForChannelHandler.EndInvoke(result));
 }
 protected override TChannel OnEndAcceptChannel(IAsyncResult result)
 {
     return(_acceptChannelMethod.EndInvoke(result));
 }
 static string EndGreeting(IAsyncResult ar)
 {
     return(greetingInvoker.EndInvoke(ar));
 }
        public void CreateEmbroidery(Preview preview, string imageName, int coefficient, int cellsCount, DColor[] palette, char[] symbols, DColor symbolColor, Embroidery.GridType gridType)
        {

            BitmapSource bitmapSource = null;

            try
            {
                DBitmap _imageFromFile = new DBitmap(imageName);

                Func<DBitmap, DBitmap> getCopyBitmap = new Func<DBitmap, DBitmap>(GetCopyOfBitmap);
                IAsyncResult getCopyBitmapResult = getCopyBitmap.BeginInvoke(_imageFromFile, null, null);
                DBitmap inputImage = getCopyBitmap.EndInvoke(getCopyBitmapResult);

                Embroidery.EmbroideryCreatorServiceClient wcf_service = new Embroidery.EmbroideryCreatorServiceClient();

                Func<DBitmap, int, int, DColor[], char[], DColor, Embroidery.GridType, DBitmap> getEmbroidery = new Func<DBitmap, int, int, DColor[], char[], DColor, Embroidery.GridType, DBitmap>(wcf_service.GetEmbroidery);
                IAsyncResult getEmbroideryResult = getEmbroidery.BeginInvoke(inputImage, coefficient, cellsCount, palette, symbols, DColor.Black, gridType, null, null);
                DBitmap resultImage = getEmbroidery.EndInvoke(getEmbroideryResult);


                if (resultImage == null)
                {
                    MessageBox.Show("Some error occured on the server");
                    //HideLoading();
                    return;
                }

                bitmapSource = GetBitmapSource(resultImage);
            }
            catch (OutOfMemoryException ex)
            {
                MessageBox.Show("Sorry, but image is too large :(");
                //HideLoading();
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Some exception was occured. Message: " + ex.Message);
                //HideLoading();
                return;
            }

            bitmapSource.Freeze();

            preview.Dispatcher.BeginInvoke(new Action(() =>
                {
                    preview.loadingPanel.Visibility = System.Windows.Visibility.Collapsed;
                    preview.previewImage.Source = bitmapSource;
                }),
                System.Windows.Threading.DispatcherPriority.Normal);
           

        }
示例#37
0
 public ObservableCollection <object> EndGetCollectionData(IAsyncResult result)
 {
     return(gcd.EndInvoke(result));
 }
示例#38
0
 public Message EndReceive(IAsyncResult result)
 {
     return(receive_delegate.EndInvoke(result));
 }
示例#39
0
 public JSMGetDatabasesResponse EndJSMGetDatabases(IAsyncResult result)
 {
     return(gjgdb.EndInvoke(result));
 }
示例#40
0
 public bool EndWaitForMessage(IAsyncResult result)
 {
     return(wait_delegate.EndInvoke(result));
 }
示例#41
0
 public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken) {
   var call = new Func<Exception>(delegate() {
     try {
       Store(item, cancellationToken);
     }
     catch (Exception ex) {
       return ex;
     }
     return null;
   });
   call.BeginInvoke(delegate(IAsyncResult result) {
     Exception ex = call.EndInvoke(result);
     if (ex != null) exceptionCallback(ex);
   }, null);
 }
示例#42
0
 private static string ConvertingEndInvoke(IAsyncResult ar)
 {
     return(convertFun.EndInvoke(ar));
 }
示例#43
0
 public override int EndRead(IAsyncResult asyncResult)
 {
     return(read_delegate.EndInvoke(asyncResult));
 }
示例#44
0
 public virtual Message EndRequest(IAsyncResult result)
 {
     return(request_delegate.EndInvoke(result));
 }
示例#45
0
 public CelsiusToFahrenheitResponse EndCelsiusToFahrenheit(IAsyncResult result)
 {
     return(celsiusToFarenheit.EndInvoke(result));
 }
示例#46
0
 public void EndExecuteDaxReader(IAsyncResult result)
 {
     _execReader.EndInvoke(result);
 }
示例#47
0
 public ServiceRecord[] EndGetServiceRecords(IAsyncResult asyncResult)
 {
     return(_dlgtGetServiceRecords.EndInvoke(asyncResult));
 }
示例#48
0
        protected override IEnumerable EndExecuteSelect(IAsyncResult asyncResult)
        {
            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Begin");

            if (_client == null)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End: _client=null");

                return(null);
            }

            IEnumerable selectResult = null;
            int         rowsAffected = 0;

            try
            {
                SynchronousAsyncSelectResult syncResult = asyncResult as SynchronousAsyncSelectResult;

                if (syncResult != null)
                {
                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, "syncResult");

                    selectResult = syncResult.SelectResult;
                }
                else
                {
                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, "EndExecute");

                    if (!Owner.IsSingleSource)
                    {
                        var response = _execute != null?_execute.EndInvoke(asyncResult) : _executeFetchMultiple.EndInvoke(asyncResult);

                        if (response != null)
                        {
                            var entities = response.Entities;
                            rowsAffected = entities.Count;
                            selectResult = ExecuteSelect(entities).ToList();

                            if (Owner.CacheParameters.Enabled)
                            {
                                IEnumerable <string> dependencies;
                                string cacheKey;
                                if (Request.Query != null)
                                {
                                    dependencies = GetCacheDependencies(Request.Query, selectResult);
                                    cacheKey     = GetCacheKey(Request.Query);
                                }
                                else
                                {
                                    dependencies = GetCacheDependencies(Fetch, selectResult, Owner.IsSingleSource);
                                    cacheKey     = GetCacheKey(Request.Query);
                                }

                                // insert into cache
                                ObjectCacheManager.GetInstance().Insert(cacheKey, selectResult, dependencies);
                            }
                        }
                    }
                    else
                    {
                        var entity = _executeSingle.EndInvoke(asyncResult);
                        if (entity != null)
                        {
                            selectResult = ExecuteSelect(new[] { entity }).ToList();
                            if (Owner.CacheParameters.Enabled)
                            {
                                var dependencies = GetCacheDependencies(Fetch, selectResult, Owner.IsSingleSource);
                                var cacheKey     = GetCacheKey(Fetch.ToFetchExpression());

                                // insert into cache
                                ObjectCacheManager.GetInstance().Insert(cacheKey, selectResult, dependencies);
                            }
                        }
                    }
                }
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("{0}\n\n{1}", ex.Detail.InnerXml, ex.ToString()));
            }
            catch (Exception e)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception: {0}", e.ToString()));

                // raise post-event with exception
                CrmDataSourceStatusEventArgs selectedExceptionArgs = new CrmDataSourceStatusEventArgs(0, e);
                OnSelected(selectedExceptionArgs);

                if (!selectedExceptionArgs.ExceptionHandled)
                {
                    throw;
                }

                return(selectResult);
            }
            finally
            {
                _client = null;
            }

            // raise post-event
            CrmDataSourceStatusEventArgs selectedArgs = new CrmDataSourceStatusEventArgs(rowsAffected, null);

            OnSelected(selectedArgs);

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");

            return(string.IsNullOrEmpty(Owner.StaticEntityWrapperTypeName) ? selectResult : CreateEntities(selectResult));
        }
示例#49
0
        public void Login()
        {
            if (string.IsNullOrWhiteSpace(this.UserName))
            {
                this.ErrorMessage = "用户名不能为空!";
                return;
            }
            if (string.IsNullOrWhiteSpace(this.Password))
            {
                this.ErrorMessage = "密码不能为空!";
                return;
            }
            if (string.IsNullOrWhiteSpace(this.Captcha))
            {
                this.ErrorMessage = "验证码不能为空!";
                return;
            }
            this.ErrorMessage = null;

            IsLoading = true;
            var action = new Func<string, string, string, string, bool, Logic.Models.LoginResult>(this.AccountBLL.Login);
            action.BeginInvoke(this.UserName, this.Password, this.Captcha, this.CaptchaID, false, ar => 
            {
                IsLoading = false;
                var result = action.EndInvoke(ar);
                if (result.R > 0)
                {
                    this.ErrorMessage = result.Message;
                    this.LoadCaptcha();
                }
                else
                {
                    this.CurrentLoginUser = result.UserInfo;
                    
                }                
            }, null);
        }
示例#50
0
        public JobManagerForm(Func <JobManagerFramework.JobManager> getJobManager, Dictionary <string, string> settings = null)
        {
            Func <string> getHeader       = () => META.Logger.Header();
            var           getHeaderResult = getHeader.BeginInvoke(null, null);

            InitializeComponent();

            InitJobQueue();

            this.toolStripStatusLabel      = new SpringLabel();
            this.toolStripStatusLabel.Text = "Loading";
            this.statusStrip1.Items.Add(this.toolStripStatusLabel);
            this.lvJobQueue.DoubleClick += showInExplorerToolStripMenuItem_Click;

            this.remoteServiceStatusForm = new RemoteServiceStatusForm();

            if (settings != null)
            {
                string value = string.Empty;
                if (settings.TryGetValue("-u", out value))
                {
                    Properties.Settings.Default.UserID = value;
                }
                if (settings.TryGetValue("-p", out value))
                {
                    password = value;
                }
                if (settings.TryGetValue("-U", out value))
                {
                    Properties.Settings.Default.VehicleForgeUri = value;
                }
            }

            //this.TempDir = Path.Combine(System.IO.Path.GetTempPath(), "META_JobManager");

            this.TempDir = Path.Combine(
                System.IO.Path.GetTempPath(),
                Path.Combine("META", "JobManager"));


            if (Directory.Exists(this.TempDir) == false)
            {
                Directory.CreateDirectory(this.TempDir);
            }

            this.TraceFileName = Path.Combine(this.TempDir, string.Format("JobManagerLog.trace.{0}.txt", Process.GetCurrentProcess().Id));

            this.logToolStripMenuItem.ToolTipText += string.Format(" ({0})", Path.GetFullPath(this.TraceFileName));

            var           fs     = new FileStream(this.TraceFileName, FileMode.Create);
            TraceListener fileTL = new TextWriterTraceListener(fs)
            {
                TraceOutputOptions = TraceOptions.DateTime
            };

            // use TraceXXX to get timestamp per http://stackoverflow.com/questions/863394/add-timestamp-to-trace-writeline

            Trace.AutoFlush = true;
            Trace.Listeners.Add(fileTL);

            Trace.TraceInformation(getHeader.EndInvoke(getHeaderResult));

            manager           = getJobManager();
            this.FormClosing += (sender, args) =>
            {
                if (manager.HasIncompleteSots)
                {
                    DialogResult dr = MessageBox.Show(this, "Some jobs have not been posted and will be lost. Do you want to exit anyways?", "JobManager", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No)
                    {
                        args.Cancel = true;
                        return;
                    }
                }
                if (manager.IsRemote == false)
                {
                    int unfinished = manager.UnfinishedJobCount;
                    if (unfinished > 0)
                    {
                        DialogResult dr = MessageBox.Show(this, unfinished + " jobs have not completed. Do you want to exit and terminate running processes?", "JobManager", MessageBoxButtons.YesNo);
                        if (dr == DialogResult.No)
                        {
                            args.Cancel = true;
                            return;
                        }
                    }
                }
                Trace.TraceInformation("JobManager is closing");
                manager.Dispose();
                manager = null;
            };
            this.Resize       += new EventHandler(JobManager_Resize);
            NotifyIcon         = new NotifyIcon();
            NotifyIcon.Icon    = Icon;
            NotifyIcon.Visible = false;
            NotifyIcon.Click  += new EventHandler(NotifyIcon_Click);
            this.exitToolStripMenuItem.Click += new EventHandler((o, ev) =>
            {
                this.Close();
            });

            manager.JobAdded += Manager_JobAdded;
            manager.SotAdded += Manager_SotAdded;
            //pool.JobStatusChanged += JobStatusChanged;

            if (settings.ContainsKey("-i"))
            {
                this.toolStripStatusLabel.Text             = "Configured for local execution.";
                this.remoteStatusToolStripMenuItem.Enabled = false;
                this.remoteStatusToolStripMenuItem.Visible = false;
                return;
            }
            Shown += new EventHandler(delegate(object o, EventArgs args)
            {
                if (this.Configure() == DialogResult.OK)
                {
                    lock (this)
                    {
                        //TODO: determine if set for remote execution and show in status bar
                        if (manager.IsRemote)
                        {
                            this.toolStripStatusLabel.Text             = "Configured for remote execution.";
                            this.remoteStatusToolStripMenuItem.Enabled = true;
                            this.remoteStatusToolStripMenuItem.Visible = true;
                        }
                        else
                        {
                            this.toolStripStatusLabel.Text             = "Configured for local execution.";
                            this.remoteStatusToolStripMenuItem.Enabled = false;
                            this.remoteStatusToolStripMenuItem.Visible = false;
                        }

                        manager.ServiceStatusUpdated += UpdateServiceStatus;
                        manager.LoadSavedJobs();
                    }
                }
                else
                {
                    this.toolStripStatusLabel.Text = "Closing";
                    this.Close();
                }
            });

            Trace.TraceInformation("Application started.");
        }
 public void Refresh()
 {
     if (this.IsLoading) return;
     this.IsLoading = true;
     var client = new WebService.WeatherWebServiceSoapClient();
     var func = new Func<string, string[]>(client.getWeatherbyCityName);
     func.BeginInvoke(this.CurrentArea.Name, ar =>
     {
         var data = func.EndInvoke(ar);
         this.WeatherInfo = new Models.WeatherInfo(data);
         this.RefreshTime = DateTime.Now;
         this.IsLoading = false;
     }, null);
 }
示例#52
0
 public object EndExecuteScalar(IAsyncResult asyncResult)
 {
     return(funcExecuteScalar.EndInvoke(asyncResult));
 }
        private void SaveButton_Click(object sender, EventArgs e)
        {
            object _button = sender;
            if (_button == null) return;
            bool _enabled = Materia.GetPropertyValue<bool>(_button, "Enabled", true);
            if (!_enabled) return;

            _saving = false; GridFinishEdit(); DataBinderValidationEventArgs _args = Validate();

            if (_args != null)
            {
                if (!_args.Valid)
                {
                    if (_args.Control != null)
                    {
                        if (_args.Control.GetType().Name.ToLower().Contains("C1FlexGrid".ToLower()) ||
                            _args.Control.GetType().BaseType.Name.ToLower().Contains("C1FlexGrid".ToLower()))
                        {
                            if (!String.IsNullOrEmpty(_args.Notification.RLTrim()))
                            {
                                SetControlFocus((Control) _args.Control); MessageBox.Show(_args.Notification, "Entry Validation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                                bool _allowediting = true;

                                try { _allowediting = Materia.GetPropertyValue<bool>(_args.Control, "AllowEditing", true); }
                                catch { }

                                if (_allowediting)
                                {
                                    int _row = -1; int _col = -1;

                                    try { _row = Materia.GetPropertyValue<int>(_args.Control, "Row", -1); }
                                    catch { }

                                    try { _col = Materia.GetPropertyValue<int>(_args.Control, "Col", -1); }
                                    catch { }

                                    if (_row > -1 &&
                                        _col > -1)
                                    {
                                        try { Materia.InvokeMethod(_args.Control, "StartEditing", new object[] { _row, _col }); }
                                        catch { }
                                    }
                                }
                            }

                            return;
                        }
                        else return;
                    }
                    else return;
                }
                else
                {
                    if (_args.Cancel) return;
                }


                _enabled = Materia.GetPropertyValue<bool>(_button, "Enabled", true);
                try { Materia.SetPropertyValue(_button, "Enabled", false); }
                catch { }
                CancelRunningProcess = false; _saving = true;

                Action _valuesetdelegate = new Action(SetFieldValues);
                IAsyncResult _valuesetresult = _valuesetdelegate.BeginInvoke(null, _valuesetdelegate);

                while (!_valuesetresult.IsCompleted &&
                       !CancelRunningProcess)
                {
                    OnDataGathering(new EventArgs());
                    Thread.Sleep(1); Application.DoEvents();
                }

                if (CancelRunningProcess)
                {
                    if (!_valuesetresult.IsCompleted)
                    {
                        try { _valuesetresult = null; }
                        catch { }
                    }

                    try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                    catch { }

                    Materia.RefreshAndManageCurrentProcess(); _saving = false; return;
                }

                _valuesetdelegate.EndInvoke(_valuesetresult);

                Action _fksetdelegate = new Action(SetForeignKeys);
                IAsyncResult _fksetresult = _fksetdelegate.BeginInvoke(null, _fksetdelegate);

                while (!_fksetresult.IsCompleted &&
                       !CancelRunningProcess)
                {
                    OnDataGathering(new EventArgs());
                    Thread.Sleep(1); Application.DoEvents();
                }

                if (CancelRunningProcess)
                {
                    if (!_fksetresult.IsCompleted)
                    {
                        try { _fksetresult = null; }
                        catch { }
                    }

                    try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                    catch { }

                    Materia.RefreshAndManageCurrentProcess(); _saving = false; return;
                }

                _fksetdelegate.EndInvoke(_fksetresult);

                Func<string> _sqlgetdelegate = new Func<string>(Binding.GetUpdateStatements);
                IAsyncResult _sqlgetresult = _sqlgetdelegate.BeginInvoke(null, _sqlgetdelegate);

                while (!_sqlgetresult.IsCompleted &&
                       !CancelRunningProcess)
                {
                    OnDataGathering(new EventArgs());
                    Thread.Sleep(1); Application.DoEvents();
                }

                if (CancelRunningProcess)
                {
                    if (!_sqlgetresult.IsCompleted)
                    {
                        try { _sqlgetresult = null; }
                        catch { }
                    }

                    try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                    catch { }

                    Materia.RefreshAndManageCurrentProcess(); _saving = false; return;
                }

                string _sql = _sqlgetdelegate.EndInvoke(_sqlgetresult);
                try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                catch { }

                DataBinderSavingEventArgs _saveargs = new DataBinderSavingEventArgs(_sql);
                OnBeforeDataSave(_saveargs); AcceptUpdates();

                if (!_saveargs.Cancel)
                {
                    try { Materia.SetPropertyValue(_button, "Enabled", false); }
                    catch { }

                    _sql = "";

                    Func<string> _sqlgetfinaldelegate = new Func<string>(Binding.GetUpdateStatements);
                    IAsyncResult _sqlgetfinalresult = _sqlgetfinaldelegate.BeginInvoke(null, _sqlgetfinaldelegate);

                    while (!_sqlgetfinalresult.IsCompleted &&
                           !CancelRunningProcess)
                    {
                        OnDataGathering(new EventArgs());
                        Thread.Sleep(1); Application.DoEvents();
                    }

                    if (CancelRunningProcess)
                    {
                        if (_sqlgetfinalresult != null)
                        {
                            try { _sqlgetfinalresult = null; }
                            catch { }
                        }

                        try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                        catch { }

                        Materia.RefreshAndManageCurrentProcess(); _saving = false; return;
                    }

                    string _query = _sqlgetfinaldelegate.EndInvoke(_sqlgetfinalresult);

                    if (WithBlobDataSource())
                    {
                        if (!String.IsNullOrEmpty(_query.RLTrim()))
                        {
                            if (!_query.RLTrim().ToLower().StartsWith("set global max_allowed_packet")) _sql = "SET GLOBAL max_allowed_packet = (1024 * 1204) * " + MySql.MaxAllowedPacket.ToString() + ";";
                        }
                    }

                    _sql += ((!String.IsNullOrEmpty(_sql.RLTrim())) ? "\n" : "") + _query;

                    if (String.IsNullOrEmpty(_sql.RLTrim()))
                    {
                        try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                        catch { }

                        Materia.RefreshAndManageCurrentProcess(); _saving = false; return;
                    }

                    _saveargs.CommandText = _sql;
                    OnDataSaveExecuting(_saveargs);

                    if (_saveargs.Cancel)
                    {
                        try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                        catch { }

                        Materia.RefreshAndManageCurrentProcess(); _saving = false; return;
                    }

                    _sql = _saveargs.CommandText;
                    IAsyncResult _saveresult = Que.BeginExecution(Connection, _sql, CommandExecution.ExecuteNonQuery);

                    while (!_saveresult.IsCompleted &&
                           !CancelRunningProcess)
                    {
                        OnDataSaving(new EventArgs());
                        Thread.Sleep(1); Application.DoEvents();
                    }

                    if (CancelRunningProcess)
                    {
                        if (!_saveresult.IsCompleted)
                        {
                            try { _saveresult = null; }
                            catch { }
                        }

                        try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                        catch { }

                        Materia.RefreshAndManageCurrentProcess(); _saving = false; return;
                    }

                    QueResult _result = Que.EndExecution(_saveresult); _saveargs = null;

                    if (_result == null)
                    {
                        try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                        catch { }

                        Materia.RefreshAndManageCurrentProcess(); _saving = false; return;
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(_result.Error.RLTrim())) _saveargs = new DataBinderSavingEventArgs(_sql, _result.Error);
                        else _saveargs = new DataBinderSavingEventArgs(_sql, _result.RowsAffected);

                        if (!String.IsNullOrEmpty(_result.Error.RLTrim())) _saveargs.ErrorNotification = "An error occured while trying to save the changes and updates to the current record(s). Please try again and\n/ or report this issue to the system administrator.";
                        else
                        {
                            Action _updatedelegate = new Action(Update);
                            IAsyncResult _updateresult = _updatedelegate.BeginInvoke(null, _updatedelegate);

                            while (!_updateresult.IsCompleted)
                            {
                                OnDataLoading(new EventArgs());
                                Thread.Sleep(1); Application.DoEvents(); 
                            }

                            _updatedelegate.EndInvoke(_updateresult);
                        }

                        try { Materia.SetPropertyValue(_button, "Enabled", _enabled); }
                        catch { }
                        Materia.RefreshAndManageCurrentProcess(); _saving = false;
                        AcceptUpdates(); OnAfterDataSave(_saveargs);

                        if (!String.IsNullOrEmpty(_saveargs.Error.RLTrim()) &&
                            !String.IsNullOrEmpty(_saveargs.ErrorNotification.RLTrim())) MessageBox.Show(_saveargs.ErrorNotification, "Record Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                        if (!_saveargs.Cancel)
                        {
                            AcceptAllChanges(); _haveupdates = false;

                            Form _form = null;

                            try { _form = (Form)ContainerControl; }
                            catch { _form = null; }

                            if (_form != null)
                            {
                                if (_form.Text.RLTrim().EndsWith("*")) _form.Text = _form.Text.Replace("*", "");
                            }
                        }
                    }
                }
            }


        }
示例#54
0
 public DbDataReader EndExecuteReader(IAsyncResult asyncResult)
 {
     return(funcExecuteReader.EndInvoke(asyncResult));
 }
		/// <summary>
		/// Starts the task, optionally in a background thread, and waits until the task completes.
		/// </summary>
		/// <remarks>
		/// If the task is started in a background thread, the task will be terminated in the
		/// calling thread terminates. Otherwise, the calling thread will not terminate until
		/// the task completes.
		/// </remarks>
		/// <param name="p_booRunInBackground">Whether the task should be run in a background thread.</param>
		/// <param name="p_objArgs">Arguments to pass to the task execution method.</param>
		/// <returns>The return value of the task.</returns>
		/// <seealso cref="StartWait(object[])"/>
		/// <seealso cref="Start(object[])"/>
		/// <seealso cref="Start(bool, object[])"/>
		protected object StartWait(bool p_booRunInBackground, params object[] p_objArgs)
		{
			//see Start() for discussion on BeginInvoke/EndInvoke versus
			// threads
			//
			//in this method, it appears we should be using BeginInvoke/EndInvoke,
			// unlike in the Start() method. this is because it makes the most
			// sense for an exception thrown during the execution of the task to
			// bubble up the the caller of this method, which EndInvoke allows.
			// this is important for things like transactions: letting the exception
			// bubble up allows the transaction to roll back when an unhandled
			// exception is thrown in the task's code
			// with threading, this doesn't happen - at least not unless we make it.
			Func<object, object> dlg = new Func<object, object>(RunThreadedWork);
			IAsyncResult ar = dlg.BeginInvoke(p_objArgs, null, p_objArgs);
			m_objReturnValue = dlg.EndInvoke(ar);
			ar.AsyncWaitHandle.Close();

			/*
			m_areTaskEnded.Reset();
			Start(p_booRunInBackground, p_objArgs);
			m_areTaskEnded.WaitOne();*/
			return m_objReturnValue;
		}
示例#56
0
 public int EndExecuteNonQuery(IAsyncResult asyncResult)
 {
     return(funcExecuteUpdate.EndInvoke(asyncResult));
 }