public static void Error(Exception exception)
 {
     if (exception != null)
     {
         ErrorAction?.Invoke(exception.ToString());
     }
 }
Esempio n. 2
0
        public override void Begin(Func <CancellationToken, Task> action = null, Action <Exception> onError = null)
        {
            ThrowIfDisposed();

            lock (Sync)
            {
                if (IsActive)
                {
                    return;
                }

                IsActive = true;

                Cts?.Dispose();

                Cts = new CancellationTokenSource();
            }

            if (action != null)
            {
                Action = action;
            }

            if (onError != null)
            {
                ErrorAction = onError;
            }

            Task = Task.Run(async() =>
            {
                while (!Cts.IsCancellationRequested)
                {
                    try { await Action(Cts.Token).ConfigureAwait(false); }
                    catch (OperationCanceledException) { /* ignored */ }
                    catch (Exception e)
                    {
                        if (!Cts.IsCancellationRequested)
                        {
                            try { ErrorAction?.Invoke(e); }
                            catch { /* ignored */ }

                            OnError(e);
                        }
                    }

                    try
                    {
                        if (!Cts.IsCancellationRequested)
                        {
                            await DelayAsync(Cts.Token).ConfigureAwait(false);
                        }
                    }
                    catch { /* ignored */ }
                }
            });
        }
Esempio n. 3
0
        private async void ExecuteSavePlace(object obj)
        {
            _place.LastEdit    = DateTimeOffset.Now;
            _place.Name        = Name;
            _place.Description = Description;
            _place.Rating      = short.Parse(Rating);
            _place.Type        = SelectedPlaceType;
            var result = await PlaceStore.UpdateItemAsync(_place);

            if (result == null)
            {
                ErrorAction?.Invoke($"Update Place '{_place.Name}' failed:");
                App.LogOutLn($"Update Place '{_place.Name}' failed.");
                UpdateReady?.Invoke(false);
            }
            else
            {
                UpdateReady?.Invoke(true);
            }
        }
Esempio n. 4
0
        public override void Begin()
        {
            ThrowIfDisposed();

            if (IsActive)
            {
                throw new InvalidOperationException($"{nameof(RetryTaskController)} - Task already running, use {nameof(CancelAsync)} to abort.");
            }

            IsActive = true;

            Cts = new CancellationTokenSource();

            Task = Task.Run(async() =>
            {
                while (!Cts.IsCancellationRequested)
                {
                    try { await Action(Cts.Token).ConfigureAwait(false); }
                    catch (OperationCanceledException) { }
                    catch (Exception e)
                    {
                        if (!Cts.IsCancellationRequested)
                        {
                            try
                            {
                                ErrorAction?.Invoke(e);
                                OnError(e);
                            }
                            catch { /* ignored */ }
                        }
                    }

                    if (!Cts.IsCancellationRequested)
                    {
                        await Task.Delay(RetryDelayMilliseconds, Cts.Token)
                        .ConfigureAwait(false);
                    }
                }
            });
        }
