Ejemplo n.º 1
0
        private void OpenWeb(System.Threading.Tasks.Task task)
        {
            try
            {
                AppConfig config = new AppConfig();
                string    strIp  = config.AppConfigGet("VideoIP");
                strIp = "http://" + strIp;
                webBrowser1.Navigate(strIp);
                //while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
                //{
                //    //等待
                //    Thread.Sleep(100);

                //}
                Thread.Sleep(2000);
                webBrowser1.Document.GetElementById("username").InnerText = "admin";
                webBrowser1.Document.GetElementById("password").Focus();
                webBrowser1.Document.GetElementById("password").InnerText = "admin12345";
                webBrowser1.Document.GetElementById("username").Focus();
                //task.ContinueWith((a) => {

                //    //HtmlElementCollection htmlele = webBrowser1.Document.GetElementsByTagName("button");
                //    //htmlele[0].Focus();
                //});
                task.ContinueWith((a) => { Thread.Sleep(2000); spanClick("ng-binding", "label"); });

                task.ContinueWith((a) => { Thread.Sleep(3000); spanClick("icon-playall", "i"); });
            }
            catch (Exception ex)
            { }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 开启新线程
 /// </summary>
 /// <param name="time"></param>
 /// <param name="mytask"></param>
 /// <param name="finishstep"></param>
 public void NewTaskStart(Int64 time, tg_task mytask, string finishstep)
 {
     try
     {
         var token = new CancellationTokenSource();
         var task  = new System.Threading.Tasks.Task(() => SpinWait.SpinUntil(() =>
         {
             var taskinfo = Common.getInstance().GetWorkInfo(mytask.user_id);
             if (taskinfo.GuardSceneId == 0)
             {
                 token.Cancel();
                 return(true);
             }
             return(false);
         }, (int)time * 1000), token.Token);
         task.Start();
         task.ContinueWith(m =>
         {
             TaskUpdateAndSend(mytask, finishstep);
             token.Cancel();
         }, token.Token);
     }
     catch (Exception ex)
     {
         XTrace.WriteException(ex);
     }
 }
Ejemplo n.º 3
0
 protected void Continue(System.Threading.Tasks.Task task, Action action, Action canceled = null, Action <Exception> error = null)
 {
     task.ContinueWith(t =>
     {
         if (t.IsFaulted)
         {
             Act(() => {
                 if (error != null)
                 {
                     error(t.Exception);
                 }
                 else
                 {
                     throw t.Exception;
                 }
             });
         }
         else if (t.IsCanceled)
         {
             if (canceled != null)
             {
                 Act(canceled);
             }
         }
         else
         {
             Act(action);
         }
     }
                       );
 }
        internal static async System.Threading.Tasks.Task <T> MapResponse <T>(
            this System.Threading.Tasks.Task <IRestResponse <T> > task)
        {
            return(await task.ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    var result = t.Result;

                    if (result.IsSuccessful)
                    {
                        return result.Data;
                    }
                    else
                    {
                        var responseError = JsonConvert.DeserializeObject <ResponseError>(result.Content);
                        throw new TagSDKException(result.ErrorMessage, result.StatusCode, responseError);
                    }
                }
                else
                {
                    throw t.Exception;
                }
            }));
        }
