Beispiel #1
0
        public void TestMutiThreadInclude()
        {
            var task1 = new System.Threading.Tasks.Task(() =>
            {
                System.Threading.Thread.Sleep(10000);
                using (var uow = new UnitOfWork(new TContext()))
                {
                    var resp  = uow.Repositories <Student>();
                    var list1 = resp.Include(x => x.Teacher).All();
                }
            });

            var task2 = new System.Threading.Tasks.Task(() =>
            {
                using (var uow = new UnitOfWork(new TContext()))
                {
                    var resp = uow.Repositories <Student>();
                    resp.Include(x => x.Teacher);


                    System.Threading.Thread.Sleep(100000);
                    resp.All();
                }
            });

            task1.Start();
            task2.Start();
            System.Threading.Tasks.Task.WaitAll(task1, task2);
        }
        private void FindDuplicateIndexes(object sender, EventArgs e)
        {
            try
            {
                CallWrapper();
                var task = new System.Threading.Tasks.Task(() =>
                {
                    OutputPane.WriteMessageAndActivatePane("Finding Duplicate Indexes...");
                    var finder = new DuplicateIndexFinder();
                    finder.ShowDuplicateIndexes();
                    OutputPane.WriteMessageAndActivatePane("Finding Duplicate Indexes...done");
                });

                task.Start();

                if (task.Exception != null)
                {
                    throw task.Exception;
                }
            }
            catch (Exception ex)
            {
                OutputPane.WriteMessage("Error finding duplicate indexes: {0}", ex.Message);
            }
        }
Beispiel #3
0
        internal bool RunAsAdministrator(System.Threading.Tasks.Task <bool> taskToDo)
        {
            try {
                /// If logon fails
                if (!LogonUser(Username, DomainName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out SafeTokenHandleStruct safeTokenHandle))
                {
                    Utils.Tracer.Log($"Could not logon as {Username}@{DomainName} ; error code : {Marshal.GetLastWin32Error()}", Utils.MessageVerbosity.Error);
                    return(false);
                }

                /// we're connected
                using (safeTokenHandle) {
                    Utils.Tracer.Log($"Logged in with Windows NT token \"{safeTokenHandle}\" : {Username}@{DomainName}");

                    /// Use the token handle returned by LogonUser
                    using (System.Security.Principal.WindowsImpersonationContext ctx = System.Security.Principal.WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle())) {
                        /// using context will let us act as the new user
                        using (taskToDo) {
                            taskToDo.Start();
                            return(taskToDo.Result);
                        }
                        /// on Dispose/Close, we switch back to previous user
                    }
                }
            }
            catch (Exception ex) {
                Utils.Tracer.Log("Error trying to run as administrator", ex);
                return(false);
            }
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            PubnubAPI pubnub = new PubnubAPI(
                "pub-c-2902e1f0-71b1-44ff-a438-11d120ed8bcf",               // PUBLISH_KEY
                "sub-c-92dac9b8-0747-11e3-9163-02ee2ddab7fe",               // SUBSCRIBE_KEY
                "sec-c-M2RjZmI0OTUtOGU1MC00Mzg1LThjMTQtYjQ4ZmU1YWQ4NzU5",   // SECRET_KEY
                true                                                        // SSL_ON?
            );

            Console.WriteLine("Enter chanel name: ");
            string chanel = Console.ReadLine();

            Console.WriteLine("Enter message: ");
            string msg = Console.ReadLine();
            pubnub.Publish(chanel, msg);

            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                 () =>
                 pubnub.Subscribe(
                     "chat",
                     delegate(object message)
                     {
                         Console.WriteLine("Received Message -> '" + message + "'");
                         return true;
                     }
                 )
             );

            t.Start();
        }
Beispiel #5
0
        public void RunBackground(Action action)
        {
            CurrentBackground = new BackgroundWindow();
            var t = new System.Threading.Tasks.Task(new Action(() => {
                try
                {
                    action();
                    CurrentBackground.Closing -= CurrentBackground.OnClosing;
                    Dispatcher.Invoke(CurrentBackground.Close);
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() => {
                        var ew = new ErrorWindow();
                        var tr = new Thread(new ParameterizedThreadStart(ew.ShowError))
                        {
                            CurrentUICulture = new System.Globalization.CultureInfo("en-US")
                        };
                        tr.Start(ex);
                        if (ew.ShowDialog() != true)
                        {
                            CurrentBackground.Closing -= CurrentBackground.OnClosing;
                            Dispatcher.Invoke(() => {
                                CurrentBackground.Close();
                                Close();
                            });
                        }
                    });
                }
            }));

            t.Start();
            CurrentBackground.ShowDialog();
        }
Beispiel #6
0
        private void GetUserInfoList(UserApi userApi, List <string> opendIds,
                                     List <UserBatchGetApiResult.UserInfo> userInfoList, int count, List <string> successList)
        {
            var taskList = new List <System.Threading.Tasks.Task>();

            for (var i = 0; i < count; i++)
            {
                lock (opendIds)
                {
                    var takeCount    = opendIds.Count > 100 ? 100 : opendIds.Count;
                    var openIdsToGet = opendIds.Skip(i * 100).Take(takeCount).ToArray();
                    if (openIdsToGet.Count() > 0)
                    {
                        var task = new System.Threading.Tasks.Task(() =>
                        {
                            var debugStr = "";
                            //该接口最多支持获取100个粉丝的信息
                            try
                            {
                                debugStr = "准备获取以下粉丝信息:" + string.Join(",", openIdsToGet) + "。" + Environment.NewLine;

                                var batchResult = userApi.Get(openIdsToGet);
                                if (batchResult.IsSuccess())
                                {
                                    debugStr += "已成功获取粉丝信息。";
                                    lock (userInfoList)
                                    {
                                        userInfoList.AddRange(batchResult.UserInfoList);
                                    }
                                    lock (successList)
                                    {
                                        successList.AddRange(openIdsToGet);
                                    }
                                }
                                else
                                {
                                    debugStr += "粉丝信息获取失败:" + batchResult.DetailResult + "。";
                                }
                            }
                            catch (Exception ex)
                            {
                                debugStr += "粉丝信息获取异常:" + ex + "。";
                            }
                            finally
                            {
                                Logger.Log(LoggerLevels.Debug, debugStr);
                            }
                        });
                        task.Start();
                        taskList.Add(task);
                    }
                }
            }
            if (taskList.Count > 0)
            {
                System.Threading.Tasks.Task.WaitAll(taskList.ToArray());
            }
            Logger.Log(LoggerLevels.Debug, "已处理完" + taskList.Count + "个任务。");
            taskList.Clear();
        }
Beispiel #7
0
 public void StartBackgroundWorkers()
 {
     //This works in .NET Standard:
     //System.Threading.Tasks.Task.Run(this.readAction);
     System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(this.readAction);
     task.Start();
 }
Beispiel #8
0
 public void StartCommandLoop(SocksController loopController)
 {
     _cancelTokenSource = new CancellationTokenSource();
     _cancelToken = _cancelTokenSource.Token;
     _commandChannelLoop = new System.Threading.Tasks.Task((g) => {
         try
         {
             ImplantComms.LogMessage($"Command loop starting - beacon time is {C2Config.CommandBeaconTime}ms");
             if (!CommandLoop((CancellationToken)g))
             {
                 loopController.StopProxyComms();
                 _error.LogError($"Stopping all proxy comms as command channel is now broken");
                 return;
             }
         }
         catch (Exception ex)
         {
             var lst = new List<String>
             {
                 "Error in command channel loop"
             };
             _error.LogError($"Command Channel loop is broken {ex.Message}, hard stopping all connections");
             loopController.StopProxyComms();
             return;
         }
     }, _cancelToken);
     _commandChannelLoop.Start();
 }
        static public void Main()
        {
            Pubnub pubnub = new Pubnub(
                                       publishKey: "pub-c-d8635a25-b556-4267-84c4-a9db379cd66a",
                                       subscribeKey: "sub-c-e809ad42-8bd8-11e5-bf00-02ee2ddab7fe");

            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () =>
                pubnub.Subscribe<string>(
                channel: channel,
                userCallback: DisplaySubscribeReturnMessage,
                connectCallback: DisplaySubscribeConnectStatusMessage,
                errorCallback: DisplayErrorMessage)
            );
            t.Start();

            while (true)
            {
                Console.Write("Enter a message to be sent to Pubnub: ");
                string msg = Console.ReadLine();
                pubnub.Publish<string>(
                    channel: channel,
                    message: msg,
                    userCallback: DisplayReturnMessage,
                    errorCallback: DisplayErrorMessage);
                Console.WriteLine("Message {0} sent.", msg);
            }
        }