Esempio n. 5
0
        private async void Execute(object obj)
        {
            try
            {
                PasswordHelper.CreatePasswordHash(Password, out var hash, out var salt);
                var user = new User
                {
                    Id       = Guid.NewGuid(),
                    Email    = Email,
                    Hash     = hash,
                    Salt     = salt,
                    Created  = DateTimeOffset.Now,
                    LastEdit = DateTimeOffset.Now,
                    Name     = Username
                };

                var result = await UserStore.AddItemAsync(user);

                if (result == null)
                {
                    ErrorAction?.Invoke(Strings.ERROR_OCCURED_WHILE_CREATING_NEW_USER);
                    NewUserSucceeded?.Invoke(false);
                }
                else
                {
                    AppStore.Instance.User = user;
                    NewUserSucceeded?.Invoke(true);
                }
            }
            catch (Exception ex)
            {
                ErrorAction?.Invoke(Strings.ERROR_OCCURED_WHILE_CREATING_NEW_USER);
                App.LogOutLn(ex.Message, GetType().Name);
                NewUserSucceeded?.Invoke(false);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Publishes the app to the given folder
        /// </summary>
        /// <param name="targetPath">Folder to publsh the project too</param>
        /// <param name="behaviour">Preferred treatment of previous builds</param>
        /// <returns>The collection of results from the output handlers</returns>
        public List <HandlerResponse> PublishApp(string targetPath,
                                                 PublishBehaviour behaviour = PublishBehaviour.CleanFirst)
        {
            var results = InputHandlers.ProcessHandlers(
                new FilePath(ProjectFilePath).GetDirectory().MakeAbsolute(Environment).FullPath, s => Log(s));

            Log(
                $"Completed processing input handlers: {results.Count(r => r.Result == HandlerResult.OK)} OK, {results.Count(r => r.Result == HandlerResult.Error)} errors, {results.Count(r => r.Result == HandlerResult.NotRun)} not run");
            if (results.Any(r => r.Result == HandlerResult.Error))
            {
                throw new HandlerProcessingException(InputHandlers, results);
            }
            string outputPath;

            if (behaviour == PublishBehaviour.DoNotBuild)
            {
                outputPath  = Path.Combine(new FileInfo(ProjectFilePath).Directory.FullName, "bin", Configuration);
                BuildAction = null;
            }
            else
            {
                outputPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString("N"));
                if (!FileSystem.Exist((DirectoryPath)outputPath))
                {
                    FileSystem.GetDirectory(outputPath).Create();
                }
            }
            var props = new Dictionary <string, string>
            {
                { "Configuration", Configuration },
                { "Platform", Platform },
                { "OutputPath", outputPath },
                { "PublishDir", Path.Combine(outputPath, "app.publish") + "\\" }
            };

            BuildSettings = new MSBuildSettings
            {
                Configuration   = Configuration,
                MSBuildPlatform = GetMSBuildPlatform(Platform),
                Verbosity       = Verbosity.Quiet
            };
            BuildSettings.AddTargets(behaviour);
            BuildSettings.AddProperties(props, AdditionalProperties);
            BuildAction?.Invoke(this);
            var publishDir =
                new DirectoryPath(
                    new DirectoryInfo(props["OutputPath"]).GetDirectories()
                    .FirstOrDefault(d => d.Name == "app.publish")
                    .FullName);

            if (GenerateManifest)
            {
                PrepareManifestManager(publishDir, InformationSource.Both);
                ManifestManager.DeployManifest(ManifestManager.CreateAppManifest());
            }
            Log("Processing output handlers");
            var output = OutputHandlers.ProcessHandlers(publishDir.FullPath, s => Log(s));

            Log(
                $"Completed processing output handlers: {output.Count(r => r.Result == HandlerResult.OK)} OK, {output.Count(r => r.Result == HandlerResult.Error)} errors, {output.Count(r => r.Result == HandlerResult.NotRun)} not run");
            if (output.Any(o => o.Result == HandlerResult.Error) && ErrorAction != null)
            {
                Log("Error encountered while processing output handlers. Aborting!");
                ErrorAction?.Invoke(output);
                //throw new HandlerProcessingException(OutputHandlers, output); // in case something goes real wrong
            }
            if (string.IsNullOrWhiteSpace(targetPath))
            {
                return(output);
            }
            Log("Copying publish results to target directory");
            new DirectoryInfo(publishDir.MakeAbsolute(Environment).FullPath).Copy(destDirPath: targetPath,
                                                                                  copySubDirs: true);
            return(output);
        }
Esempio n. 7
0
 public void Error(string message)
 {
     ErrorAction?.Invoke(message);
 }
Esempio n. 8
0
        private Task <byte[]> DoHttpRequestTask()
        {
            byte[] resultBytes = null;
            TaskCompletionSource <byte[]> task = new TaskCompletionSource <byte[]>();
            AsyncCallback getResponseCallBack  = (ar) =>
            {
                try
                {
                    var             re       = (HttpWebRequest)ar.AsyncState;
                    HttpWebResponse response = (HttpWebResponse)re.EndGetResponse(ar);
                    //状态码200
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        resultBytes = GetByteArray(response);
                    }
                    else
                    {
                        //未获取到请求结果
                        Debug.WriteLine("can't get response data:" + Request.RequestUri.AbsolutePath);
                    }
                }
                catch (Exception e)
                {
                    ErrorAction?.Invoke(this);
                    Debug.WriteLine(Request.RequestUri.AbsolutePath + ":" + e.Message);
                }
                finally
                {
                    _stopTimer = true;//停止计时器
                    //设置TaskResult通知调用线程已获取到请求结果
                    task.SetResult(resultBytes);
                }
            };
            AsyncCallback getRequestCallBack = (ar) =>
            {
                try
                {
                    var re = (WebRequest)ar.AsyncState;

                    //TODO:设置request header
                    // Just here
                    //----------------------

                    //TODO:设置要发送的网络请求报文体
                    if (!string.IsNullOrEmpty(Body))
                    {
                        var bytes = Encoding.UTF8.GetBytes(Body);
                        using (var stream = Request.EndGetRequestStream(ar))
                        {
                            stream.Write(bytes, 0, bytes.Length);
                        }
                    }
                    //------------------------------

                    re.BeginGetResponse(getResponseCallBack, re);
                }
                catch (Exception e)
                {
                    _stopTimer = true;//停止计时器
                    ErrorAction?.Invoke(this);
                    Debug.WriteLine(Request.RequestUri.AbsolutePath + ":" + e.Message);
                    task.SetResult(null);
                }
            };

            if (Request.Method.ToUpper().Equals("POST"))
            {
                Request.BeginGetRequestStream(getRequestCallBack, Request);
            }
            else if (Request.Method.ToUpper().Equals("GET"))
            {
                Request.BeginGetResponse(getResponseCallBack, Request);
            }
            //if (IsEnableTimeOut)
            //    StartTimer();//启用超时计时器
            return(task.Task);
        }