Ejemplo n.º 5
0
 public static System.Threading.Tasks.Task <T> LogOnFaulted <T>(this System.Threading.Tasks.Task <T> self)
 {
     return(self.ContinueWith <T>(task =>
     {
         LoggerResolver.Current.Fail(self.Exception.InnerException);
         return default(T);
     }, System.Threading.Tasks.TaskContinuationOptions.OnlyOnFaulted));
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Список точек с расходом для программы 'Balans'
        /// </summary>
        private void BalanceExport()
        {
            if (HasData == false)
            {
                EmcosSiteWrapperApp.ShowWarning("Отсутствуют данные.");
                return;
            }
            Status        = State.Busy;
            DialogMessage = "Экспорт данных: Список точек с расходом для программы 'Balans'";

            var fileName = CreateNameForReport("ForBalance");
            var task     = new System.Threading.Tasks.Task(() =>
            {
                var be = new Export.ForBalanceExport(
                    new Export.ExportInfo
                {
                    Title       = "Данные для програмы Balance",
                    StartDate   = Session.Info.Period.StartDate,
                    EndDate     = Session.Info.Period.EndDate,
                    Substations = Substations
                });
                DispatcherExtensions.InUi(() =>
                {
                    if (be.Export(fileName) == false)
                    {
                        return;
                    }
                });
                System.Diagnostics.Process.Start(fileName);
            });

            task.ContinueWith((t) =>
            {
                Status = State.Ready;
            }, System.Threading.Tasks.TaskContinuationOptions.None);

            task.ContinueWith((s) =>
            {
                EmcosSiteWrapperApp.LogError("Экспорт для программы 'Balance' - ошибка");
                EmcosSiteWrapperApp.LogException(s.Exception);
                ShowDialogError("Произошла ошибка при формировании отчёта.\nОбратитесь к разработчику.");
            }, System.Threading.Tasks.TaskContinuationOptions.OnlyOnFaulted);

            task.Start(System.Threading.Tasks.TaskScheduler.Current);
        }
Ejemplo n.º 7
0
            protected override void Start()
            {
                try
                {
                    if (Status != StatusType.Queued)
                    {
                        throw new Exception("Stream has not been queued.");
                    }

                    base.Start();

                    _FileInfo = _DriveService.GetFile(FileId);

                    if (_FileInfo == null)
                    {
                        throw new Exception("File '" + FileId + "' no longer exists.");
                    }

                    Lock();

                    using (API.DriveService.Connection connection = API.DriveService.Connection.Create())
                    {
                        FilesResource.TrashRequest request = connection.Service.Files.Trash(FileId);

                        request.Fields = API.DriveService.RequestFields.FileFields;

                        _CancellationTokenSource = new System.Threading.CancellationTokenSource();

                        System.Threading.Tasks.Task <File> task = request.ExecuteAsync(_CancellationTokenSource.Token);

                        if (task.IsCompleted)
                        {
                            DriveService_ProgressChanged(task);
                        }
                        else
                        {
                            task.ContinueWith(thisTask => DriveService_ProgressChanged(thisTask));
                        }
                    }
                }
                catch (Exception exception)
                {
                    try
                    {
                        _Status           = StatusType.Failed;
                        _ExceptionMessage = exception.Message;

                        DriveService_ProgressChanged(StatusType.Failed, exception);
                    }
                    catch
                    {
                        Debugger.Break();
                    }

                    Log.Error(exception);
                }
            }
Ejemplo n.º 8
0
        // Add the following code from
        // http://www.windowsazure.com/en-us/develop/mobile/tutorials/single-sign-on-windows-8-dotnet/



        /// <summary>
        /// Set up Microsoft account (Live ID) authentication.
        /// </summary>
        /// <returns></returns>
        private async System.Threading.Tasks.Task Authenticate()
        {
            /*
             * // Enable this code if you want to use client-side authentication.
             * // You'll need Live SDK 5.2 or later.
             * // Remove the existing call to LoginAsync.
             *
             * LiveAuthClient liveIdClient = new LiveAuthClient("http://tictactoemobile1000.azure-mobile.net");
             *
             *
             * while (session == null)
             * {
             *  // Force a logout to make it easier to test with multiple Microsoft Accounts
             *  if (liveIdClient.CanLogout)
             *      liveIdClient.Logout();
             *
             *
             *  LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" });
             *  if (result.Status == LiveConnectSessionStatus.Connected)
             *  {
             *      session = result.Session;
             *      LiveConnectClient client = new LiveConnectClient(result.Session);
             *      LiveOperationResult meResult = await client.GetAsync("me");
             *      mobileServiceUser = await App.TicTacToeMobile1000Client
             *          .LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken);
             *
             *
             *      string title = string.Format("Welcome {0}!", meResult.Result["first_name"]);
             *      var dialog = new MessageDialog("You are now logged in.", title);
             *      dialog.Commands.Add(new UICommand("OK"));
             *      await dialog.ShowAsync();
             *  }
             *  else
             *  {
             *      session = null;
             *      var dialog = new MessageDialog("You must log in.", "Login Required");
             *      dialog.Commands.Add(new UICommand("OK"));
             *      await dialog.ShowAsync();
             *  }
             * }*/

            // If you want Single-Sign On, enable this version of the call.
            //mobileServiceUser = await App.mobileClient
            //            .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, true);

            System.Threading.Tasks.Task <MobileServiceUser> t1 = App.mobileClient
                                                                 .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
            await t1.ContinueWith(cont =>
            {
                mobileServiceUser             = t1.Result;
                System.Threading.Tasks.Task t = TicTacToeCSharp.TicTacToeMobile1000Push.UploadChannel(mobileServiceUser);
                t.Wait();
            });
        }
Ejemplo n.º 9
0
 protected override void OnStop()
 {
     startTask.ContinueWith(task =>
     {
         if (server != null)
         {
             server.Dispose();
         }
         return(task);
     }).Wait();
 }
Ejemplo n.º 10
0
 // Runs `action`. If called multiple times, actions are called in strict sequential order.
 // If a previously enqueued action has not started running, it will never be called.
 // (In other words, new actions render older ones obsolete.)
 public void EnqueueEvent(System.Action action)
 {
     LastCancellationTokenSource.Cancel();
     LastCancellationTokenSource.Dispose();
     LastTask = LastTask.ContinueWith(
         (System.Threading.Tasks.Task previousTask) => { action(); },
         (LastCancellationTokenSource = new System.Threading.CancellationTokenSource()).Token,
         System.Threading.Tasks.TaskContinuationOptions.LazyCancellation,
         System.Threading.Tasks.TaskScheduler.Current
         );
 }
Ejemplo n.º 11
0
        /// <summary>开启戒严线程</summary>
        private void NewArrestStart(decimal time, tg_task mytask, string finishstep)
        {
            try
            {
                var token = new CancellationTokenSource();
                var task  = new System.Threading.Tasks.Task(() => SpinWait.SpinUntil(() =>
                {
                    var taskinfo = Variable.TaskInfo.FirstOrDefault(q => q.userid == mytask.user_id);
                    if (taskinfo == null)
                    {
                        token.Cancel(); return(true);
                    }
                    switch (mytask.task_step_type)     //根据对应类型验证是否取消线程
                    {
                    case (int)TaskStepType.ARREST_RUMOR: if (taskinfo.ArrestRumorSceneId == 0)
                        {
                            token.Cancel(); return(true);
                        }
                        break;

                    case (int)TaskStepType.ARREST_FIRE: if (taskinfo.ArrestFireSceneId == 0)
                        {
                            token.Cancel(); return(true);
                        }
                        break;

                    case (int)TaskStepType.ARREST_BREAK: if (taskinfo.ArrestBreakSceneId == 0)
                        {
                            token.Cancel(); return(true);
                        }
                        break;

                    case (int)TaskStepType.ARREST_SEll_WINE: if (taskinfo.ArrestSellSceneId == 0)
                        {
                            token.Cancel(); return(true);
                        }
                        break;
                    }
                    return(false);
                }, (int)time * 1000), token.Token);
                task.Start();
                task.ContinueWith(m =>
                {
                    TaskUpdateAndSend(mytask, finishstep);
                    token.Cancel();
                }, token.Token);
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
        }
Ejemplo n.º 12
0
 /// <summary>Use on Tasks that are not awaited</summary>
 public static void FireAndForget(this System.Threading.Tasks.Task task)
 {
         #if DEBUG
     // Check if any exception occurred
     task.ContinueWith((_) =>
     {
         if (task.Exception != null)
         {
             CommonLibs.Utils.Debug.ASSERT(false, nameof(FireAndForget), $"An async task that was not awaited threw an exception ({task.Exception.GetType().FullName}): {task.Exception.Message}");
         }
     });
         #endif
 }
Ejemplo n.º 13
0
        public static string DownloadString(string url)
        {
            var request = WebRequest.Create(url);

            request.Method = "GET";

            System.Threading.Tasks.Task <WebResponse> task = System.Threading.Tasks.Task.Factory.FromAsync(
                request.BeginGetResponse,
                asyncResult => request.EndGetResponse(asyncResult),
                null);

            return(task.ContinueWith(t => ReadStreamFromResponse(t.Result)).Result);
        }
Ejemplo n.º 14
0
 public static System.Threading.Tasks.Task PostSaveHook(System.Threading.Tasks.Task saveTask, Game.GnomanEmpire self, bool fallenKingdom)
 {
     return(saveTask.ContinueWith((task) =>
     {
         foreach (var mod in active_mods)
         {
             mod.AfterGameSaved(modSaveFile.GetDataFor(mod));
         }
         var path = fallenKingdom ? Game.GnomanEmpire.SaveFolderPath("OldWorlds\\") : Game.GnomanEmpire.SaveFolderPath("Worlds\\");
         // Todo: fallen kingdoms not considered with filename and so on!
         var file = System.IO.Path.Combine(path, self.CurrentWorld + ".msv");
         modSaveFile.SaveTo(new System.IO.FileInfo(file));
     }));
 }
Ejemplo n.º 15
0
        public static System.Threading.Tasks.Task PostSaveGame(System.Threading.Tasks.Task saveTask, Game.GnomanEmpire self, bool fallenKingdom)
        {
            return(saveTask.ContinueWith(task =>
            {
                var saveFile = GetSaveLocation(fallenKingdom, self.CurrentWorld);
                using (FileStream saveStream = File.Create(saveFile))
                {
                    ModDataSaver modDataSaver = new ModDataSaver(saveStream, Instance.ModManager);
                    modDataSaver.Save();
                }

                Instance.ModManager.OnPostSaveGameEvent(new PostSaveGameEventArgs(fallenKingdom));
            }));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Executed a background work for the current view model.
        /// </summary>
        /// <param name="pStart">The entry point of the work to do.</param>
        /// <param name="pParams">The background work parameters.</param>
        public void DoBackgroundWork(ParameterizedBackgroundWorkStart pStart, object pParams)
        {
            // Indicating the tree view is busy.
            System.Threading.Tasks.Task lBusyTask = new System.Threading.Tasks.Task(() => this.IsBusy = true);

            // Excuting the background task.
            System.Threading.Tasks.Task lBackgroundTask = lBusyTask.ContinueWith((antecedent) => pStart(this, pParams));

            // The tree view is not busy anymore.
            lBackgroundTask.ContinueWith((pAntecedent) => this.IsBusy = false);

            // Launching the task.
            lBusyTask.Start();
        }
Ejemplo n.º 17
0
        protected override void OnStop()
        {
            var shutdownTask = startTask.ContinueWith(task =>
            {
                if (server != null)
                {
                    server.Dispose();
                }
                return(task);
            });
            var keepAliveTask = Task.Factory.StartNew(() =>
            {
                if (shutdownTask.Wait(9000))
                {
                    return;
                }
                do
                {
                    RequestAdditionalTime(10000);
                } while(!shutdownTask.Wait(9000));
            });

            Task.WaitAll(shutdownTask, keepAliveTask);
        }
Ejemplo n.º 18
0
        public string Get(string url)
        {
            var request = CreateRequest(url);

            request.Method          = WebRequestMethods.Http.Get;
            request.CookieContainer = this.Cookies;
            request.KeepAlive       = true;

            System.Threading.Tasks.Task <WebResponse> task = System.Threading.Tasks.Task.Factory.FromAsync(
                request.BeginGetResponse,
                asyncResult => request.EndGetResponse(asyncResult),
                null);

            return(task.ContinueWith(t => ReadStreamFromResponse(t.Result)).Result);
        }
Ejemplo n.º 19
0
        private static async System.Threading.Tasks.Task <int?> getVersionAsync(bool checkOnly = false)
        {
            var task = new System.Threading.Tasks.Task <int?>(getVersion);

            if (!checkOnly)
            {
                task.ContinueWith((antecedent) =>
                {
                    lock (defaultVersionLock)
                    {
                        defaultVersionAsync = antecedent.Result;
                    }
                });
            }
            task.Start();
            return(await task);
        }
Ejemplo n.º 20
0
 internal void Read(int size)
 {
     _Offset = 0;
     _Buffer = new byte[size];
     try
     {
         System.Threading.Tasks.Task <int> task = _Peer.Receive(_Buffer, _Offset, _Buffer.Length - _Offset);
         task.ContinueWith(t => _Readed(t.Result));
     }
     catch (SystemException e)
     {
         if (ErrorEvent != null)
         {
             ErrorEvent();
         }
     }
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Initializes new tasks and runs tasks scheduling it
        /// for execution to the current TaskScheduler.
        /// </summary>
        private void ManageTasks()
        {
            lock (tasks)
            {
                List <Task> tasksToStart = tasks.FindAll(t => t.TaskData.TaskState == TaskState.InQueue);
                if (tasksToStart.Count != 0)
                {
                    foreach (Task taskToStart in tasksToStart)
                    {
                        lock (taskToStart)
                        {
                            Task task = tasks.Single(t => t.TaskData.Id == taskToStart.TaskData.Id);
                            task.TaskData.TaskState = TaskState.InProgress;
                            var cancellationTokenSource = new CancellationTokenSource();
                            CancellationToken token     = cancellationTokenSource.Token;
                            task.CancellationTokenSource = cancellationTokenSource;
                            var systemTask = new SystemTask(() =>
                            {
                                using (cancellationTokenSource.Token.Register(Thread.CurrentThread.Abort))
                                {
                                    ExecuteTaskAction(task);
                                }
                            }, token);

                            SystemTask notificationTask = systemTask.ContinueWith((SystemTask t) =>
                            {
                                cancellationTokenSource.Dispose();

                                var data = new Dictionary <string, string>
                                {
                                    { "title", $"LibiadaWeb: Task completed" },
                                    { "body", $"Task type: { task.TaskData.TaskType.GetDisplayValue() } \nExecution time: { task.TaskData.ExecutionTime }" },
                                    { "icon", "/Content/DNA.png" },
                                    { "tag", $"/{ task.TaskData.TaskType }/Result/{ task.TaskData.Id }" }
                                };
                                PushNotificationHelper.Send(task.TaskData.UserId, data);
                            });

                            task.SystemTask = systemTask;
                            systemTask.Start();
                        }
                    }
                }
            }
        }
Ejemplo n.º 22
0
        private void _Readed(int read_count)
        {
            int readSize = read_count;

            _Offset += readSize;
            NetworkMonitor.Instance.Read.Set(readSize);
            if (_Offset == _Buffer.Length)
            {
                DoneEvent(_Buffer);
            }
            else
            {
                System.Threading.Tasks.Task <int> task = _Peer.Receive(
                    _Buffer,
                    _Offset,
                    _Buffer.Length - _Offset);
                task.ContinueWith(t => _Readed(t.Result));
            }
        }
        public static string DownloadString(string url)
        {
#if PORTABLE
            var request = WebRequest.Create(url);
            request.Method = "GET";

            System.Threading.Tasks.Task <WebResponse> task = System.Threading.Tasks.Task.Factory.FromAsync(
                request.BeginGetResponse,
                asyncResult => request.EndGetResponse(asyncResult),
                null);

            return(task.ContinueWith(t => ReadStreamFromResponse(t.Result)).Result);
#else
            using (var client = new WebClient())
            {
                client.Encoding = System.Text.Encoding.UTF8;
                return(client.DownloadString(url));
            }
#endif
        }
Ejemplo n.º 24
0
 protected void Continue <T>(System.Threading.Tasks.Task <T> task, Action <T> action, Action canceled = null, Action <Exception> error = null)
 {
     task.ContinueWith(t =>
     {
         if (t.IsFaulted)
         {
             Act(() => {
                 if (error != null)
                 {
                     error(t.Exception);
                 }
                 else
                 {
                     throw t.Exception;
                 }
             });
         }
         else if (t.IsCanceled)
         {
             if (canceled != null)
             {
                 Act(canceled);
             }
         }
         else
         {
             try
             {
                 var result = t.Result;
                 Act(() => action(result));
             }
             catch (Exception e)
             {
                 Act(() => { throw e; });
             }
         }
     }
                       );
 }
Ejemplo n.º 25
0
Archivo: Hub.cs Proyecto: radtek/BackO
        private void ClientSSLAccept(IAsyncResult ar)
        {
            StateObject so     = (StateObject)ar.AsyncState;
            Socket      client = so.workSocket;

            System.Threading.Tasks.Task sslT = System.Threading.Tasks.Task.Factory.StartNew(() => {
                NetworkStream clientStream = new NetworkStream(client);
                SslStream sslStream        = new SslStream(clientStream, false, ClientCertAuthenticate);
                Logger.Append("HUBRN", Severity.TRIVIA, "SSL Connection attempt from " + client.RemoteEndPoint.ToString() + " : beginning SSL authentication");
                try{
                    sslStream.AuthenticateAsServer(Certificate, true, SslProtocols.Default, false);
                }
                catch (AuthenticationException) {
                    Logger.Append("HUBRN", Severity.INFO, "Client node " + client.RemoteEndPoint.ToString() + " tried to connect without certificate");
                }
                Logger.Append("HUBRN", Severity.TRIVIA, "Connection attempt from " + client.RemoteEndPoint.ToString() + " : SSL authentication done.");
                Utils.DisplayCertificateInformation(sslStream.RemoteCertificate);


                PeerNode pn = AuthenticateNode(sslStream, client);
                if (pn == null)
                {
                    return;
                }

                PutNodeOnline(pn);
            });

            sslT.ContinueWith(t => {
                var aggException = t.Exception.Flatten();
                foreach (var e in aggException.InnerExceptions)
                {
                    Logger.Append("HUBRN", Severity.ERROR, "Unexpected error (" + e.Message + ") : " + e.ToString());
                }
            }, System.Threading.Tasks.TaskContinuationOptions.OnlyOnFaulted);
        }
Ejemplo n.º 26
0
        private void StartTask(Action act_task)
        {
            try
            {
                btncancel.Visibility = Visibility.Visible;
                c_cancel = new System.Threading.CancellationTokenSource();

                System.Threading.CancellationToken c_tok = c_cancel.Token;

                t_task = System.Threading.Tasks.Task.Factory.StartNew(obj =>
                {
                    act_task();

                }, c_tok, System.Threading.Tasks.TaskCreationOptions.PreferFairness);
                t_task.ContinueWith(new Action<System.Threading.Tasks.Task>((t) =>
                {
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        HideLoadingControls();
                    }), null);

                }));



            }
            catch (Exception ex)
            {
                ExceptionManager.Publish(ex);


            }
            //act_task();
            //HideLoadingControls();
        }
 /// <summary>Gets the strongly-typed property accessor used to get and set Razor Document Properties properties.</summary>
 internal System.Threading.Tasks.Task <RazorComponentWithTargetPath> GetRazorComponentWithTargetPathPropertiesAsync()
 {
     System.Threading.Tasks.Task <System.Collections.Immutable.IImmutableDictionary <string, Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog> > namedCatalogsTask = this.GetNamedCatalogsAsync();
     return(namedCatalogsTask.ContinueWith(CreateRazorComponentWithTargetPathPropertiesDelegate, this, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously, System.Threading.Tasks.TaskScheduler.Default));
 }
Ejemplo n.º 28
0
Archivo: NKDC.cs Proyecto: dioptre/nkd
 private static async System.Threading.Tasks.Task<int?> getVersionAsync(bool checkOnly = false)
 {
     var task = new System.Threading.Tasks.Task<int?>(getVersion);
     if (!checkOnly)
         task.ContinueWith((antecedent) =>
         {
             lock (defaultVersionLock)
             {
                 defaultVersionAsync = antecedent.Result;
             }
         });
     task.Start();
     return await task;
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Баланс подстанций
        /// </summary>
        private void ExportSubstationsBalance()
        {
            if (HasData == false)
            {
                EmcosSiteWrapperApp.ShowWarning("Отсутствуют данные.");
                return;
            }
            Status        = State.Busy;
            DialogMessage = "Экспорт данных: Баланс подстанций";

            var dialog = ShowDialogQuestion(
                String.Format("Скопировать файл отчёта в папку '{0}'?", Properties.Settings.Default.ReportBalancePSFolder),
                Title, TMPApplication.WpfDialogs.DialogMode.YesNo);
            var r = dialog.Result;

            var task = new System.Threading.Tasks.Task(() =>
            {
                var defaultFileName = CreateNameForReport("out");
                var sbe             = new Export.SubstationsBalanceExport(
                    new Export.ExportInfo
                {
                    Title       = "Отчёт по балансам подстанций",
                    StartDate   = Session.Info.Period.StartDate,
                    EndDate     = Session.Info.Period.EndDate,
                    Substations = Substations
                });
                DispatcherExtensions.InUi(() =>
                {
                    if (sbe.Export(defaultFileName) == false)
                    {
                        return;
                    }
                });

                if (r == TMPApplication.WpfDialogs.DialogResultState.Yes)
                {
                    if (System.IO.Directory.Exists(Properties.Settings.Default.ReportBalancePSFolder) == false)
                    {
                        try
                        {
                            System.IO.Directory.CreateDirectory(Properties.Settings.Default.ReportBalancePSFolder);
                        }
                        catch (System.IO.IOException ioe)
                        {
                            ShowDialogError(String.Format("Папка {0} не найдена. При попытке её создать произошла ошибка: {1}.\nФайл отчёта не скопирован.", Properties.Settings.Default.ReportBalancePSFolder, ioe.Message));
                        }
                    }
                    var filename = System.IO.Path.Combine(
                        Properties.Settings.Default.ReportBalancePSFolder,
                        String.Format(Properties.Settings.Default.ReportBalancePSFileNameTemplate, Session.Info.Period.StartDate) + ".xlsx");
                    System.IO.File.Copy(defaultFileName, filename, true);
                    System.Diagnostics.Process.Start(filename);
                }
                else
                {
                    System.Diagnostics.Process.Start(defaultFileName);
                }
            }, System.Threading.Tasks.TaskCreationOptions.AttachedToParent);

            task.ContinueWith((t) =>
            {
                Status = State.Ready;
            }, System.Threading.Tasks.TaskContinuationOptions.None);

            task.ContinueWith((s) =>
            {
                EmcosSiteWrapperApp.LogError("Экспорт балансов подстанций - ошибка");
                EmcosSiteWrapperApp.LogException(s.Exception);

                ShowDialogError("Произошла ошибка при формировании отчёта.\nОбратитесь к разработчику.");
            }, System.Threading.Tasks.TaskContinuationOptions.OnlyOnFaulted);
            task.Start(System.Threading.Tasks.TaskScheduler.Current);
        }
        private async void GetRecords()
        {
            //get the stored email of this user
            string email = prefs.GetString("email", "");

            //point the lambda call to the right location endpoint
            Amazon.RegionEndpoint region = Amazon.RegionEndpoint.USEast1;

            //credentials
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials(WebApp.AWSKey, WebApp.AWSSecret);

            TextView textHere = FindViewById <TextView>(Resource.Id.textView1);

            textHere.Text = "";
            try
            {
                //setup the lambda client with the credential and endpoint information
                Amazon.Lambda.AmazonLambdaClient client = new Amazon.Lambda.AmazonLambdaClient(awsCredentials, region);

                //payload has to be encapsulated in double quotes, thus the strange escape sequences here
                var invokeRequest = new Amazon.Lambda.Model.InvokeRequest {
                    FunctionName = "GetScanHistory", InvocationType = "RequestResponse", Payload = "\"" + email + "\""
                };

                //going to put this task on another thread so the UI doesn't lock up
                System.Threading.Tasks.Task <Amazon.Lambda.Model.InvokeResponse> responseTask = client.InvokeAsync(invokeRequest);

                await responseTask.ContinueWith((response) =>
                {
                    string statusText        = "";
                    string informationalText = "Internal error: Unhandled branch point"; // Should always be set in the next "if"

                    if (response.IsCanceled)
                    {
                        statusText = "Cancelled"; informationalText = "";
                    }
                    else if (response.IsFaulted)
                    {
                        statusText        = "Faulted";
                        informationalText = response.Exception.Message;
                        foreach (var exception in response.Exception.InnerExceptions)
                        {
                            informationalText += "\n" + exception.Message;
                        }
                    }
                    else if (response.IsCompleted)
                    {
                        statusText         = "Finished";
                        var responseReader = new System.IO.StreamReader(response.Result.Payload);
                        informationalText  = responseReader.ReadToEnd();
                    }

                    // This continuation is not run on the main UI thread, so need to set up
                    // another task perform the UI changes on the correct thread.
                    RunOnUiThread(() =>
                    {
                        Console.WriteLine(statusText);
                        Console.WriteLine(informationalText);

                        //now that we have the response we can deserialize it from Json to our object type
                        List <QRScan> scanList = JsonConvert.DeserializeObject <List <QRScan> >(informationalText);
                        foreach (QRScan scan in scanList)
                        {
                            textHere.Text += scan;
                            textHere.Text += "\n";
                        }
                    });
                });
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
        public async void WriteRecord(string fname, string nick, int age, string gender)
        {
            //point the lambda call to the right location endpoint
            Amazon.RegionEndpoint region = Amazon.RegionEndpoint.USEast1;

            //credentials
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials(Auth.AWSKey, Auth.AWSSecret);

            try
            {
                //setup the lambda client with the credential and endpoint information
                Amazon.Lambda.AmazonLambdaClient client = new Amazon.Lambda.AmazonLambdaClient(awsCredentials, region);

                JObject myUser = new JObject();
                myUser["id"]       = id;
                myUser["email"]    = email;
                myUser["name"]     = fname;
                myUser["nickname"] = nick;
                myUser["age"]      = age;
                myUser["gender"]   = Gender;

                //payload has to be encapsulated in double quotes, thus the strange escape sequences here
                var invokeRequest = new Amazon.Lambda.Model.InvokeRequest {
                    FunctionName = "WriteUserProfile", InvocationType = "RequestResponse", PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(myUser.ToString()),
                };

                //going to put this task on another thread so the UI doesn't lock up
                System.Threading.Tasks.Task <Amazon.Lambda.Model.InvokeResponse> responseTask = client.InvokeAsync(invokeRequest);

                await responseTask.ContinueWith((response) =>
                {
                    string statusText        = "";
                    string informationalText = "Internal error: Unhandled branch point"; // Should always be set in the next "if"

                    if (response.IsCanceled)
                    {
                        statusText = "Cancelled"; informationalText = "";
                    }
                    else if (response.IsFaulted)
                    {
                        statusText        = "Faulted";
                        informationalText = response.Exception.Message;
                        foreach (var exception in response.Exception.InnerExceptions)
                        {
                            informationalText += "\n" + exception.Message;
                        }
                    }
                    else if (response.IsCompleted)
                    {
                        statusText         = "Finished";
                        var responseReader = new System.IO.StreamReader(response.Result.Payload);
                        informationalText  = responseReader.ReadToEnd();

                        //take the user over to the legal disclaimer step
                        var activity = new Intent(this, typeof(LegalDisclaimerActivity));
                        StartActivity(activity);
                    }

                    // This continuation is not run on the main UI thread, so need to set up
                    // another task perform the UI changes on the correct thread.
                    RunOnUiThread(() =>
                    {
                        Console.WriteLine(statusText);
                        Console.WriteLine(informationalText);
                    });
                });
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
Ejemplo n.º 32
0
        // This process watches (via change stream) for commands inserted to a commands collection
        // When the command is considered valid it is forwarded to the RTU
        static async void ProcessMongoCmd(JSONSCADAConfig jsConfig)
        {
            do
            {
                try
                {
                    var Client     = ConnectMongoClient(jsConfig);
                    var DB         = Client.GetDatabase(jsConfig.mongoDatabaseName);
                    var collection =
                        DB
                        .GetCollection
                        <rtCommand>(CommandsQueueCollectionName);

                    bool isMongoLive =
                        DB
                        .RunCommandAsync((Command <BsonDocument>) "{ping:1}")
                        .Wait(1000);
                    if (!isMongoLive)
                    {
                        throw new Exception("Error on connection " + jsConfig.mongoConnectionString);
                    }

                    Log("MongoDB CMD CS - Start listening for commands via changestream...");
                    var filter = "{ operationType: 'insert' }";

                    var pipeline =
                        new EmptyPipelineDefinition <ChangeStreamDocument <rtCommand
                                                                           >
                                                     >().Match(filter);
                    using (var cursor = await collection.WatchAsync(pipeline))
                    {
                        await cursor
                        .ForEachAsync(async change =>
                        {
                            if (!Active)
                            {
                                return;
                            }

                            // process change event, only process inserts
                            if (
                                change.OperationType ==
                                ChangeStreamOperationType.Insert
                                )
                            {
                                // consider only commands for this driver
                                {
                                    Log("MongoDB CMD CS - Looking for connection " +
                                        change
                                        .FullDocument
                                        .protocolSourceConnectionNumber +
                                        "...");
                                    var found = false;
                                    foreach (DNP3_connection
                                             srv
                                             in
                                             DNP3conns
                                             )
                                    {
                                        if (
                                            srv.protocolConnectionNumber ==
                                            change
                                            .FullDocument
                                            .protocolSourceConnectionNumber
                                            )
                                        {
                                            found  = true;
                                            var cs = srv.channel.GetChannelStatistics();
                                            if (
                                                srv.isConnected &&
                                                srv.commandsEnabled
                                                )
                                            {
                                                var group     = change.FullDocument.protocolSourceCommonAddress;
                                                var variation = change.FullDocument.protocolSourceASDU;
                                                if (group == 41 || group == 12)
                                                {
                                                    if (         // check for command expired
                                                        DateTime
                                                        .Now
                                                        .ToLocalTime()
                                                        .Subtract(change
                                                                  .FullDocument
                                                                  .timeTag
                                                                  .ToLocalTime(
                                                                      ))
                                                        .Seconds <
                                                        10
                                                        )
                                                    {         // can execute
                                                        System.Threading.Tasks.Task <CommandTaskResult> cmdTask = null;

                                                        if (group == 12)
                                                        {
                                                            OperationType ot = OperationType.NUL;

                                                            TripCloseCode tc = TripCloseCode.NUL;
                                                            switch (System.Convert.ToUInt16(change.FullDocument.protocolSourceCommandDuration))
                                                            {
                                                            default:
                                                            case 0:
                                                                ot = OperationType.NUL;
                                                                break;

                                                            case 1:
                                                                if (change.FullDocument.value != 0)
                                                                {
                                                                    ot = OperationType.PULSE_ON;
                                                                }
                                                                else
                                                                {
                                                                    ot = OperationType.PULSE_OFF;
                                                                }
                                                                break;

                                                            case 2:
                                                                if (change.FullDocument.value != 0)
                                                                {
                                                                    ot = OperationType.PULSE_OFF;
                                                                }
                                                                else
                                                                {
                                                                    ot = OperationType.PULSE_ON;
                                                                }
                                                                break;

                                                            case 3:
                                                                if (change.FullDocument.value != 0)
                                                                {
                                                                    ot = OperationType.LATCH_ON;
                                                                }
                                                                else
                                                                {
                                                                    ot = OperationType.LATCH_OFF;
                                                                }
                                                                break;

                                                            case 4:
                                                                if (change.FullDocument.value != 0)
                                                                {
                                                                    ot = OperationType.LATCH_OFF;
                                                                }
                                                                else
                                                                {
                                                                    ot = OperationType.LATCH_ON;
                                                                }
                                                                break;

                                                            case 11:
                                                                if (change.FullDocument.value != 0)
                                                                {
                                                                    ot = OperationType.PULSE_ON;
                                                                    tc = TripCloseCode.CLOSE;
                                                                }
                                                                else
                                                                {
                                                                    ot = OperationType.PULSE_OFF;
                                                                    tc = TripCloseCode.TRIP;
                                                                }
                                                                break;

                                                            case 13:
                                                                if (change.FullDocument.value != 0)
                                                                {
                                                                    ot = OperationType.LATCH_ON;
                                                                    tc = TripCloseCode.CLOSE;
                                                                }
                                                                else
                                                                {
                                                                    ot = OperationType.LATCH_OFF;
                                                                    tc = TripCloseCode.TRIP;
                                                                }
                                                                break;

                                                            case 21:
                                                                if (change.FullDocument.value != 0)
                                                                {
                                                                    ot = OperationType.PULSE_ON;
                                                                    tc = TripCloseCode.TRIP;
                                                                }
                                                                else
                                                                {
                                                                    ot = OperationType.PULSE_OFF;
                                                                    tc = TripCloseCode.CLOSE;
                                                                }
                                                                break;

                                                            case 23:
                                                                if (change.FullDocument.value != 0)
                                                                {
                                                                    ot = OperationType.LATCH_ON;
                                                                    tc = TripCloseCode.TRIP;
                                                                }
                                                                else
                                                                {
                                                                    ot = OperationType.LATCH_OFF;
                                                                    tc = TripCloseCode.CLOSE;
                                                                }
                                                                break;
                                                            }
                                                            ControlRelayOutputBlock crob = new ControlRelayOutputBlock(ot, tc, false, 1, 0, 0);
                                                            if (System.Convert.ToBoolean(change.FullDocument.protocolSourceCommandUseSBO))
                                                            {
                                                                cmdTask = srv.master.SelectAndOperate(
                                                                    crob,
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                            else
                                                            {
                                                                cmdTask = srv.master.DirectOperate(
                                                                    crob,
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                        }
                                                        else if (group == 41 && variation == 1)
                                                        {
                                                            if (System.Convert.ToBoolean(change.FullDocument.protocolSourceCommandUseSBO))
                                                            {
                                                                cmdTask = srv.master.SelectAndOperate(
                                                                    new AnalogOutputInt32(System.Convert.ToInt32(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                            else
                                                            {
                                                                cmdTask = srv.master.DirectOperate(
                                                                    new AnalogOutputInt32(System.Convert.ToInt32(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                        }
                                                        else if (group == 41 && variation == 2)
                                                        {
                                                            if (System.Convert.ToBoolean(change.FullDocument.protocolSourceCommandUseSBO))
                                                            {
                                                                cmdTask = srv.master.SelectAndOperate(
                                                                    new AnalogOutputInt16(System.Convert.ToInt16(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                            else
                                                            {
                                                                cmdTask = srv.master.DirectOperate(
                                                                    new AnalogOutputInt16(System.Convert.ToInt16(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                        }
                                                        else if (group == 41 && variation == 3)
                                                        {
                                                            if (System.Convert.ToBoolean(change.FullDocument.protocolSourceCommandUseSBO))
                                                            {
                                                                cmdTask = srv.master.SelectAndOperate(
                                                                    new AnalogOutputFloat32(System.Convert.ToSingle(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                            else
                                                            {
                                                                cmdTask = srv.master.DirectOperate(
                                                                    new AnalogOutputFloat32(System.Convert.ToSingle(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                        }
                                                        else if (group == 41 && variation == 4)
                                                        {
                                                            if (System.Convert.ToBoolean(change.FullDocument.protocolSourceCommandUseSBO))
                                                            {
                                                                cmdTask = srv.master.SelectAndOperate(
                                                                    new AnalogOutputDouble64(System.Convert.ToDouble(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                            else
                                                            {
                                                                cmdTask = srv.master.DirectOperate(
                                                                    new AnalogOutputDouble64(System.Convert.ToDouble(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                        }
                                                        else if (group == 41)     // group 41, other variations defaults to float32
                                                        {
                                                            if (System.Convert.ToBoolean(change.FullDocument.protocolSourceCommandUseSBO))
                                                            {
                                                                cmdTask = srv.master.SelectAndOperate(
                                                                    new AnalogOutputFloat32(System.Convert.ToSingle(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                            else
                                                            {
                                                                cmdTask = srv.master.DirectOperate(
                                                                    new AnalogOutputFloat32(System.Convert.ToSingle(change.FullDocument.value)),
                                                                    System.Convert.ToUInt16(change.FullDocument.protocolSourceObjectAddress),
                                                                    TaskConfig.Default);
                                                            }
                                                        }

                                                        if (cmdTask != null)
                                                        {
                                                            _ = cmdTask.ContinueWith((result) =>
                                                            {
                                                                Console.WriteLine("Result: " + result.Result);
                                                                Log("MongoDB CMD CS - " +
                                                                    srv.name +
                                                                    " - Command " +
                                                                    " TAG:" + change.FullDocument.tag +
                                                                    " GRP:" + change.FullDocument.protocolSourceCommonAddress +
                                                                    " VAR:" + change.FullDocument.protocolSourceASDU +
                                                                    " OBJ:" + change.FullDocument.protocolSourceObjectAddress +
                                                                    " Value:" + change.FullDocument.value +
                                                                    " Delivered");

                                                                // update as delivered
                                                                var filter =
                                                                    new BsonDocument(new BsonDocument("_id",
                                                                                                      change.FullDocument.id));
                                                                var update =
                                                                    new BsonDocument("$set", new BsonDocument {
                                                                    { "delivered", true },
                                                                    { "ack",
                                                                      result.Result.Results.FirstOrDefault().PointState == CommandPointState.SUCCESS &&
                                                                      result.Result.Results.FirstOrDefault().Status == CommandStatus.SUCCESS },
                                                                    { "ackTimeTag", BsonValue.Create(DateTime.Now) },
                                                                    { "resultDescription", result.Result.ToString() }
                                                                });
                                                                var res =
                                                                    collection
                                                                    .UpdateOneAsync(filter,
                                                                                    update);
                                                            });
                                                        }
                                                        else
                                                        {
                                                            Console.WriteLine("Command Error");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        // update as expired
                                                        Log("MongoDB CMD CS - " +
                                                            srv.name +
                                                            " - Command " +
                                                            " TAG:" + change.FullDocument.tag +
                                                            " GRP:" + change.FullDocument.protocolSourceCommonAddress +
                                                            " VAR:" + change.FullDocument.protocolSourceASDU +
                                                            " OBJ:" + change.FullDocument.protocolSourceObjectAddress +
                                                            " Value:" + change.FullDocument.value +
                                                            " Expired");
                                                        var filter =
                                                            new BsonDocument(new BsonDocument("_id",
                                                                                              change
                                                                                              .FullDocument
                                                                                              .id));
                                                        var update =
                                                            new BsonDocument("$set",
                                                                             new BsonDocument("cancelReason",
                                                                                              "expired"));
                                                        var result =
                                                            await collection
                                                            .UpdateOneAsync(filter,
                                                                            update);
                                                    }
                                                }
                                                else
                                                {
                                                    // update as canceled (asdu not implemented)
                                                    Log("MongoDB CMD CS - " +
                                                        srv.name +
                                                        " - Command " +
                                                        " TAG:" + change.FullDocument.tag +
                                                        " GRP:" + change.FullDocument.protocolSourceCommonAddress +
                                                        " VAR:" + change.FullDocument.protocolSourceASDU +
                                                        " OBJ:" + change.FullDocument.protocolSourceObjectAddress +
                                                        " Value:" + change.FullDocument.value +
                                                        " ASDU Not Implemented");
                                                    var filter =
                                                        new BsonDocument(new BsonDocument("_id",
                                                                                          change
                                                                                          .FullDocument
                                                                                          .id));
                                                    var update =
                                                        new BsonDocument("$set",
                                                                         new BsonDocument("cancelReason",
                                                                                          "asdu not implemented"));
                                                    var result =
                                                        await collection
                                                        .UpdateOneAsync(filter,
                                                                        update);
                                                }
                                            }
                                            else
                                            {
                                                // update as canceled (not connected)
                                                Log("MongoDB CMD CS - " +
                                                    srv.name +
                                                    " - Command " +
                                                    " TAG:" + change.FullDocument.tag +
                                                    " GRP:" + change.FullDocument.protocolSourceCommonAddress +
                                                    " VAR:" + change.FullDocument.protocolSourceASDU +
                                                    " OBJ:" + change.FullDocument.protocolSourceObjectAddress +
                                                    " Value:" + change.FullDocument.value +
                                                    change.FullDocument.value +
                                                    (
                                                        srv.commandsEnabled
                                                            ? " Not Connected"
                                                            : " Commands Disabled"
                                                    ));
                                                var filter =
                                                    new BsonDocument(new BsonDocument("_id",
                                                                                      change
                                                                                      .FullDocument
                                                                                      .id));
                                                var update =
                                                    new BsonDocument("$set",
                                                                     new BsonDocument("cancelReason",
                                                                                      (
                                                                                          srv
                                                                                          .commandsEnabled
                                                                        ? "not connected"
                                                                        : "commands disabled"
                                                                                      )));
                                                var result =
                                                    await collection
                                                    .UpdateOneAsync(filter,
                                                                    update);
                                            }
                                            break;
                                        }
                                    }
                                    if (!found)
                                    {
                                        // update as canceled command (not found)
                                        Log("MongoDB CMD CS - " +
                                            change
                                            .FullDocument
                                            .protocolSourceConnectionNumber
                                            .ToString() +
                                            " - Command " +
                                            " TAG:" + change.FullDocument.tag +
                                            " GRP:" + change.FullDocument.protocolSourceCommonAddress +
                                            " VAR:" + change.FullDocument.protocolSourceASDU +
                                            " OBJ:" + change.FullDocument.protocolSourceObjectAddress +
                                            " Value:" + change.FullDocument.value +
                                            " Not Found");
                                        var filter =
                                            new BsonDocument(new BsonDocument("_id",
                                                                              change
                                                                              .FullDocument
                                                                              .id));
                                        var update =
                                            new BsonDocument("$set",
                                                             new BsonDocument("cancelReason",
                                                                              "connection not found"));
                                        var result =
                                            await collection
                                            .UpdateOneAsync(filter,
                                                            update);
                                    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    Log("Exception MongoCmd");
                    Log(e);
                    Log(e
                        .ToString()
                        .Substring(0,
                                   e.ToString().IndexOf(Environment.NewLine)));
                    System.Threading.Thread.Sleep(3000);
                }
            }while (true);
        }