Beispiel #10
0
        public void Launch()
        {
            m_Socket.Bind(Port: 0);
            m_Enable = true;

            _Procresser.Start();
        }
        /// <summary>
        /// Load the list of the popup
        /// </summary>
        private void LoadItems()
        {
            ComboBoxMode = WindowMode.Loading;
            NotifyPropertyChanged("ComboBoxMode");

            var possibleItems = ((FieldViewModel)EditorLabelName.DataContext).getRelatedEntities(_filter);

            System.Threading.Tasks.Task taskRetrieveData = new System.Threading.Tasks.Task(async() =>
            {
                List <BaseEntityWrapper> results = await possibleItems;
                this.Dispatcher.Invoke(() =>
                {
                    listView.Items.Clear();
                    if (results != null)
                    {
                        results.ForEach(item => listView.Items.Add(item));
                    }
                    listView.Items.Refresh();

                    ComboBoxMode = WindowMode.Loaded;
                    NotifyPropertyChanged("ComboBoxMode");
                });
            });
            taskRetrieveData.Start();
        }
 public void Start()//启动
 {
     System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(() =>
     {
         while (true)
         {
             if (ListQueue.Count > 0)
             {
                 try
                 {
                     ScanQueue();
                 }
                 catch (Exception ex)
                 {
                     ex.Message.Log();
                 }
             }
             else
             {
                 Thread.Sleep(3000);
                 "当前任务全部解析已完成".Log(true);
             }
         }
     });
     task.Start();
 }
Beispiel #13
0
        private void checkin_simpleButton_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("确认为勾选的学生签到吗", "消息",
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            List <StudentInfo> checkin = new List <StudentInfo>();

            for (int i = 0; i < gridView2.RowCount; i++)
            {
                StudentInfo stu = gridView2.GetRow(i) as StudentInfo;
                if (stu.Checkin)
                {
                    checkin.Add(stu);
                }
            }

            foreach (var v in checkin)
            {
                v.Remaining -= 1;
                int result = StudentInfo.Updata(v);
            }
            CheckGroupMembers();
            XtraMessageBox.Show("签到完成", "消息", MessageBoxButtons.OK);

            //异步插入签到记录
            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(new Action(() => {
                checkin.ForEach(p => CheckinRecordInfo.AddRecord(p));
            }));
            t.Start();
        }
Beispiel #14
0
        static public void Main()
        {
            Pubnub pubnub = new Pubnub(
                publishKey: "pub-c-d8635a25-b556-4267-84c4-a9db379cd66a",
                subscribeKey: "sub-c-e809ad42-8bd8-11e5-bf00-02ee2ddab7fe");

            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () =>
                pubnub.Subscribe <string>(
                    channel: channel,
                    userCallback: DisplaySubscribeReturnMessage,
                    connectCallback: DisplaySubscribeConnectStatusMessage,
                    errorCallback: DisplayErrorMessage)
                );
            t.Start();

            while (true)
            {
                Console.Write("Enter a message to be sent to Pubnub: ");
                string msg = Console.ReadLine();
                pubnub.Publish <string>(
                    channel: channel,
                    message: msg,
                    userCallback: DisplayReturnMessage,
                    errorCallback: DisplayErrorMessage);
                Console.WriteLine("Message {0} sent.", msg);
            }
        }
Beispiel #15
0
        private void LoadingNameSpace()
        {
            if (task == null)
            {
                task = new System.Threading.Tasks.Task(() =>
                {
                    foreach (var line in txtCache.Get(_buffer.CurrentSnapshot).Lines)
                    {
                        string txt = line.Text;

                        if (txt.IndexOf("import") >= 0)
                        {
                            var rx = Regex.Matches(txt, "(?<=import[ ,\t]).+");

                            foreach (Match item in rx)
                            {
                                if (item.Success)
                                {
                                    string val = item.Value.Trim(' ', '\t', '"');
                                    LoadingNameSpace(val);
                                }
                            }
                        }
                    }

                    task = null;
                });

                task.Start();
            }
        }
Beispiel #16
0
        public void Start(IStreamable peer)
        {
            _Stop = false;
            _Peer = peer;

            _Task.Start();
        }
Beispiel #17
0
        // create a task for loading the next image
        System.Threading.Tasks.Task LoadNextImage(ImageVoteWidget widget)
        {
            this.BeginLoading(widget);

            var task = new System.Threading.Tasks.Task(async() => {
                // get images until it is a valid image
                Image image = null;
                while (image == null)
                {
                    image = await this.ImageLoader.NextImage();
                }

                System.Threading.SpinWait.SpinUntil(() => !widget.IsFading);

                // update image in gui thread
                BooruApp.BooruApplication.TaskRunner.StartTaskMainThread("Change image", () => {
                    widget.Image = image;
                    image.Release();
                    this.FinishLoading();
                });
            });

            task.Start();
            return(task);
        }
 public void CreateLoadTask <T>(Func <T> _LoadFunction)
 {
     if (m_LoadTask == null)
     {
         m_LoadTask = new MultithreadTask(() =>
         {
             T result = default(T);
             try
             {
                 result = _LoadFunction();
             }
             catch (Exception ex)
             {
                 Logger.LogException(ex);
             }
             lock (m_LockObject)
             {
                 if (m_DataPriv == null || result != null)
                 {
                     m_DataPriv = result;
                     m_LastOutdateCheckDateTime = DateTime.UtcNow;
                     m_LastLoadTime             = DateTime.UtcNow;
                 }
                 m_LoadTask   = null;
                 m_DataLoaded = true;
             }
         });
         m_LoadTask.Start();
     }
 }
Beispiel #19
0
        private void Save()
        {
            //HttpClient client = new HttpClient ();
            NameValueCollection args = new NameValueCollection();

            args.Add("name", this.name.Text);
            args.Add("message", this.message.Text);
            args.Add("trigger", this.trigger.Text);

            string data = "name=" + this.name.Text + "&message=" + this.message.Text + "&trigger=" + this.trigger.Text;

            WebView web = FindViewById <WebView> (Resource.Id.browser);

            web.Settings.JavaScriptEnabled = true;


            web.PostUrl(
                this.endpoint,
                System.Text.Encoding.UTF8.GetBytes(data));

            go = false;
            int retries = 0;

            while (!go && retries < 4000)
            {
                System.Threading.Tasks.Task v = System.Threading.Tasks.Task.Delay(1000);
                v.Start();
                System.Threading.Tasks.Task.WaitAll(new System.Threading.Tasks.Task[] { v });
                retries++;
            }
            Finish();
        }
Beispiel #20
0
 public void Start()
 {
     if (thread != null)
     {
         thread.Start();
     }
 }
Beispiel #21
0
 private void btnGenerar_Click(object sender, EventArgs e)
 {
     oNomina = new WCF_Nomina.Hersan_NominaClient();
     try {
         if (gvDatos.RowCount == 0)
         {
             if (RadMessageBox.Show("Desea general las semanas del año ?", this.Text, MessageBoxButtons.YesNo, RadMessageIcon.Question) == DialogResult.No)
             {
                 return;
             }
             else
             {
                 if (oNomina.NOM_Semanas_generar(dtAnio.Value.Year) > 0)
                 {
                     System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(() => { CargaGrid(); });
                     task.Start();
                     RadMessageBox.Show("Semanas generadas correctamente", this.Text, MessageBoxButtons.OK, RadMessageIcon.Info);
                 }
                 else
                 {
                     RadMessageBox.Show("Ocurrió un error al generar las semanas del año", this.Text, MessageBoxButtons.OK, RadMessageIcon.Exclamation);
                 }
             }
         }
     } catch (Exception ex) {
         RadMessageBox.Show("Ocurrió un error al generar las semanas del año.\n" + ex.Message, this.Text, MessageBoxButtons.OK, RadMessageIcon.Error);
     } finally {
         oNomina = null;
     }
 }
Beispiel #22
0
        private static void Log(LogType type, string message)
        {
            try
            {
                string final = "(Truffle) ";

                switch (type)
                {
                case LogType.Error:
                    final = "(Truffle) (Error) " + message;
                    break;

                case LogType.Message:
                    final = "(Truffle) " + message;
                    break;
                }

                //if (GenericPrincipal.Current.Identity.Name != String.Empty)
                //    final = "(Context:" + System.Security.Principal.GenericPrincipal.Current.Identity.Name + ") " + final;

                Action <object> action = (object msg) =>
                {
                    blowBubble(msg.ToString());
                };

                System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(action, final);
                t.Start();
            }
            catch { }
        }
Beispiel #23
0
 public void Start(IStreamable peer)
 {
     _Stop = false;
     _Peer = peer;
     _Task = new System.Threading.Tasks.Task(_Run, System.Threading.Tasks.TaskCreationOptions.LongRunning);
     _Task.Start();
 }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            var dte = Package.GetGlobalService(typeof(DTE)) as DTE;
            var doc = dte.ActiveDocument;

            if (doc == null)
            {
                MessageBox.Show("Please open a JavaScript file", "JS Google Closure Compiler");
                return;
            }

            errorListHelper.Remove();

            const string CompilerUrl    = @"http://closure-compiler.appspot.com/compile";
            var          requestCompile = new RequestCompile(
                doc.FullName,
                CompilationLevelHelper.AdvancedOptimizations,
                CompilerUrl);

            Action asyncRunner = () =>
            {
                var compilerResults = requestCompile.Run();
                var resultsWriter   = new ResultsWriter(errorListHelper);
                resultsWriter.EmitErrors(compilerResults);
                resultsWriter.EmitWarnings(compilerResults);
            };

            var task1 = new System.Threading.Tasks.Task(asyncRunner);

            task1.Start();
        }