Esempio n. 9
0
        private void DoWork()
        {
            double cpuUsage = 0;
            var    errMsg   = string.Empty;

            while (IsWorking)
            {
                //暂停
                if (IsWorkPause)
                {
                    Thread.Sleep(1);
                    continue;
                }

                //CPU使用率
                if (!_appInfo.GetCpuPerformance(ref cpuUsage, ref errMsg))
                {
                    ErrorAction?.Invoke(errMsg);
                    IsWorking = false;
                    continue;
                }

                //APP内存
                long memAppPrivate    = 0;
                long memAppWorkingSet = 0;
                if (!_appInfo.GetMemInfo(ref memAppPrivate, ref memAppWorkingSet, ref errMsg))
                {
                    ErrorAction?.Invoke(errMsg);
                    IsWorking = false;
                    continue;
                }

                //线程数
                var threadCount = 0;
                if (!_appInfo.GetThreadCount(ref threadCount, ref errMsg))
                {
                    ErrorAction?.Invoke(errMsg);
                    IsWorking = false;
                    continue;
                }

                var appPerformance = new AppPerformanceInfo()
                {
                    SystemMemoryInfo    = GetSysMemInfo(),
                    CpuUsage            = cpuUsage,
                    AppPrivateMemory    = memAppPrivate,
                    AppWorkingSetMemory = memAppWorkingSet,
                    ThreadCount         = threadCount
                };
                ShowInfoAction?.Invoke(appPerformance);

                //等待计时
                var interval = _config.TimerInterval * 1000;
                var count    = interval / 100;
                for (var i = 0; i < count; i++)
                {
                    if (!IsWorking)
                    {
                        return;
                    }

                    Thread.Sleep(100);
                }

                if (interval % 100 > 0)
                {
                    Thread.Sleep(interval % 100);
                }

                Thread.Sleep(1);
            }
        }
Esempio n. 10
0
 protected virtual void OnErrorAction() => ErrorAction?.Invoke(this, new System.EventArgs());