Beispiel #25
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);
     }
 }
        /// <summary>
        /// Refresh margin's data and redraw it.
        /// </summary>
        private void UpdateMargin()
        {
            var task = new Task(() => {
                bool success = RefreshVersionControl();
                if (_isDisposed)
                {
                    return;
                }

                if (!success)
                {
                    lock (_drawLockObject) {
                        _versionControl     = null;
                        _versionControlItem = null;
                        SetMarginActivated(false);
                        Redraw(false, MarginDrawReason.InternalReason);
                    }
                }
                else
                {
                    lock (_drawLockObject) {
                        _versionControlItem = null; // Reset as it belongs to the old versionControl
                    }
                    RefreshVersionControlItem(CancellationToken.None);
                }
            });

            task.Start();
        }
Beispiel #27
0
        /// <summary>
        /// Starts laser read and write tasks
        /// </summary>
        static void StartLaserTasks()
        {
            _laserWriteTask = new System.Threading.Tasks.Task(() =>
            {
                Task writeTask        = new Task("LaserWrite");
                double[] firstSamples = LaserFunction(0, _rate);
                writeTask.AOChannels.CreateVoltageChannel("Dev2/AO2", "", 0, 10, AOVoltageUnits.Volts);
                writeTask.Timing.ConfigureSampleClock("", _rate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples);
                writeTask.Stream.WriteRegenerationMode = WriteRegenerationMode.DoNotAllowRegeneration;
                AnalogSingleChannelWriter dataWriter   = new AnalogSingleChannelWriter(writeTask.Stream);
                dataWriter.WriteMultiSample(false, firstSamples);
                writeTask.Start();
                long start_sample = _rate;
                while (!_writeStop.WaitOne(100))
                {
                    double[] samples = LaserFunction(start_sample, _rate);
                    if (samples == null)
                    {
                        break;
                    }
                    dataWriter.WriteMultiSample(false, samples);
                    start_sample += _rate;
                }
                writeTask.Dispose();
                Task resetTask = new Task("LaserReset");
                resetTask.AOChannels.CreateVoltageChannel("Dev2/AO2", "", 0, 10, AOVoltageUnits.Volts);
                AnalogSingleChannelWriter resetWriter = new AnalogSingleChannelWriter(resetTask.Stream);
                resetWriter.WriteSingleSample(true, 0);
                resetTask.Dispose();
            });

            _laserReadTask = new System.Threading.Tasks.Task(() =>
            {
                Task read_task = new Task("laserRead");
                read_task.AIChannels.CreateVoltageChannel("Dev2/ai16", "Laser", AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
                read_task.Timing.ConfigureSampleClock("", _rate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples);
                read_task.Start();
                AnalogSingleChannelReader laser_reader = new AnalogSingleChannelReader(read_task.Stream);
                while (!_readStop.WaitOne(10))
                {
                    var nsamples = read_task.Stream.AvailableSamplesPerChannel;
                    if (nsamples >= 10)
                    {
                        double[] read = laser_reader.ReadMultiSample((int)nsamples);
                        lock (_laser_aiv_lock)
                        {
                            foreach (double d in read)
                            {
                                //Simple exponential smoother
                                _laser_aiv = 0.9 * _laser_aiv + 0.1 * d;
                            }
                        }
                    }
                }
                read_task.Dispose();
            });
            _laserWriteTask.Start();
            _laserReadTask.Start();
        }
Beispiel #28
0
    static void Main(string[] args)
    {
        var t = new System.Threading.Tasks.Task(DownloadPageAsync);

        t.Start();
        Console.WriteLine("Downloading page...");
        Console.Read();
    }
        public void Run(string configuration, IResultHandler resultHandler)
        {
            Console.WriteLine("Doing work for: " + configuration);

            var t = new System.Threading.Tasks.Task(() => { resultHandler.OnSuccess(); });

            t.Start();
        }
Beispiel #30
0
        void _done()
        {
            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(doneAsync);
            t.Start();

            //var t = new DataTaskTask(this);
            //t.Execute();
        }
        public void Load()
        {
            tokenSource = new CancellationTokenSource();
            CancellationToken ct = tokenSource.Token;

            loadTask = new System.Threading.Tasks.Task(loadfromdb, ct);
            loadTask.Start();
        }
Beispiel #32
0
        public void Run(string configuration, IResultHandler resultHandler)
        {
            Console.WriteLine("Doing work for: " + configuration);

            var t = new System.Threading.Tasks.Task(() => { resultHandler.OnSuccess(); });

            t.Start();
        }
Beispiel #33
0
        //选择素材进行下载
        private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ShowNewWin.Visibility = Visibility.Visible;
            System.Threading.Tasks.Task task = new System.Threading.Tasks.Task((Action) delegate
            {
                try
                {
                    Grid grid = sender as Grid;
                    if (grid == null)
                    {
                        return;
                    }
                    AssetInfo model = new AssetInfo();
                    this.Dispatcher.Invoke((Action) delegate { model = grid.DataContext as AssetInfo; });


                    if (model == null)
                    {
                        return;
                    }

                    byte[] buffer;
                    if (!File.Exists(model._as_url))
                    {
                        FileStream fs = new FileStream(model._as_url, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                        fs.Seek(fs.Length, SeekOrigin.Current);


                        while ((buffer = Globals.client.DownLoadAsset(Guid.Parse(model._as_guid), fs.Length)).Length > 0)
                        {
                            fs.Write(buffer, 0, buffer.Length);
                        }

                        fs.Flush();
                        fs.Close();
                    }


                    if (Bpage)
                    {
                        _AssInfo.AssetName  = model._as_name;
                        _AssInfo.AssetPath  = model._as_url;
                        _AssInfo.Thumbnails = model._as_thumbnail;
                    }
                    thumbnails = model._as_thumbnail;
                    path       = model._as_url;

                    this.Dispatcher.Invoke((Action) delegate { ShowNewWin.Visibility = Visibility.Visible; this.DialogResult = true; });
                }
                catch (Exception ex)

                {
                    log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                    log.Error(ex.Message + "\r\n" + ex.StackTrace);
                }
            });
            task.Start();
        }
		/// <summary>
		///		Procesa los datos
		/// </summary>
		private void ProcessTimer()
		{ // Detiene el temporizador
				objTimer.Stop();
			// Si se debe ejecutar, crea un hilo nuevo
				if (MustExecute())
					{ System.Threading.Tasks.Task objTaskCompiler = new System.Threading.Tasks.Task(() => CallProcess());

							// Arranca el hilo
								objTaskCompiler.Start();
					}
		}
Beispiel #35
0
       public static void Main()
        {
            // Start the HTML5 Pubnub client
            Process.Start(@"..\..\index.html");

            System.Threading.Thread.Sleep(2000);

            PubnubAPI pubnub = new PubnubAPI(
                "pub-c-35648aec-f497-4d5b-ab3e-8d621ba3794c",               // PUBLISH_KEY
                "sub-c-fb346fbe-8d19-11e5-a7e4-0619f8945a4f",               // SUBSCRIBE_KEY
                "sec-c-M2JmNWIwODMtNDNhYi00MjBlLWI2ZTYtZjExNjA1OTU4ZDBj",   // SECRET_KEY
                true                                                        // SSL_ON?
            );

            string channel = "simple chat channel";

            // Publish a sample message to Pubnub
            List<object> publishResult = pubnub.Publish(channel, "Hello there!");

            Console.WriteLine(
                "Publish Success: " + publishResult[0] + "\n" +
                "Publish Info: " + publishResult[1]
            );

            // Show PubNub server time
            object serverTime = pubnub.Time();
            Console.WriteLine("Server Time: " + serverTime);

            // Subscribe for receiving messages (in a background task to avoid blocking)
            var task = new System.Threading.Tasks.Task(
                () =>
                pubnub.Subscribe(
                    channel,
                    delegate (object message)
                    {
                        Console.WriteLine("Received Message -> '" + message + "'");
                        return true;
                    }

                )
            );

            task.Start();

            // Read messages from the console and publish them to Pubnub
            while (true)
            {
                Console.Write("Enter a message to be sent to Pubnub: ");
                var message = Console.ReadLine();
                pubnub.Publish(channel, message);
                Console.WriteLine("Message {0} sent.", message);
            }
        }
Beispiel #36
0
        public Service(VerifyData data)
        {
            _Key = new object();
            _Data = data;
            _Soin = new SpinWait();

            _Proxy = new Proxy(new RemotingFactory());
            (_Proxy as IUpdatable).Launch();
            _ProxyUpdate = new Task(Service._UpdateProxy, new WeakReference<Proxy>(_Proxy));
            _ProxyUpdate.Start();

            _User = _Proxy.SpawnUser("1");
        }
        private static void Main()
        {
            // Start the HTML5 Pubnub client
            Process.Start("..\\..\\PubNubClient.html");

            Thread.Sleep(2000);

            var pubNubApi = new PubNubApi(
                "pub-c-4a077e28-832a-4b58-aa75-2a551f0933ef",               // PUBLISH_KEY
                "sub-c-3a79639c-059e-11e3-8dc9-02ee2ddab7fe",               // SUBSCRIBE_KEY
                "sec-c-ZTAxYTk2ZGMtNzRiNi00ZTkwLTg4ZWEtOTMxOTk4NzAyNGIw",   // SECRET_KEY
                true                                                        // SSL_ON?
            );

            string channel = "chat-channel";

            // Publish a sample message to Pubnub
            List<object> publishResult = pubNubApi.Publish(channel, "Hello Pubnub!");
            Console.WriteLine(
                "Publish Success: " + publishResult[0].ToString() + "\n" +
                "Publish Info: " + publishResult[1]
            );

            // Show PubNub server time
            object serverTime = pubNubApi.Time();
            Console.WriteLine("Server Time: " + serverTime.ToString());

            // Subscribe for receiving messages (in a background task to avoid blocking)
            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () =>
                pubNubApi.Subscribe(
                    channel,
                    delegate(object message)
                    {
                        Console.WriteLine("Received Message -> '" + message + "'");
                        return true;
                    }
                )
            );
            t.Start();

            // Read messages from the console and publish them to PubNub
            while (true)
            {
                Console.Write("Enter a message to be sent to Pubnub: ");
                string message = Console.ReadLine();
                pubNubApi.Publish(channel, message);
                Console.WriteLine("Message {0} sent.", message);
            }
        }
        static void Main()
        {
            // Start the HTML5 Pubnub client
            Process.Start("..\\..\\PubNub-HTML5-Client.html");

            //System.Threading.Thread.Sleep(2000);

            PubnubAPI pubnub = new PubnubAPI(
                "pub-c-a40489bf-98a7-40ff-87df-4af2f371d50a",               // PUBLISH_KEY
                "sub-c-68236eaa-8bb6-11e5-8b47-02ee2ddab7fe",               // SUBSCRIBE_KEY
                "sec-c-ZmVhNTE4NTgtYWRmYi00NGNjLWIzNjgtZjI1YTU2M2ZkMDU2",   // SECRET_KEY
                true                                                        // SSL_ON?
            );
            string channel = "demo-channel";

            // Publish a sample message to Pubnub
            List<object> publishResult = pubnub.Publish(channel, "Hello Pubnub!");
            Console.WriteLine(
                "Publish Success: " + publishResult[0].ToString() + "\n" +
                "Publish Info: " + publishResult[1]
            );

            // Show PubNub server time
            object serverTime = pubnub.Time();
            Console.WriteLine("Server Time: " + serverTime.ToString());

            // Subscribe for receiving messages (in a background task to avoid blocking)
            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () =>
                pubnub.Subscribe(
                    channel,
                    delegate (object message)
                    {
                        Console.WriteLine("Received Message -> '" + message + "'");
                        return true;
                    }
                )
            );
            t.Start();

            // Read messages from the console and publish them to Pubnub
            while (true)
            {
                Console.Write("Enter a message to be sent to Pubnub: ");
                string msg = Console.ReadLine();
                pubnub.Publish(channel, msg);
                Console.WriteLine("Message {0} sent.", msg);
            }
        }
        /* 02. Implement a very simple chat application based on some message queue service:
            Users can send message into a common channel.
            Messages are displayed in the format {IP : message_text}.
            Use PubNub. Your application can be console, GUI or Web-based.*/
        static void Main()
        {
            Process.Start("..\\..\\PubNubChatDemo.html");

            System.Threading.Thread.Sleep(2000);

            PubnubAPI pubnub = new PubnubAPI(
                "pub-c-e485b33f-6d32-4410-9cb8-98c61a4a48df",               // PUBLISH_KEY
                "sub-c-44c8865e-0817-11e3-ab8d-02ee2ddab7fe",               // SUBSCRIBE_KEY
                "sec-c-NWQwNjFmY2EtNzljMy00MGU2LTk4YjYtMWQwZThmM2U1Mjcw",   // SECRET_KEY
                false                                                        // SSL_ON?
            );
            string channel = "secret-ninja-channel";

            // Publish a sample message to Pubnub
            List<object> publishResult = pubnub.Publish(channel, "Hello Pubnub!");
            Console.WriteLine(
                "Publish Success: " + publishResult[0].ToString() + "\n" +
                "Publish Info: " + publishResult[1]
            );

            // Show PubNub server time
            object serverTime = pubnub.Time();

            Console.WriteLine("Server Time: " + serverTime.ToString());

            // Subscribe for receiving messages (in a background task to avoid blocking)
            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () =>
                pubnub.Subscribe(
                    channel,
                    delegate(object message)
                    {
                        Console.WriteLine("Received Message -> '" + message + "'");
                        return true;
                    }
                )
            );
            t.Start();

            // Read messages from the console and publish them to Pubnub
            while (true)
            {
                Console.Write("Enter a message to be sent to Pubnub: ");
                string msg = Console.ReadLine();
                pubnub.Publish(channel, msg);
                Console.WriteLine("Message {0} sent.", msg);
            }
        }
        internal static void Main(string[] args)
        {
            Process.Start("..\\..\\RecieverPage.html");

            System.Threading.Thread.Sleep(2000);

            PubnubAPI pubnub = new PubnubAPI(
                "pub-c-d9aadadf-abba-443c-a767-62023d43411a",               // PUBLISH_KEY
                "sub-c-102d0358-073f-11e3-916b-02ee2ddab7fe",               // SUBSCRIBE_KEY
                "sec-c-YmI4NDcxNzQtOWZhYi00MTRmLWI4ODktMDI2ZjViMjQyYzdj",   // SECRET_KEY
                false);

            string channel = "PublishApp";

            // Publish a sample message to Pubnub
            List<object> publishResult = pubnub.Publish(channel, "Hello Pubnub!");
            Console.WriteLine(
                "Publish Success: " + publishResult[0].ToString() + "\n" +
                "Publish Info: " + publishResult[1]);

            // Show PubNub server time
            object serverTime = pubnub.Time();
            Console.WriteLine("Server Time: " + serverTime.ToString());

            // Subscribe for receiving messages (in a background task to avoid blocking)
            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () =>
                pubnub.Subscribe(
                    channel,
                    delegate(object message)
                    {
                        Console.WriteLine("Received Message -> '" + message + "'");
                        return true;
                    }));

            t.Start();

            // Read messages from the console and publish them to Pubnub
            while (true)
            {
                Console.Write("Enter a message to be sent to Pubnub: ");
                string msg = Console.ReadLine();
                pubnub.Publish(channel, msg);
                Console.WriteLine("Message {0} sent.", msg);
            }
        }
Beispiel #41
0
        static void Main(string[] args)
        {
            log("Server started.");

            Server.ConsoleIO.ConsoleCommand consoleIO = new ConsoleIO.ConsoleCommand(system);

            System.Action oAction = new System.Action(run);
            System.Threading.Tasks.Task oTask = new System.Threading.Tasks.Task(oAction);

            oTask.Start();

               while (system.run())
            {
                System.Threading.Thread.Sleep(5000);
            }

            log("Server closed");
        }
        static void Main()
        {
            // Start the HTML5 Pubnub client
            Process.Start("..\\..\\PubnubClient.html");

            System.Threading.Thread.Sleep(2000);

            PubnubAPI pubnub = new PubnubAPI(PUBLISH_KEY, SUBSCRIBE_KEY, SECRET_KEY, true);
            string channel = "chat-channel";

            // Publish a sample message to Pubnub
            List<object> publishResult = pubnub.Publish(channel, "Hello Pubnub!");
            Console.WriteLine(
                "Publish Success: " + publishResult[0].ToString() + "\n" +
                "Publish Info: " + publishResult[1]
            );

            // Show PubNub server time
            object serverTime = pubnub.Time();
            Console.WriteLine("Server Time: " + serverTime.ToString());

            // Subscribe for receiving messages (in a background task to avoid blocking)
            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () =>
                pubnub.Subscribe(
                    channel,
                    delegate (object message)
                    {
                        Console.WriteLine("Received Message -> '" + message + "'");
                        return true;
                    }
                )
            );
            t.Start();

            // Read messages from the console and publish them to Pubnub
            while (true)
            {
                Console.Write("Enter a message to be sent to Pubnub: ");
                string msg = Console.ReadLine();
                pubnub.Publish(channel, msg);
                Console.WriteLine("Message {0} sent.\n", msg);
            }
        }
Beispiel #43
0
        static void Main(string[] args)
        {
            var myIp = GetExternalIp();
            // Start the HTML5 Pubnub client
            Process.Start(@"..\..\..\PubNub-HTML5-Client.html");

            System.Threading.Thread.Sleep(2000);

            Pubnub pubnub = new Pubnub(
                "pub-c-4331b990-8629-4f47-9669-51f0e2ee9c9d",               // PUBLISH_KEY
                "sub-c-bfd2fbba-0428-11e3-91de-02ee2ddab7fe",               // SUBSCRIBE_KEY
                "sec-c-NDExYTBlYjUtM2QyYS00YTJiLWExNDItM2Y5NDQ2ZjA1N2Uy",   // SECRET_KEY
                "",                                                         // CIPHER_KEY
                true                                                        // SSL_ON?
            );
            string channel = "ninja-channel";

            // Publish a sample message to Pubnub
            pubnub.Publish<string>(channel, "", DisplayReturnMessage);

            // Show PubNub server time
            pubnub.Time<string>(DisplayReturnMessage);
            //Console.WriteLine("Server Time: " + serverTime.ToString());

            // Subscribe for receiving messages (in a background task to avoid blocking)
            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () =>
                pubnub.Subscribe<string>(
                    channel,
                    DisplayReturnMessage,
                    DisplayConnectStatusMessage
                )
            );
            t.Start();

            // Read messages from the console and publish them to Pubnub
            while (true)
            {
                Console.Write("Enter a message to be sent to Pubnub: ");
                string msg = Console.ReadLine();
                pubnub.Publish<string>(channel, myIp + " : " + msg, DisplayReturnMessage);
                Console.WriteLine("Message {0} sent.", msg);
            }
        }
Beispiel #44
0
 private void btnMaster_Click(object sender, EventArgs e)
 {
     List<Form> SubForms = new List<Form>();
     //Action<Form, Form> AddForm = (v, f) => { v = f; SubForms.Add(v); };
     Action<Picasso.MakeForm, Picasso.AssignForm> NewForm =
         (Construct, AssignToVar) =>
         {
             Form f = Construct();
             SubForms.Add(f);
             this.AddOwnedForm(f);
             f.Owner = this;
             AssignToVar(f);
         };
     M = new Master(ImgPath, NewForm, this);
     //int ChildrenCount;
     Watch = new Stopwatch();
     Action A = M.GenerateChildren;
     System.Threading.Tasks.Task T = new System.Threading.Tasks.Task(A);
     //System.Threading.Thread Th = new System.Threading.Thread(new System.Threading.ThreadStart(A));
     Watch.Start();
     T.Start();
 }
        private bool CreateUser(UserClass user)
        {
            var connection = new SqlCeConnection(this.path);
            try
            {
                var eng = new SqlCeEngine(this.path);
                var cleanup = new System.Threading.Tasks.Task(eng.Dispose);
                eng.CreateDatabase();
                cleanup.Start();
            }
            catch (Exception e)
            {
                EventLogging.WriteError(e);
            }
            connection.Open();

            var taco = new SqlCeDataAdapter();
            var userIdParam = new SqlCeParameter("userId", SqlDbType.Int, 60000, "UserID") { Value = user.UserId };
            var userNameParam = new SqlCeParameter("userName", SqlDbType.NVarChar, 128, "UserName") { Value = user.UserName };
            var passHashParam = new SqlCeParameter("passHash", SqlDbType.NVarChar, 128, "PassHash") { Value = user.PasswordHash };
            var friendsParam = new SqlCeParameter("friends", SqlDbType.VarBinary, 5000, "Friends") { Value = user.Friends };
            var dbCommand = new SqlCeCommand();
            dbCommand.Connection = connection;
            dbCommand.Parameters.Add(userNameParam);
            taco.InsertCommand.Parameters.Add(userNameParam);
            taco.InsertCommand.Parameters.Add(passHashParam);
            taco.InsertCommand.Parameters.Add(friendsParam);
            taco.InsertCommand.Parameters.Add("UserName", SqlDbType.NVarChar, 128);
            return false;
        }
        public void runUpload(System.Threading.CancellationToken serviceStop)
        {
            DateTime startTime = DateTime.UtcNow;
            string uploadToken = "";
            Session session = new Session(connection.Hostname, 80);
            session.APIVersion = API_Version.LATEST;

            try
            {
                session.login_with_password(connection.Username, connection.Password);
                connection.LoadCache(session);
                var pool = Helpers.GetPoolOfOne(connection);
                if (pool != null)
                {
                    try
                    {
                        string opaqueref = Secret.get_by_uuid(session, pool.HealthCheckSettings.UploadTokenSecretUuid);
                        uploadToken = Secret.get_value(session, opaqueref);
                    }
                    catch (Exception e)
                    {
                        log.Error("Exception getting the upload token from the xapi secret", e);
                        uploadToken = null;
                    }
                }

                if (string.IsNullOrEmpty(uploadToken))
                {
                    if (session != null)
                        session.logout();
                    session = null;
                    log.ErrorFormat("The upload token is not retrieved for {0}", connection.Hostname);
                    updateHealthCheckSettings(false, startTime);
                    server.task = null;
                    ServerListHelper.instance.UpdateServerInfo(server);
                    return;
                }

            }
            catch (Exception e)
            {
                if (session != null)
                    session.logout();
                session = null;
                log.Error(e, e);
                updateHealthCheckSettings(false, startTime);
                server.task = null;
                ServerListHelper.instance.UpdateServerInfo(server);
                return;
            }

            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                Func<string> upload = delegate()
                {
                    try
                    {
                        return bundleUpload(connection, session, uploadToken, cts.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        return "";
                    }
                };
                System.Threading.Tasks.Task<string> task = new System.Threading.Tasks.Task<string>(upload);
                task.Start();

                // Check if the task runs to completion before timeout.
                for (int i = 0; i < TIMEOUT; i += INTERVAL)
                {
                    // If the task finishes, set HealthCheckSettings accordingly.
                    if (task.IsCompleted || task.IsCanceled || task.IsFaulted)
                    {
                        if (task.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
                        {
                            string upload_uuid = task.Result;
                            if (!string.IsNullOrEmpty(upload_uuid))
                                updateHealthCheckSettings(true, startTime, upload_uuid);
                            else
                                updateHealthCheckSettings(false, startTime);
                        }
                        else
                            updateHealthCheckSettings(false, startTime);

                        server.task = null;
                        ServerListHelper.instance.UpdateServerInfo(server);
                        return;
                    }

                    // If the main thread (XenServerHealthCheckService) stops,
                    // set the cancel token to notify the working task to return.
                    if (serviceStop.IsCancellationRequested)
                    {
                        cts.Cancel();
                        updateHealthCheckSettings(false, startTime);
                        task.Wait();
                        server.task = null;
                        ServerListHelper.instance.UpdateServerInfo(server);
                        return;
                    }

                    System.Threading.Thread.Sleep(INTERVAL);
                }

                // The task has run for 24h, cancel the task and mark it as a failure upload.
                cts.Cancel();
                updateHealthCheckSettings(false, startTime);
                task.Wait();
                server.task = null;
                ServerListHelper.instance.UpdateServerInfo(server);
                return;
            }
            catch (Exception e)
            {
                if (session != null)
                    session.logout();
                session = null;
                log.Error(e, e);
                server.task = null;
                ServerListHelper.instance.UpdateServerInfo(server);
            }

        }
Beispiel #47
0
        /// <summary>
        /// 測定状態の変更イベント
        /// </summary>
        /// <param name="status"></param>
        void testSquence_StatusChanged(Sequences.TestSequence.TestStatusType status)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((MethodInvoker) delegate{ testSquence_StatusChanged(status); });
                return;
            }

            switch (status)
            {
                case Sequences.TestSequence.TestStatusType.Run:

                    controllerForm.SetMeasureStatus(frmMeasureController.MeasureStatus.Start);

                    bAllReadyStart = true;

                    this.measureTask.Start();

                    this.swMeasure.Reset();
                    this.swMeasure.Start();
                    ShowStatusMessage(AppResource.GetString("TXT_MEASURE_START"));

                    break;
                case Sequences.TestSequence.TestStatusType.Pause:
                    controllerForm.SetMeasureStatus(frmMeasureController.MeasureStatus.Stop);

                    //for (int i = 0; i < this.graph2DList.Length; i++)
                    //{
                    //    if (this.graph2DList[i] != null)
                    //    {
                    //        this.graph2DList[i].IsRealTime = false;
                    //    }
                    //}

                    this.swMeasure.Stop();

                    ShowStatusMessage(AppResource.GetString("MSG_MEAS_STOP_TEST"));

                    this.measureTask.Pause();

                    break;
                case Sequences.TestSequence.TestStatusType.Stop:
                    controllerForm.SetMeasureStatus(frmMeasureController.MeasureStatus.Exit);

                    ShowStatusMessage(AppResource.GetString("MSG_MEAS_END"));
                    try
                    {
                        this.controllerForm.Enabled = false;
                        this.graphControllerForm.Enabled = false;
                        this.Enabled = false;

                        RealTimeData.EndData();
                        this.measureTask.Pause();

                        bool bret = true;

                        //データが一つでも受信されていればデータ保存する。
                        if (RealTimeData.receiveCount != 0)
                        {
                            ShowStatusMessage(AppResource.GetString("MSG_MEAS_SAVE_FILES"));
                            // 測定設定ファイル群及びデータファイルを保存する
                            bret = SaveMeasureFiles();
                        }

                        if (bret)
                            testSquence.ExitTest();
                        else
                        {
                            //画面終了しない。再開があるため。
                            return;
                        }

                        //測定完了フラグオン
                        bMeasureClosed = true;
                    }
                    finally
                    {
                        this.controllerForm.Enabled = true;
                        this.graphControllerForm.Enabled = true;
                        this.Enabled = true;

                    }

                    //画面終了
                    if (this.InvokeRequired)
                        this.Invoke((MethodInvoker)delegate() { this.Close(); });
                    else
                        this.Close();

                    break;

                //緊急停止
                case Sequences.TestSequence.TestStatusType.EmergencyStop:

                    System.Threading.Tasks.Task task =
                        new System.Threading.Tasks.Task(
                            delegate
                            {
                                this.measureTask.Stop();
                                //測定を停止する。
                                testSquence.EndTest();
                            });

                    task.Start();

                    MessageBox.Show(AppResource.GetString("MSG_MEAS_EMERGENCY_STOP"), AppResource.GetString("TXT_MEASUREMENT"), MessageBoxButtons.OK, MessageBoxIcon.Stop);

                    break;
            }
        }
Beispiel #48
0
 public static void Initialize()
 {
     task = new System.Threading.Tasks.Task<DictionaryEntities>(InitializeThreadProc);
     task.Start();
 }
Beispiel #49
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;
 }
        public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
        {
            log.Info("XenServer Health Check Service start to refresh uploading tasks");

            //We need to check if CIS can be accessed in current enviroment

            List<ServerInfo> servers = ServerListHelper.instance.GetServerList();
            foreach (ServerInfo server in servers)
            {
                if (server.task != null && (!server.task.IsCompleted || !server.task.IsCanceled || !server.task.IsFaulted))
                {
                    continue;
                }

                XenConnection connectionInfo = new XenConnection();
                connectionInfo.Hostname = server.HostName;
                connectionInfo.Username = server.UserName;
                connectionInfo.Password = server.Password;
                log.InfoFormat("Check server {0} with user {1}", connectionInfo.Hostname, connectionInfo.Username);
                Session session = new Session(server.HostName, 80);
                session.APIVersion = API_Version.LATEST;
                try
                {
                    session.login_with_password(server.UserName, server.Password);
                    connectionInfo.LoadCache(session);
                    if (RequestUploadTask.Request(connectionInfo, session) || RequestUploadTask.OnDemandRequest(connectionInfo, session))
                    {
                        // Create a task to collect server status report and upload to CIS server
                        log.InfoFormat("Start to upload server status report for XenServer {0}", connectionInfo.Hostname);

                        XenServerHealthCheckBundleUpload upload = new XenServerHealthCheckBundleUpload(connectionInfo);
                        Action uploadAction = delegate()
                        {
                            upload.runUpload(cts.Token);
                        };
                        System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(uploadAction);
                        task.Start();

                        server.task = task;
                        ServerListHelper.instance.UpdateServerInfo(server);
                    }
                    session.logout();
                    session = null;
                }
                catch (Exception exn)
                {
                    if (session != null)
                        session.logout();
                    log.Error(exn, exn);
                }
            }
        }
        private void log(string level, string message)
        {
            //Try to get the threadId which is very useful when debugging
            string threadId = null;
            try
            {
#if NETFX_CORE
                threadId = Environment.CurrentManagedThreadId.ToString();
#else
                threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
#endif
            }
            catch (Exception) { }

            string logStringToWrite;
            if (threadId != null)
                logStringToWrite = DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString() + " [" + threadId + " - " + level + "] - " + message;
            else
                logStringToWrite = DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString() + " [" + level + "] - " + message;

#if !NETFX_CORE
            if (_currentLogMode == LogMode.ConsoleAndLogFile || _currentLogMode == LogMode.ConsoleOnly)
                Console.WriteLine(logStringToWrite);
#endif

            if ((_currentLogMode == LogMode.ConsoleAndLogFile || _currentLogMode == LogMode.LogFileOnly) && LogFileLocationName != null)
            {
                try
                {
                    lock (_locker)
                    {

#if NETFX_CORE
                        System.Threading.Tasks.Task writeTask = new System.Threading.Tasks.Task(async () =>
                            {
                                while (true)
                                {
                                    try
                                    {
                                        Windows.Storage.StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
                                        Windows.Storage.StorageFile file = await folder.CreateFileAsync(LogFileLocationName, Windows.Storage.CreationCollisionOption.OpenIfExists);
                                        await Windows.Storage.FileIO.AppendTextAsync(file, logStringToWrite + "\n");
                                        break;
                                    }
                                    catch (Exception) { }
                                }
                            });

                        writeTask.ConfigureAwait(false);
                        writeTask.Start();
                        writeTask.Wait(); 
#else
                        using (var sw = new System.IO.StreamWriter(LogFileLocationName, true))
                            sw.WriteLine(logStringToWrite);
#endif                        
                    }
                }
                catch (Exception) { }
            }
        }
        public void InputWord(string url)
        {
            Random rd = new Random();
            int rdd = rd.Next(10, 100);
            string filename = "rs"+DateTime.Now.ToString("yyyy-MM-dd") + rdd.ToString() + ".doc";
            string LocalPath = null;
            //string pdfurl=null;
            try
            {
                int poseuqlurl = url.IndexOf('=');
                int possnap;
                string url1;
                string pdfname;
                url1 = url.Substring(poseuqlurl + 1, url.Length - poseuqlurl - 1);
                possnap = url1.LastIndexOf('/');
                pdfname = url1.Substring(possnap + 1, url1.Length - possnap - 1);
                filename = pdfname;
                /*int poseuqlurl = url.IndexOf('=');
                string url1;
                url1 = url.Substring(poseuqlurl + 1, url.Length - poseuqlurl - 1);
                //pdfurl;*/
                Uri u = new Uri(url1);
                //Uri u = new Uri(url);
                //filename = "123.doc";
                //string time1 = DateTime.Now.ToString();
                //filename = DateTime.Now.ToString() + ".doc";
                LocalPath = "D:\\files\\" + filename;
                if (!File.Exists(@LocalPath))
                {
                    //不存在
                    HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u);
                    mRequest.Method = "GET";
                    mRequest.ContentType = "application/x-www-form-urlencoded";

                    HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse();
                    Stream sIn = wr.GetResponseStream();
                    FileStream fs = new FileStream(LocalPath, FileMode.Create, FileAccess.Write);
                    byte[] bytes = new byte[4096];
                    int start = 0;
                    int length;
                    while ((length = sIn.Read(bytes, 0, 4096)) > 0)
                    {
                        fs.Write(bytes, 0, length);
                        start += length;
                    }
                    sIn.Close();
                    wr.Close();
                    fs.Close();
                    string pdfpath = showwordfiles(LocalPath);
                }
            }
            catch { }
            //LocalPath = "D:\\1111.doc";
            delet_tables(LocalPath);
            FileInfo fi = new FileInfo(LocalPath);
            fi.Attributes = FileAttributes.ReadOnly;

            //然后完成对文档的解析

            _Application app = new Microsoft.Office.Interop.Word.Application();
            _Application app1 = new Microsoft.Office.Interop.Word.Application();
            _Application app2 = new Microsoft.Office.Interop.Word.Application();
            _Application app3 = new Microsoft.Office.Interop.Word.Application();
            _Application app4 = new Microsoft.Office.Interop.Word.Application();
            _Application app5 = new Microsoft.Office.Interop.Word.Application();
            _Application app6 = new Microsoft.Office.Interop.Word.Application();
            _Application app7 = new Microsoft.Office.Interop.Word.Application();
            //_Document doc;

            //string temp;
            //type1 = "SyRS";
            //type2 = "TSP";
            //string pattern1 = @"...-SyRS-....";
            //pattern1 = @"^\[\w+-\w+-\w+-\d+\]";
            //pattern2 = @"\[\w+-\w+-\d+\]";
            pattern1 = @"^\[\w{3,}-.+\]";
            pattern2 = @"\[\w{3,}-.+?\]";
            /*pattern1 = @"^\[\w+-\w+-\d+\]";
            pattern2 = @"\[\w+-\w+-\d+\]";*/
            pattern3 = @"End";
            pattern4 = @"^#";
            //string pattern5 = @"[*]";

            //object fileName = @"D:\\projectfiles\cascofiles\testdoc.doc"
            //E:\\cascofiles\testdoc.doc
            object fileName = LocalPath;
            // if (dlg.ShowDialog() == DialogResult.OK)
            //  {
            //     fileName = dlg.FileName;
            //  }
            object unknow = System.Type.Missing;
            //object unknow1 = System.Reflection.Missing.Value;
            doc = app.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc1 = app1.Documents.Open(ref fileName,
               ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
               ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
               ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc2 = app2.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc3 = app3.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc4 = app4.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc5 = app5.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc6 = app6.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc7 = app7.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            pcount = doc.Paragraphs.Count;//count the paragraphs
            int jjj = pcount;

            //Thread t1 = new Thread(new ThreadStart(thread1));
            //Thread t2 = new Thread(new ThreadStart(thread2));
            var t1 = new System.Threading.Tasks.Task(() => thread1());
            var t2 = new System.Threading.Tasks.Task(() => thread2());
            var t3 = new System.Threading.Tasks.Task(() => thread3());
            var t4 = new System.Threading.Tasks.Task(() => thread4());
            var t5 = new System.Threading.Tasks.Task(() => thread5());
            var t6 = new System.Threading.Tasks.Task(() => thread6());
            var t7 = new System.Threading.Tasks.Task(() => thread7());
            var t8 = new System.Threading.Tasks.Task(() => thread8());
            t1.Start();
            t2.Start();
            t3.Start();
            t4.Start();
            t5.Start();
            t6.Start();
            t7.Start();
            t8.Start();
            System.Threading.Tasks.Task.WaitAll(t1,t2,t3,t4,t5,t6,t7,t8);
            doc.Close(ref unknow, ref unknow, ref unknow);

            doc1.Close(ref unknow, ref unknow, ref unknow);

            doc2.Close(ref unknow, ref unknow, ref unknow);

            doc3.Close(ref unknow, ref unknow, ref unknow);

            doc4.Close(ref unknow, ref unknow, ref unknow);

            doc5.Close(ref unknow, ref unknow, ref unknow);

            doc6.Close(ref unknow, ref unknow, ref unknow);

            doc7.Close(ref unknow, ref unknow, ref unknow);

            app.Quit(ref unknow, ref unknow, ref unknow);
            app1.Quit(ref unknow, ref unknow, ref unknow);
            app2.Quit(ref unknow, ref unknow, ref unknow);
            app3.Quit(ref unknow, ref unknow, ref unknow);
            app4.Quit(ref unknow, ref unknow, ref unknow);
            app5.Quit(ref unknow, ref unknow, ref unknow);
            app6.Quit(ref unknow, ref unknow, ref unknow);
            app7.Quit(ref unknow, ref unknow, ref unknow);
            //string jsonString = string1+string2+string3+string4+string5+string6+string7+string8;
            var json = new JavaScriptSerializer().Serialize(aaa.finalstrings);
            //jsonString = string1;
            //return myarray[0].arraycontent[5];
            Context.Response.ContentType = "text/json";
            Context.Response.Write(json);
            Context.Response.End();
            //return jsonString;
            //return myarray[0].sourse[0];
            //return "123";
        }
        private void switchConfigurations(EnvironmentConfig config)
        {
            var w = new NetEnvSwitcher.AreYouSureWindow(config.Name);
            w.Owner = this;
            w.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;

            if (w.ShowDialog() == true)
            {
                ConfigurationsPanel.IsEnabled = false;

                LogParagraph.Inlines.Add(new LineBreak());

                var rect = new Rectangle();
                rect.Fill = Brushes.Gray;
                rect.Width = 600;
                rect.Height = 1;
                rect.Margin = new Thickness(0, 10, 0, 10);
                LogParagraph.Inlines.Add(rect);
                LogParagraph.Inlines.Add(new LineBreak());

                var t = new System.Threading.Tasks.Task(() =>
                    {
                        try
                        {
                            WriteLine("======== Switching to " + config.Name);

                            var bannedProcessesRunning = _bannedProcManager.GetBannedProcessesRunning();
                            if (bannedProcessesRunning.Count == 0)
                            {

                                _serviceManager.StopServices();

                                _envManager.SwitchTo(config);

                                _envManager.ResetAConfigRevisionCount();

                                WriteLine("Sleeping 3 seconds for good measure...");
                                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3));

                                _serviceManager.StartServices(config.IsGuardServerAllowed);

                                WriteLine("Launching GuardianMFC");
                                _envManager.LaunchGuardianMFC();

                                WriteLine("======== Switched to " + config.Name);
                                addMissionAccomplishedImage();
                            }
                            else
                            {
                                WriteLine("PROBLEM: You need to stop apps before switching!");
                                foreach (var p in bannedProcessesRunning)
                                {
                                    WriteLine(" -> " + p.ProcessName);
                                }

                                Dispatcher.BeginInvoke(new Action(() =>
                                    {
                                        var window = new NetEnvSwitcher.RunningAppsWindow(bannedProcessesRunning);
                                        window.Owner = this;
                                        window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
                                        window.ShowDialog();
                                    }));
                            }

                            refreshGuiAfterOperation();
                        }
                        catch (Exception ex)
                        {
                            WriteLine("!!!!!!!! Problem switching to " + config.Name);

                            while (ex != null)
                            {
                                WriteLine(ex.ToString());
                                ex = ex.InnerException;
                            }

                            refreshGuiAfterOperation();
                        }
                    });
                t.Start();
            }
        }
 private void CorrectCaseTableNames(object sender, EventArgs e)
 {
     try
     {
         var task = new System.Threading.Tasks.Task(() =>
         {
             OutputPane.WriteMessageAndActivatePane("Correcting the case of table names...");
             var finder = new CorrectCaseTableFinder();
             finder.CorrectCaseAllTableNames();
             OutputPane.WriteMessageAndActivatePane("Correcting the case of table names...done");
         });
         
         task.Start();
         
         if (task.Exception != null)
             throw task.Exception;
     }
     catch (Exception ex)
     {
         OutputPane.WriteMessage("Error correcting table name case: {0}", ex.Message);
     }
 }
Beispiel #55
0
        static void Main(string[] args)
        {
            Console.WriteLine("Beispiel für parallele Programmierung in c#. ");
            Console.WriteLine();

            Console.WriteLine("Berechnung von Primzahlen Auswahlmöglichkeiten:");
            Console.WriteLine("    [1] Sequentiel");
            Console.WriteLine("    [2] Parallel");
            Console.WriteLine("    [3] Parallel LINQ");
            Console.WriteLine("    [4] Parallel LINQ mit Einschränkung an CPU-Kerne");
            Console.WriteLine("");
            Console.WriteLine("Andere Funktionen:");
            Console.WriteLine("    [5] Parallel Invoke");
            Console.WriteLine("    [6] Task-Klasse");
            Console.WriteLine("");
            Console.WriteLine("Anwendung Auswahlmöglichkeiten:");
            Console.WriteLine("    [7] Exit");
            Console.WriteLine();

            do
            {
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
                string key = keyInfo.KeyChar.ToString();

                switch (key)
                {
                    /// Sqeuentielle Ermittlung aller Primzahlen im bereich 1 bis 10000000
                    case "1":

                        Console.WriteLine("Primzahlen werden sequentiel ermittelt....");

                        Stopwatch swseq = Stopwatch.StartNew();
                        foreach (var i in Enumerable.Range(1, 10000000))
                        {
                            if (IsPrime(i))
                            {
                                //Console.WriteLine(i);
                            }
                        }

                        swseq.Stop();

                        Console.WriteLine("sequentiell fertig nach {0}ms", swseq.ElapsedMilliseconds);
                        Console.WriteLine("");

                        break;

                    /// Parallele Ermittlung aller Primzahlen im bereich 1 bis 10000000
                    case "2":

                        Console.WriteLine("Primzahlen werden parallel ermittelt...");
                        Stopwatch swparallel = Stopwatch.StartNew();
                        System.Threading.Tasks.Parallel.ForEach(Enumerable.Range(1, 10000000), body =>
                        {
                            IsPrime(body);
                        });
                        swparallel.Stop();
                        Console.WriteLine("parellel fertig nach {0}ms", swparallel.ElapsedMilliseconds);
                        Console.WriteLine("");

                        break;

                    /// PLINQ Ermittlung aller Primzahlen im bereich 1 bis 10000000
                    case "3":

                        Console.WriteLine("Primzahlen werden mit parallel LINQ ermittelt...");
                        Stopwatch swparallelLinq = Stopwatch.StartNew();
                        var primes = (from p in Enumerable.Range(1, 10000000).AsParallel()
                                           where IsPrime(p) == true
                                           select p).ToList();

                        swparallelLinq.Stop();
                        Console.WriteLine("parellel fertig nach {0}ms", swparallelLinq.ElapsedMilliseconds);
                        Console.WriteLine("");

                        break;

                    /// PLINQ Ermittlung aller Primzahlen im bereich 1 bis 10000000
                    case "4":

                        Console.WriteLine("Primzahlen werden mit parallel LINQ und beschränkter Anzahl an CPU-Kernen ermitteln...");
                        Console.Write("Anzahl CPU-Kerne: ");
                        ConsoleKeyInfo keyProcessor = Console.ReadKey(false);
                        Console.Write("\n");

                        int anzahlKey = System.Convert.ToInt32(keyProcessor.KeyChar.ToString());

                        Stopwatch swparallelLinqWithProcessor = Stopwatch.StartNew();
                        var primesWithProcessor = (from p in Enumerable.Range(1, 10000000)
                             .AsParallel()
                             .WithDegreeOfParallelism(anzahlKey)
                                      where IsPrime(p) == true
                                      select p).ToList();
                        Console.WriteLine("parellel fertig nach {0}ms", swparallelLinqWithProcessor.ElapsedMilliseconds);
                        Console.WriteLine("");
                        break;

                    case "5":
                        Console.WriteLine("Verarbeitung von drei Methoden die jeweils die Zahlen 1-10 durchlaufen...");
                        System.Threading.Tasks.Parallel.Invoke(TaskOne, TaskTwo, TaskThree);
                        Console.WriteLine("");
                        break;

                    case "6":

                        Console.WriteLine("Verwendung der Task-Klasse...");

                        ///Task #1 über new initialisiert und seperater Methode. Muss explizit gestartet werden.
                        System.Threading.Tasks.Task task1 = new System.Threading.Tasks.Task(DoSomething);
                        task1.Start();

                        Console.WriteLine("");

                        ///Task #2 über new initialisiert und LINQ-Methode. Muss explizit gestartet werden.
                        System.Threading.Tasks.Task task2 = new System.Threading.Tasks.Task(() =>
                        {
                            Console.WriteLine("Task #2 gestartet ...");
                            System.Threading.Thread.Sleep(3000);
                            Console.WriteLine("Task #2: fertig ...");
                        });
                        task2.Start();

                        Console.WriteLine("");

                        ///Task #3 über Task.Factory.StartNew initialisiert und LINQ-Methode. Wird automatisch gestartet.
                        System.Threading.Tasks.Task task3 = System.Threading.Tasks.Task.Factory.StartNew(() =>
                        {
                            Console.WriteLine("Task #3 gestartet ...");
                            System.Threading.Thread.Sleep(6000);
                            Console.WriteLine("Task #3: fertig ...");
                        });
                        System.Threading.Tasks.Task.WaitAll(task1, task2, task3);

                        break;

                    /// Abbruch der Anwendung.
                    default:

                        if (key == "7")
                        {
                            _Cancel = true;
                            Console.WriteLine("ENTER-Taste zum beenden der Anwendung...");
                        }
                        else
                        {
                            Console.WriteLine("'" + key + "' steht nicht zur Auswahl.");
                        }
                        break;
                }

            } while (!_Cancel);

            Console.Read();
        }
        private void FindDuplicateIndexes(object sender, EventArgs e)
        {
            try
            {
                var task = new System.Threading.Tasks.Task(() =>
                {
                    OutputPane.WriteMessageAndActivatePane("Finding Duplicate Indexes...");
                    var finder = new DuplicateIndexFinder();
                    finder.ShowDuplicateIndexes();
                    OutputPane.WriteMessageAndActivatePane("Finding Duplicate Indexes...done");
                });

                task.Start();

                if (task.Exception != null)
                    throw task.Exception;
            }
            catch (Exception ex)
            {
                OutputPane.WriteMessage("Error finding duplicate indexes: {0}", ex.Message);
            }
        }
        void ILayer.Render(Graphics g, Map map)
        {
            // We don't need to regenerate the tiles
            if (map.Envelope.Equals(_lastViewport) && _numPendingDownloads == 0)
            {
                g.DrawImage(_bitmap, Point.Empty);
                return;
            }

            // Create a backbuffer
            lock (_renderLock)
            {
                if (_bitmap == null || _bitmap.Size != map.Size)
                {
                    _bitmap = new Bitmap(map.Size.Width, map.Size.Height, PixelFormat.Format32bppArgb);
                    using (var tmpGraphics = Graphics.FromImage(_bitmap))
                        tmpGraphics.Clear(Color.Transparent);
                }
            }
            // Save the last viewport
            _lastViewport = map.Envelope;

            // Cancel old rendercycle
            ((ITileAsyncLayer)this).Cancel();

            var mapViewport = map.Envelope;
            var mapSize = map.Size;

            var mapColumnWidth = _cellSize.Width+_cellBuffer.Width;
            var mapColumnHeight = _cellSize.Height + _cellBuffer.Width;
            var columns = (int)Math.Ceiling((double) mapSize.Width/mapColumnWidth);
            var rows = (int) Math.Ceiling((double) mapSize.Height/mapColumnHeight);

            var renderMapSize = new Size(columns * _cellSize.Width + _cellBuffer.Width, 
                                         rows * _cellSize.Height + _cellBuffer.Height);
            var horizontalFactor = (double) renderMapSize.Width/mapSize.Width;
            var verticalFactor = (double) renderMapSize.Height/mapSize.Height;

            var diffX = 0.5d*(horizontalFactor*mapViewport.Width - mapViewport.Width);
            var diffY = 0.5d*(verticalFactor*mapViewport.Height-mapViewport.Height);

            var totalRenderMapViewport = mapViewport.Grow(diffX, diffY);
            var columnWidth = totalRenderMapViewport.Width/columns;
            var rowHeight = totalRenderMapViewport.Height/rows;

            var rmdx = (int)((mapSize.Width-renderMapSize.Width) * 0.5f);
            var rmdy = (int)((mapSize.Height - renderMapSize.Height) * 0.5f);

            var tileSize = Size.Add(_cellSize, Size.Add(_cellBuffer, _cellBuffer));

            var miny = totalRenderMapViewport.MinY;
            var pty = rmdy + renderMapSize.Height - tileSize.Height;

            for (var i = 0; i < rows; i ++)
            {
                var minx = totalRenderMapViewport.MinX;
                var ptx = rmdx;
                for (var j = 0; j < columns; j++)
                {
                    var tmpMap = new Map(_cellSize);
                    
                    tmpMap.Layers.Add(_baseLayer);
                    tmpMap.DisposeLayersOnDispose = false;
                    tmpMap.ZoomToBox(new Envelope(minx, minx + columnWidth, miny, miny + rowHeight));

                    var cancelToken = new System.Threading.CancellationTokenSource();
                    var token = cancelToken.Token;
                    var pt = new Point(ptx, pty);
                    var t = new System.Threading.Tasks.Task(delegate
                    {
                        if (token.IsCancellationRequested)
                            token.ThrowIfCancellationRequested();

                        var res = RenderCellOnThread(token, pt, tmpMap);
                        if (res)
                        {
                            System.Threading.Interlocked.Decrement(ref _numPendingDownloads);
                            var e = DownloadProgressChanged;
                            if (e != null)
                                e(_numPendingDownloads);
                        }

                    }, token);
                    var dt = new RenderTask {CancellationToken = cancelToken, Task = t};
                    lock (_currentTasks)
                    {
                        _currentTasks.Add(dt);
                        _numPendingDownloads++;
                    }
                    t.Start();
                    minx += columnWidth;
                    ptx += _cellSize.Width;
                }
                miny += rowHeight;
                pty -= _cellSize.Height;
            }
        }
        public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
        {
            log.Info("XenServer Health Check Service start to refresh uploading tasks");

            //We need to check if CIS can be accessed in current enviroment

            List<ServerInfo> servers = ServerListHelper.instance.GetServerList();
            foreach (ServerInfo server in servers)
            {
                if (server.task != null && (!server.task.IsCompleted || !server.task.IsCanceled || !server.task.IsFaulted))
                {
                    continue;
                }

                bool needReconnect = false;

                log.InfoFormat("Check server {0} with user {1}", server.HostName, server.UserName);

                Session session = new Session(server.HostName, 80);
                session.APIVersion = API_Version.LATEST;
                try
                {
                    session.login_with_password(server.UserName, server.Password, Helper.APIVersionString(API_Version.LATEST), Session.UserAgent);
                }
                catch (Exception exn)
                {
                    if (exn is Failure && ((Failure)exn).ErrorDescription[0] == Failure.HOST_IS_SLAVE)
                    {
                        string masterName = ((Failure)exn).ErrorDescription[1];
                        if (ServerListHelper.instance.UpdateServerCredential(server, masterName))
                        {
                            log.InfoFormat("Refresh credential to master {0} need refresh connection", masterName);
                            server.HostName = masterName;
                            needReconnect = true;
                        }
                        else
                        {
                            log.InfoFormat("Remove credential since it is the slave of master {0}", masterName);
                            if (session != null)
                                session.logout();
                            log.Error(exn, exn);
                            continue;
                        }
                    }
                    else
                    {
                        if (session != null)
                            session.logout();
                        log.Error(exn, exn);
                        continue;
                    }
                }

                try
                {
                    if (needReconnect)
                    {
                        if (session != null)
                            session.logout();
                        log.InfoFormat("Reconnect to master {0}", server.HostName);
                        session = new Session(server.HostName, 80);
                        session.APIVersion = API_Version.LATEST;
                        session.login_with_password(server.UserName, server.Password, Helper.APIVersionString(API_Version.LATEST), Session.UserAgent);
                    }
                    XenConnection connectionInfo = new XenConnection();
                    connectionInfo.Hostname = server.HostName;
                    connectionInfo.Username = server.UserName;
                    connectionInfo.Password = server.Password;
                    connectionInfo.LoadCache(session);
                    if (RequestUploadTask.Request(connectionInfo, session) || RequestUploadTask.OnDemandRequest(connectionInfo, session))
                    {
                        // Create a task to collect server status report and upload to CIS server
                        log.InfoFormat("Start to upload server status report for XenServer {0}", connectionInfo.Hostname);

                        XenServerHealthCheckBundleUpload upload = new XenServerHealthCheckBundleUpload(connectionInfo);
                        Action uploadAction = delegate()
                        {
                            upload.runUpload(cts.Token);
                        };
                        System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(uploadAction);
                        task.Start();

                        server.task = task;
                        ServerListHelper.instance.UpdateServerInfo(server);
                    }
                    session.logout();
                    session = null;
                }
                catch (Exception exn)
                {
                    if (session != null)
                        session.logout();
                    log.Error(exn, exn);
                }
            }
        }
Beispiel #59
0
        public void Play()
        {
            if (_channel != 0)
            {
                Bass.BASS_ChannelPlay(_channel, false);

                var task = new System.Threading.Tasks.Task(CheckDownloadState);
                task.Start();
            }
        }
        /// <summary>
        /// Create the initial database
        /// </summary>
        private void CreateDB()
        {
            var connection = new SqlCeConnection(this.path);

            try
            {
                var eng = new SqlCeEngine(this.path);
                var cleanup = new System.Threading.Tasks.Task(eng.Dispose);
                eng.CreateDatabase();
                cleanup.Start();
            }
            catch (Exception e)
            {
                EventLogging.WriteError(e);
            }

            connection.Open();
            var usersDB =
                new SqlCeCommand(
                    "CREATE TABLE Users_DB("
                    + "UserID int IDENTITY (100,1) NOT NULL UNIQUE, "
                    + "UserName nvarchar(128) NOT NULL UNIQUE, "
                    + "PassHash nvarchar(128) NOT NULL, "
                    + "Friends varbinary(5000), "
                    + "PRIMARY KEY (UserID));",
                    connection);
            usersDB.ExecuteNonQuery();
            usersDB.Dispose();
            connection.Dispose();
            connection.Close();
        }