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 #2
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();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 배경화면
            ChangeBackGround();
            Model.StaticVar.PodCastItemsPageBG = this;
            Model.StaticVar.FunScreen = this;
            Model.StaticVar.MusicPlayerHandler = this;

            CategoryName = (string)e.Parameter;
            ViewModel.MainViewModel.feedBoard.InitRefreshSet_Blogs(CategoryName);
            pageTitle.Text = CategoryName;

            var lists = ViewModel.MainViewModel.feedBoard.Blogs;
            LV_Channels.ItemsSource = lists;

            //LV_Channels.ItemsSource = ViewModel.MainViewModel.feedBoard.Blogs;
            // MainViewModel에서 Category 목록을 불러온다.
            //ViewModel.MainViewModel.feedBoard.InitRefreshSet_Blogs(CategoryName);

            // 펀스크린
//             funsScreenMain = new FunScreen.FunScreenMain();
//             funsScreenMain.Width = 1366;
//             funsScreenMain.Height = 768;
//             RootGrid.Children.Add(funsScreenMain);
//             ShowFunScreen();
            // 펀스크린을 시간에 맞추어 띄우기 위함
            onFunScreen = false;
            timer = 0;
            if (task != null)
            {
                task = new System.Threading.Tasks.Task(waitingTimeForFunScreen);
            }
        }
        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 #5
0
        Thread(IRunnable runnable, ThreadGroup grp, string name)
        {
            _thread = new System.Threading.Tasks.Task(InternalRun);

            this._runnable = runnable ?? this;
            _tgroup = grp ?? _defaultGroup;
            _tgroup.Add (this);
        }
		/// <summary>
		/// Create new instance of this class
		/// </summary>
		public EmbeddedBulkInsertOperation(DocumentDatabase database,BulkInsertOptions options)
		{
			this.options = options;
			queue = new BlockingCollection<JsonDocument>(options.BatchSize * 8);
			doBulkInsert = Task.Factory.StartNew(() =>
			{
				database.BulkInsert(options, YieldDocuments());
			});
		}
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            LogStack.Enqueue(new UriExchange { Exchange = exchange, UriDescriptor = endPointDescriptor });

            if (LogTask == null)
                LogTask = System.Threading.Tasks.Task.Factory.StartNew(ProcessLogQueue);

            return exchange;
        }
		/// <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 #9
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 #10
0
        public TaskAsync(ITask task, CancellationTokenSource cancellationTokenSource)
        {
            Contract.Requires(task != null);
            Contract.Requires(cancellationTokenSource != null);

            this.cancellationTokenSource = cancellationTokenSource;
            CancellationToken token = cancellationTokenSource.Token;
            sysTask = new System.Threading.Tasks.Task(() =>
            {
                token.ThrowIfCancellationRequested();
                task.Do();
            }, token);
        }
Beispiel #11
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");
        }
Beispiel #12
0
		private void ExecuteIndexingWorkOnMultipleThreads(List<IndexToWorkOn> indexesToWorkOn)
		{
			var threadingTasks = new ThreadingTask[indexesToWorkOn.Count];
			for (int i = 0; i < indexesToWorkOn.Count; i++)
			{
				var indexToWorkOn = indexesToWorkOn[i];
				threadingTasks[i] = new ThreadingTask(() =>
					transactionalStorage.Batch(actions =>
						IndexDocuments(actions, indexToWorkOn.IndexName, indexToWorkOn.LastIndexedEtag)));

				threadingTasks[i].Start();
			}
			ThreadingTask.WaitAll(threadingTasks);
		}
        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);
            }
        }
Beispiel #14
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;
 }
        /* 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);
            }
        }
        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);
            }
        }
        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 #18
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");
        }
Beispiel #19
0
        private void buttonStart_Click(object sender, EventArgs e)
        {
            this.update_ui("Start Clicked");

            cTokenSource = new System.Threading.CancellationTokenSource();
            var cToken = cTokenSource.Token;

            task = System.Threading.Tasks.Task<int>.Factory
                .StartNew( () => this.GenerateNumbers(cToken), cToken)
                .ContinueWith( t =>
                                   {
                                       this.ts_updateui("TASK: ContinueWith: DONE");
                                       return 1;
                                   })
                ;

            cToken.Register(FormTask.cancelNotification);
        }
        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 #21
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 #22
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();
 }
		protected override void OnStart(string[] args)
		{
			startTask = Task.Factory.StartNew(() =>
			{
				try
				{
					server = new RavenDbServer(new RavenConfiguration());
				}
				catch (Exception e)
				{
					EventLog.WriteEntry("RavenDB service failed to start because of an error" + Environment.NewLine + e, EventLogEntryType.Error);
					Stop();
				}
			});

			if(startTask.Wait(TimeSpan.FromSeconds(20)) == false)
			{
				EventLog.WriteEntry(
					"Startup for RavenDB service seems to be taking longer than usual, moving initialization to a background thread",
					EventLogEntryType.Warning);
			}

		}
        public void Dispose()
        {
            _WakePrevious = null;

            if (_AwaitingCLRTask != null) {
                _AwaitingCLRTask.TryCancelScope();
                _AwaitingCLRTask = null;
            }

            if (WakeCondition != null) {
                WakeCondition.Dispose();
                WakeCondition = null;
            }

            if (_Task != null) {
                _Task.Dispose();
                _Task = null;
            }

            if (_Future != null) {
                _Future.Dispose();
                _Future = null;
            }
        }
        protected override void RunInternal()
        {
#if DEBUGORDERING
            if (graph.NumberOfVertices != layering.Length)
            {
                throw new System.Exception("the layering does not correspond to the graph");
            }
            foreach (IntEdge e in graph.Edges)
            {
                if (layering[e.Source] - layering[e.Target] != 1)
                {
                    throw new System.Exception("the edge in the graph does not span exactly one layer:" + e);
                }
            }
#endif

#if PPC // Parallel -- susanlwo
            LayerArrays secondLayers      = null;
            Ordering    revOrdering       = null;
            System.Threading.Tasks.Task t = null;

            if (/*orderingMeasure.x>0 &&*/ tryReverse)
            {
                secondLayers = layerArrays.ReversedClone();

                revOrdering = new Ordering(properLayeredGraph.ReversedClone(), false, secondLayers, startOfVirtNodes, balanceVirtAndOrigNodes, this.hasCrossWeights, settings);

                // note: below we need to pass the CancelToken from this thread into the new thread, to make sure a previous thread from the ThreadPool's
                // thread static token (that may be in a cancelled state) is picked up.
                t = System.Threading.Tasks.Task.Factory.StartNew(() => revOrdering.Run(this.CancelToken));
            }

            Calculate();

            if (/*orderingMeasure.x>0 &&*/ tryReverse)
            {
                t.Wait();

                if (revOrdering.measure < measure)
                {
                    for (int j = 0; j < nOfLayers; j++)
                    {
                        secondLayers.Layers[j].CopyTo(layerArrays.Layers[nOfLayers - 1 - j], 0);
                    }

                    layerArrays.UpdateXFromLayers();
                }
            }
#else
            Calculate();

            if (/*orderingMeasure.x>0 &&*/ tryReverse)
            {
                LayerArrays secondLayers = layerArrays.ReversedClone();

                var revOrdering = new Ordering(properLayeredGraph.ReversedClone(), false, secondLayers, startOfVirtNodes, balanceVirtAndOrigNodes,
                                               hasCrossWeights, settings);

                revOrdering.Run();

                if (revOrdering.measure < measure)
                {
                    for (int j = 0; j < nOfLayers; j++)
                    {
                        secondLayers.Layers[j].CopyTo(layerArrays.Layers[nOfLayers - 1 - j], 0);
                    }

                    layerArrays.UpdateXFromLayers();
                }
            }
#endif
        }
Beispiel #26
0
 static public void Выполнить(System.Threading.Tasks.Task <TResult> задача, АсинхронныйВыполнитель выполнитель, object данныеКЗадаче)
 {
     задача.ContinueWith(t => {
         выполнитель.Оповестить(t, данныеКЗадаче);
     });
 }
Beispiel #27
0
 static async Task func()
 {
     await Task.Delay(100);
 }
Beispiel #28
0
        private static void Main(string[] args)
        {
            Task.Run(async() =>
            {
                // When debugging to kill all chrome on windows
                // taskkill / IM chrome.exe / F

                // synchronization
                var screenshotDone = new ManualResetEventSlim();

                // STEP 1 - Run Chrome
                var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());
                using (var chromeProcess = chromeProcessFactory.Create(new Uri("http://localhost:9222"), true))
                {
                    // STEP 2 - Create a debugging session
                    var sessionInfo          = (await chromeProcess.GetSessionInfo()).LastOrDefault();
                    var chromeSessionFactory = new ChromeSessionFactory();
                    var chromeSession        = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);

                    // STEP 3 - Send a command
                    //
                    // Here we are sending a commands to tell chrome to set the viewport size
                    // and navigate to the specified URL
                    await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                    {
                        Width  = ViewPortWidth,
                        Height = ViewPortHeight,
                        Scale  = 1
                    });

                    var navigateResponse = await chromeSession.SendAsync(new NavigateCommand
                    {
                        Url = "http://www.google.com"
                    });
                    Console.WriteLine("NavigateResponse: " + navigateResponse.Id);

                    // STEP 4 - Register for events (in this case, "Page" domain events)
                    // send an command to tell chrome to send us all Page events
                    // but we only subscribe to certain events in this session
                    var pageEnableResult = await chromeSession.SendAsync <Protocol.Chrome.Page.EnableCommand>();
                    Console.WriteLine("PageEnable: " + pageEnableResult.Id);

                    // THIS IS USEFUL FOR KNOWING WHEN THINGS GO WRONG
                    chromeSession.Subscribe <ErrorResponse>(errorFired => {
                        Console.WriteLine("#{0} ({1}) {2}", errorFired.Id, errorFired.Error.Code,
                                          errorFired.Error.Message);
                    });

                    chromeSession.Subscribe <LoadEventFiredEvent>(loadEventFired =>
                    {
                        // we cannot block in event handler, hence the task
                        Task.Run(async() =>
                        {
                            Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp);

                            var documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root
                                                 .NodeId;
                            var bodyNodeId =
                                (await chromeSession.SendAsync(new QuerySelectorCommand
                            {
                                NodeId = documentNodeId,
                                Selector = "body"
                            })).Result.NodeId;
                            var height = (await chromeSession.SendAsync(new GetBoxModelCommand {
                                NodeId = bodyNodeId
                            }))
                                         .Result.Model.Height;

                            await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                            {
                                Width  = ViewPortWidth,
                                Height = height,
                                Scale  = 1
                            });

                            Console.WriteLine("Taking screenshot");
                            var screenshot =
                                await chromeSession.SendAsync(new CaptureScreenshotCommand {
                                Format = "png"
                            });

                            var data = Convert.FromBase64String(screenshot.Result.Data);
                            File.WriteAllBytes("output.png", data);
                            Console.WriteLine("Screenshot stored");

                            // tell the main thread we are done
                            screenshotDone.Set();
                        });
                    });

                    // wait for screenshoting thread to (start and) finish
                    screenshotDone.Wait();

                    Console.WriteLine("Exiting ..");
                }
            }).Wait();
        }
Beispiel #29
0
 public override Task Execute()
 {
     return(Task.Run(async() => await UnzipFiles()));
 }
Beispiel #30
0
        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);
                }
            }
        }
        void GetRemoteDescription()
        {
            bool performPost = false;

            string address  = null;
            var    pathType = GetPathType();

            switch (pathType)
            {
            case PathType.GrasshopperDefinition:
            {
                if (Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) ||
                    File.Exists(Path))
                {
                    address     = Path;
                    performPost = true;
                }
            }
            break;

            case PathType.ComponentGuid:
                address = Servers.GetDescriptionUrl(Guid.Parse(Path));
                break;

            case PathType.Server:
                address = Path;
                break;

            case PathType.NonresponsiveUrl:
                break;
            }
            if (address == null)
            {
                return;
            }

            IoResponseSchema responseSchema = null;

            System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> responseTask = null;
            IDisposable contentToDispose = null;

            if (performPost)
            {
                string postUrl = Servers.GetDescriptionPostUrl();
                var    schema  = new Schema();
                if (Path.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    schema.Pointer = address;
                }
                else
                {
                    var bytes = System.IO.File.ReadAllBytes(address);
                    schema.Algo = Convert.ToBase64String(bytes);
                }
                string inputJson = JsonConvert.SerializeObject(schema);
                var    content   = new System.Net.Http.StringContent(inputJson, Encoding.UTF8, "application/json");
                responseTask     = HttpClient.PostAsync(postUrl, content);
                contentToDispose = content;
            }
            else
            {
                responseTask = HttpClient.GetAsync(address);
            }

            if (responseTask != null)
            {
                var responseMessage  = responseTask.Result;
                var remoteSolvedData = responseMessage.Content;
                var stringResult     = remoteSolvedData.ReadAsStringAsync().Result;
                if (!string.IsNullOrEmpty(stringResult))
                {
                    responseSchema = JsonConvert.DeserializeObject <Resthopper.IO.IoResponseSchema>(stringResult);
                    _cacheKey      = responseSchema.CacheKey;
                }
            }

            if (contentToDispose != null)
            {
                contentToDispose.Dispose();
            }

            if (responseSchema != null)
            {
                _description = responseSchema.Description;
                _customIcon  = null;
                if (!string.IsNullOrWhiteSpace(responseSchema.Icon))
                {
                    try
                    {
                        byte[] bytes = Convert.FromBase64String(responseSchema.Icon);
                        using (var ms = new MemoryStream(bytes))
                        {
                            _customIcon = new System.Drawing.Bitmap(ms);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                _inputParams  = new Dictionary <string, Tuple <InputParamSchema, IGH_Param> >();
                _outputParams = new Dictionary <string, IGH_Param>();
                foreach (var input in responseSchema.Inputs)
                {
                    string inputParamName = input.Name;
                    if (inputParamName.StartsWith("RH_IN:"))
                    {
                        var chunks = inputParamName.Split(new char[] { ':' });
                        inputParamName = chunks[chunks.Length - 1];
                    }
                    _inputParams[inputParamName] = Tuple.Create(input, ParamFromIoResponseSchema(input));
                }
                foreach (var output in responseSchema.Outputs)
                {
                    string outputParamName = output.Name;
                    if (outputParamName.StartsWith("RH_OUT:"))
                    {
                        var chunks = outputParamName.Split(new char[] { ':' });
                        outputParamName = chunks[chunks.Length - 1];
                    }
                    _outputParams[outputParamName] = ParamFromIoResponseSchema(output);
                }
            }
        }
Beispiel #32
0
 /// <summary>
 /// a delegate that is called when the remote service returns default (any response code not handled elsewhere).
 /// </summary>
 /// <param name="responseMessage">the raw response message as an System.Net.Http.HttpResponseMessage.</param>
 /// <param name="response">the body result as a <see cref="Nutanix.Powershell.Models.ITaskStatus" /> from the remote call</param>
 /// <returns>
 /// A <see cref="System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
 /// </returns>
 private async System.Threading.Tasks.Task onDefault(System.Net.Http.HttpResponseMessage responseMessage, System.Threading.Tasks.Task <Nutanix.Powershell.Models.ITaskStatus> response)
 {
     using ( NoSynchronizationContext )
     {
         // Error Response : default
         WriteError(new System.Management.Automation.ErrorRecord(new System.Exception($"The service encountered an unexpected result: {responseMessage.StatusCode}"), responseMessage.StatusCode.ToString(), System.Management.Automation.ErrorCategory.InvalidOperation, new { GetEntitiesRequest }));
     }
 }
Beispiel #33
0
 public bool IsLatestSpecifiedVersion(string version)
 {
     System.Threading.Tasks.Task <bool> task = _blobContainer.GetBlockBlobReference(version).ExistsAsync();
     task.Wait();
     return(task.Result);
 }
Beispiel #34
0
 public static System.Threading.Tasks.Task Unwrap(this System.Threading.Tasks.Task <System.Threading.Tasks.Task> task)
 {
     throw null;
 }
Beispiel #35
0
 public TaskCanceledException(System.Threading.Tasks.Task task)
 {
 }
Beispiel #36
0
        internal async Task VerifyDesignTimeInputsWatched(string[] designTimeInputs, string[] sharedDesignTimeInputs, string[] watchedFiles, string[] fileChangeNotificationsToSend, string[] fileChangeNotificationsExpected)
        {
            var fileChangeService = new IVsAsyncFileChangeExMock();

            using DesignTimeInputsFileWatcher watcher = CreateDesignTimeInputsFileWatcher(fileChangeService, out ProjectValueDataSource <DesignTimeInputs> source);

            watcher.AllowSourceBlockCompletion = true;

            // Send our input. DesignTimeInputs expects full file paths
            await source.SendAsync(new DesignTimeInputs(designTimeInputs.Select(f => f), sharedDesignTimeInputs.Select(f => f)));

            // The TaskCompletionSource is the thing we use to wait for the test to finish
            var finished = new TaskCompletionSource();

            int notificationCount = 0;
            // Create a block to receive the output
            var receiver = DataflowBlockSlim.CreateActionBlock <IProjectVersionedValue <string[]> >(val =>
            {
                foreach (string file in val.Value)
                {
                    Assert.Equal(fileChangeNotificationsExpected[notificationCount++], file);
                }

                // if we've seen every file, we're done
                if (notificationCount == fileChangeNotificationsExpected.Length)
                {
                    finished.SetResult();
                }
            });

            watcher.SourceBlock.LinkTo(receiver, DataflowOption.PropagateCompletion);

            // Send down our fake file changes
            watcher.FilesChanged((uint)fileChangeNotificationsToSend.Length, fileChangeNotificationsToSend, null);

            source.SourceBlock.Complete();

            await source.SourceBlock.Completion;

            watcher.SourceBlock.Complete();

            await watcher.SourceBlock.Completion;

            // The timeout here is annoying, but even though our test is "smart" and waits for data, unfortunately if the code breaks the test is more likely to hang than fail
            if (await Task.WhenAny(finished.Task, Task.Delay(TestTimeoutMillisecondsDelay)) != finished.Task)
            {
                throw new AssertActualExpectedException(fileChangeNotificationsExpected.Length, notificationCount, $"Timed out after {TestTimeoutMillisecondsDelay}ms");
            }

            // Observe the task in case of exceptions
            await finished.Task;

            // Dispose the watcher so that internal blocks complete (especially for tests that don't send any file changes)
            await watcher.DisposeAsync();

            // Make sure we watched all of the files we should
            Assert.Equal(watchedFiles, fileChangeService.UniqueFilesWatched);

            // Should clean up and unwatch everything
            Assert.Empty(fileChangeService.WatchedFiles.ToArray());
        }
Beispiel #37
0
                static async System.Threading.Tasks.Task <object> TaskCast <T>(System.Threading.Tasks.Task <T> task)
                {
                    var t = await task.ConfigureAwait(false);

                    return((object)t);
                }
Beispiel #38
0
        public void Start(string ip = "0.0.0.0", int port = 30300, int backlog = 10)
        {
            if (socket?.IsBound == true)
            {
                throw new Exception("已经运行");
            }

            var endpoint = new IPEndPoint(IPAddress.Parse(ip), port);

            socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(endpoint);
            //同一个时间点过来10个客户端,排队
            socket.Listen(backlog);

            _task = System.Threading.Tasks.Task.Run(() =>
            {
                while (socket.IsBound)
                {
                    try
                    {
                        //创建通信用的Socket
                        Socket tSocket = socket.Accept();


                        var connection = new TcpServerClientConnection(tSocket);
                        var session    = new ArduinoSession(connection, timeOut: 5000);

                        //var ss = session.GetFirmware();

                        dic.AddOrUpdate(connection.Name, f => session, (f1, f2) => session);

                        System.Threading.Tasks.Task.Run(() =>
                        {
                            try
                            {
                                AddArduinoSession?.Invoke(this, session);
                            }
                            catch (Exception) { }
                        });
                    }
                    catch (Exception)
                    {
                        break;
                    }
                }
            });
            _task2 = System.Threading.Tasks.Task.Run(async() =>
            {
                while (socket.IsBound)
                {
                    foreach (var item in dic.Values)
                    {
                        if (item.Connection.IsOpen)
                        {
                            try
                            {
                                _ = await item.GetProtocolVersionAsync();
                            }
                            catch (Exception ex)
                            {
                                item.Connection.Close();
                                dic.TryRemove(item.Connection.Name, out var _);
                                try
                                {
                                    RemoveArduinoSession?.Invoke(this, item, "心跳超时");
                                }
                                catch (Exception) { }
                            }
                        }
                        else
                        {
                            item.Connection.Close();
                            dic.TryRemove(item.Connection.Name, out var _);
                            try
                            {
                                RemoveArduinoSession?.Invoke(this, item, "连接断开");
                            }
                            catch (Exception) { }
                        }
                    }
                    System.Threading.Thread.Sleep(TimeSpan);
                }
            });
        }
Beispiel #39
0
        protected override bool _Run()
        {
            try
            {
                if (!Authentication.FileExists(SourceFile))
                {
                    throw new System.IO.IOException("File does not exist.");
                }

                CloudBlockBlob blob = Authentication.GetCloudBlockBlob(SourceFile, false);

                if (blob == null)
                {
                    throw new Exception("File does not exist or can not be reached: " + SourceFile);
                }

                string sData = null;
                byte[] bData = null;

                System.Threading.Tasks.Task <System.IO.Stream> streamResult = blob.OpenReadAsync();
                streamResult.Wait();

                switch (FileType)
                {
                case DataType.Binary:
                    using (System.IO.Stream s = streamResult.Result)
                    {
                        bData = new byte[s.Length];
                        s.Read(bData, 0, bData.Length);
                    }

                    break;

                case DataType.String:
                    using (System.IO.Stream s = streamResult.Result)
                    {
                        bData = new byte[s.Length];
                        s.Read(bData, 0, bData.Length);
                    }

                    sData = System.Text.Encoding.UTF8.GetString(bData, 0, bData.Length);
                    bData = null;
                    break;
                }

                switch (TargetContainer)
                {
                case ContainerType.InstructionSetContainer:

                    if (bData != null)
                    {
                        InstructionSet.InstructionSetContainer[ContainerDataKey] = bData;
                    }
                    else
                    {
                        InstructionSet.InstructionSetContainer[ContainerDataKey] = sData;
                    }

                    break;

                case ContainerType.Session:

                    if (bData != null)
                    {
                        STEM.Sys.State.Containers.Session[ContainerDataKey] = bData;
                    }
                    else
                    {
                        STEM.Sys.State.Containers.Session[ContainerDataKey] = sData;
                    }

                    break;

                case ContainerType.Cache:

                    if (bData != null)
                    {
                        STEM.Sys.State.Containers.Cache[ContainerDataKey] = bData;
                    }
                    else
                    {
                        STEM.Sys.State.Containers.Cache[ContainerDataKey] = sData;
                    }

                    break;
                }
            }
            catch (AggregateException ex)
            {
                foreach (Exception e in ex.InnerExceptions)
                {
                    AppendToMessage(e.Message);
                    Exceptions.Add(e);
                }
            }
            catch (Exception ex)
            {
                AppendToMessage(ex.Message);
                Exceptions.Add(ex);
            }

            return(Exceptions.Count == 0);
        }
Beispiel #40
0
        /// <summary>
        /// Main method for launching BuildXL task
        /// </summary>
        /// <returns>Whether the task is executed successfully or not</returns>
        public override bool Execute()
        {
            if (Environment.GetEnvironmentVariable("DominoTaskDebugOnStart") == "1")
            {
                Debugger.Launch();
            }

            // Initializing logger
            var logger = new BuildXLTaskLogger(Log);

            logger.LogMessage(
                string.Format(CultureInfo.InvariantCulture, "Building value {0} with qualifier {1}", DominoValue, Configuration));

            TplTask waitForDominoExitTask = null;

            try
            {
                EventWaitHandle hostEvent;
                if (!string.IsNullOrEmpty(DominoHostEventName) && EventWaitHandle.TryOpenExisting(DominoHostEventName, EventWaitHandleRights.Synchronize, out hostEvent))
                {
                    waitForDominoExitTask = TplTask.Run(() =>
                    {
                        using (hostEvent)
                        {
                            // The hostEvent will be triggered if the BuildXL process exits.
                            // The cancellation token will be triggered if the task is cancelled or completes
                            WaitHandle.WaitAny(new[] { m_cancellationTokenSource.Token.WaitHandle, hostEvent });
                            if (!m_cancellationTokenSource.Token.IsCancellationRequested)
                            {
                                logger.LogError("BuildXL process exited before completing task.");
                                m_cancellationTokenSource.Cancel();
                            }
                        }
                    });
                }
                else
                {
                    logger.LogError(Strings.HostEventNotFound, DominoHostEventName);
                    return(false);
                }

                try
                {
                    Stopwatch timer = Stopwatch.StartNew();
                    using (EventWaitHandle success = new EventWaitHandle(false, EventResetMode.ManualReset, DominoValue.ToUpperInvariant() + Port + Scheduler.Scheduler.IdeSuccessPrefix))
                        using (EventWaitHandle failure = new EventWaitHandle(false, EventResetMode.ManualReset, DominoValue.ToUpperInvariant() + Port + Scheduler.Scheduler.IdeFailurePrefix))
                        {
                            while (timer.Elapsed < MaxProjectBuildTime)
                            {
                                if (success.WaitOne(EventPollingFrequency))
                                {
                                    break;
                                }

                                if (failure.WaitOne(EventPollingFrequency))
                                {
                                    logger.LogError(string.Format(CultureInfo.InvariantCulture, Strings.FailureMessage, DominoValue));
                                    return(false);
                                }

                                if (m_cancellationTokenSource.IsCancellationRequested)
                                {
                                    return(false);
                                }
                            }
                        }
                }
                catch (Exception exception)
                {
                    logger.LogError("Failed to execute BuildXL");
                    logger.LogErrorFromException(exception);
                    return(false);
                }

                logger.LogMessage(string.Format(CultureInfo.InvariantCulture, Strings.SuccessMessage, DominoValue));
                return(true);
            }
            finally
            {
                m_cancellationTokenSource.Cancel();
                if (waitForDominoExitTask != null)
                {
                    waitForDominoExitTask.Wait();
                }
            }
        }
Beispiel #41
0
 /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary>
 /// <param name="responseMessage">the raw response message as an System.Net.Http.HttpResponseMessage.</param>
 /// <param name="response">the body result as a <see cref="Nutanix.Powershell.Models.ITaskListIntentResponse" /> from the remote call</param>
 /// <returns>
 /// A <see cref="System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
 /// </returns>
 private async System.Threading.Tasks.Task onOK(System.Net.Http.HttpResponseMessage responseMessage, System.Threading.Tasks.Task <Nutanix.Powershell.Models.ITaskListIntentResponse> response)
 {
     using ( NoSynchronizationContext )
     {
         // onOK - response for 200 / application/json
         // (await response) // should be Nutanix.Powershell.Models.ITaskListIntentResponse
         WriteObject(await response);
     }
 }
 public static global::Windows.Foundation.IAsyncAction AsAsyncAction(this System.Threading.Tasks.Task source)
 {
     throw null;
 }
Beispiel #43
0
        protected override void OnResume()
        {
            base.OnResume();
            try
            {
                if (TAGPage.write_nfc == true)
                {
                    //PopupNavigation.Instance.PopAsync();
                    PopupNavigation.Instance.PushAsync(new ConfigStikerPage());
                    int user_id = 0;
                    if (NfcAdapter.ActionNdefDiscovered.Equals(Intent.Action))
                    {
                        //Get the NFC ID
                        var myTag = Intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);

                        var msg    = (NdefMessage)myTag[0];
                        var record = msg.GetRecords()[0];
                        //If the NFC Card ID is not null
                        if (record != null)
                        {
                            if (record.Tnf == NdefRecord.TnfWellKnown) // The data is defined by the Record Type Definition (RTD) specification available from http://members.nfc-forum.org/specs/spec_list/
                            {
                                // Get the transfered data
                                var    data   = Encoding.ASCII.GetString(record.GetPayload());
                                string result = data.Substring(1);

                                string[] variables     = result.Split('=');
                                string[] depura_userid = variables[1].Split('&');
                                user_id = Convert.ToInt32(depura_userid[0]);
                            }
                        }
                    }

                    string dominio = "boxweb.azurewebsites.net/";
                    string user    = MainViewModel.GetInstance().User.UserId.ToString();
                    string tag_id  = "";
                    if (user_id == Convert.ToInt32(user) || 0 == user_id)
                    {
                        string url = dominio + "index3.aspx?user_id=" + user + "&tag_id=" + tag_id;
                        //http://localhost:58951/index.aspx?user_id=7
                        var tag = Intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
                        if (tag != null)
                        {
                            Ndef ndef = Ndef.Get(tag);
                            if (ndef != null && ndef.IsWritable)
                            {
                                /*var payload = Encoding.ASCII.GetBytes(url);
                                 * var mimeBytes = Encoding.ASCII.GetBytes("text/html");
                                 * var record = new NdefRecord(NdefRecord.TnfWellKnown, mimeBytes, new byte[0], payload);
                                 * var ndefMessage = new NdefMessage(new[] { record });
                                 * ndef.Connect();
                                 * ndef.WriteNdefMessage(ndefMessage);
                                 * ndef.Close();*/

                                ndef.Connect();
                                NdefRecord mimeRecord = NdefRecord.CreateUri("http://" + url);
                                ndef.WriteNdefMessage(new NdefMessage(mimeRecord));
                                ndef.Close();
                            }
                        }
                        TAGPage.write_nfc = false;

                        var duration = TimeSpan.FromMilliseconds(2000);
                        Vibration.Vibrate(duration);
                    }
                    else
                    {
                        System.Threading.Tasks.Task task = App.DisplayAlertAsync("¡Este Tag esta vinculado con otro usuario!");
                    }
                    PopupNavigation.Instance.PopAsync();
                    PopupNavigation.Instance.PushAsync(new Stickerconfig());
                    Thread.Sleep(4000);
                    PopupNavigation.Instance.PopAsync();
                }
                else
                {
                    if (NfcAdapter.ActionNdefDiscovered.Equals(Intent.Action))
                    {
                        //Get the NFC ID
                        var myTag = Intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);

                        var msg    = (NdefMessage)myTag[0];
                        var record = msg.GetRecords()[0];
                        //If the NFC Card ID is not null
                        if (record != null)
                        {
                            if (record.Tnf == NdefRecord.TnfWellKnown) // The data is defined by the Record Type Definition (RTD) specification available from http://members.nfc-forum.org/specs/spec_list/
                            {
                                // Get the transfered data
                                var    data   = Encoding.ASCII.GetString(record.GetPayload());
                                string result = data.Substring(1);

                                string[] variables     = result.Split('=');
                                string[] depura_userid = variables[1].Split('&');
                                string   tag_id        = variables[2];
                                string   user_id       = depura_userid[0];

                                Imprime_box.Consulta_user(user_id, tag_id);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #44
0
        private static async Task WriteMessageCore(ValueTask writeMessageTask)
        {
            await writeMessageTask.ConfigureAwait(false);

            GrpcEventSource.Log.MessageSent();
        }
Beispiel #45
0
 /// <summary>
 /// a delegate that is called when the remote service returns default (any response code not handled elsewhere).
 /// </summary>
 /// <param name="responseMessage">the raw response message as an System.Net.Http.HttpResponseMessage.</param>
 /// <param name="response">the body result as a <see cref="Microsoft.Azure.AzConfig.Models.IError" /> from the remote call</param>
 /// <returns>
 /// A <see cref="System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
 /// </returns>
 private async System.Threading.Tasks.Task onDefault(System.Net.Http.HttpResponseMessage responseMessage, System.Threading.Tasks.Task <Microsoft.Azure.AzConfig.Models.IError> response)
 {
     using ( NoSynchronizationContext )
     {
         // Error Response : default
         var code    = (await response).ErrorProperty?.Code;;
         var message = (await response).ErrorProperty?.Message;;
         if ((null == code || null == message))
         {
             // Unrecognized Response. Create an error record based on what we have.
             WriteError(new System.Management.Automation.ErrorRecord(new System.Exception($"The service encountered an unexpected result: {responseMessage.StatusCode}\nBody: {await responseMessage.Content.ReadAsStringAsync()}"), responseMessage.StatusCode.ToString(), System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId, ResourceGroupName, ConfigStoreName, ConfigStoreUpdateParametersBody }));
         }
         else
         {
             WriteError(new System.Management.Automation.ErrorRecord(new System.Exception($"[{code}] : {message}"), code?.ToString(), System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId, ResourceGroupName, ConfigStoreName, ConfigStoreUpdateParametersBody }));
         }
     }
 }
        /// <summary>
        /// Open server line using PipesProvider that will send answer backward to cliend by dirrect line.
        /// Line will established relative to the data shared by client query.
        ///
        /// Using this method you frovide uniform revers connection and not need to create
        /// a transmission line by yourself.
        ///
        /// Recommended to use this methos by default dor duplex connection between sever and clients.
        /// </summary>
        /// <param name="answer">Qury that will sent by server to target client.</param>
        /// <param name="entryQuery">Query that was recived from client.
        /// Method will detect core part and establish backward connection.</param>
        /// <returns></returns>
        public static bool SendAnswerViaPP(UniformQueries.Query answer, UniformQueries.Query entryQuery)
        {
            // Instiniate primitive server to provide loop.
            BaseServer server = new BaseServer();

            // Try to compute bacward domaint to contact with client.
            if (!UniformQueries.QueryPart.TryGetBackwardDomain(entryQuery, out string domain))
            {
                Console.WriteLine("ERROR (BSSA0): Unable to buid backward domain. QUERY: " + entryQuery.ToString());
                return(false);
            }

            // Set fields.
            server.pipeName = domain;

            // Subscribe or waiting delegate on server loop event.
            ServerAPI.TransmissionToProcessing += InitationCallback;


            // Starting server loop.
            server.StartServerThread(
                "SERVER ANSWER " + domain, server,
                ThreadingServerLoop_PP_Output);

            // Skip line
            Console.WriteLine();
            return(true);

            // Create delegate that will set our answer message to processing
            // when transmission line would established.
            void InitationCallback(BaseServerTransmissionController tc)
            {
                if (tc is ServerToClientTransmissionController transmissionController)
                {
                    // Target callback.
                    if (transmissionController.PipeName == server.pipeName)
                    {
                        // Unsubscribe.
                        ServerAPI.TransmissionToProcessing -= InitationCallback;

                        bool encryptingComplete = false;

                        // Encrypting data in async operation.
                        var encryptionAgent = new System.Threading.Tasks.Task(async delegate()
                        {
                            // Try to encrypt answer if required.
                            await PipesProvider.Security.Encryption.EnctyptionOperatorsHandler.
                            TryToEncryptByReceivedQueryAsync(entryQuery, answer, CancellationToken.None);

                            encryptingComplete = true;
                        });

                        try
                        {
                            encryptionAgent.Start();
                        }
                        catch { }

                        // Wait for encryption
                        while (!encryptingComplete)
                        {
                            Thread.Sleep(5);
                        }

                        // Set answer query as target for processing,
                        transmissionController.ProcessingQuery = answer;

                        // Log.
                        Console.WriteLine(@"{0}: Processing query changed on: " + @answer.ToString(), @transmissionController.PipeName);
                    }
                }
                else // Incorrect type.
                {
                    // Close transmisssion.
                    tc.SetStoped();

                    // Log.
                    Console.WriteLine("{0}: ERROR Incorrect transmisssion controller. Required \"ServerAnswerTransmissionController\"", tc.PipeName);
                }
            }
        }
Beispiel #47
0
 /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary>
 /// <param name="responseMessage">the raw response message as an System.Net.Http.HttpResponseMessage.</param>
 /// <param name="response">the body result as a <see cref="Microsoft.Azure.AzConfig.Models.IConfigurationStore" /> from the
 /// remote call</param>
 /// <returns>
 /// A <see cref="System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
 /// </returns>
 private async System.Threading.Tasks.Task onOK(System.Net.Http.HttpResponseMessage responseMessage, System.Threading.Tasks.Task <Microsoft.Azure.AzConfig.Models.IConfigurationStore> response)
 {
     using ( NoSynchronizationContext )
     {
         // onOK - response for 200 / application/json
         // (await response) // should be Microsoft.Azure.AzConfig.Models.IConfigurationStore
         WriteObject(await response);
     }
 }
 private static async void DoNotWait(Task task)
 {
     await task;
 }
Beispiel #49
0
        /// <summary>
        /// Renders the layer
        /// </summary>
        /// <param name="graphics">Graphics object reference</param>
        /// <param name="map">Map which is rendered</param>
        public override void Render(Graphics graphics, Map map)
        {
            var bbox = map.Envelope;
            var extent = new Extent(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            int level = BruTile.Utilities.GetNearestLevel(_source.Schema.Resolutions, map.PixelSize);
            var tiles = _source.Schema.GetTilesInView(extent, level);

            //Abort previous running Threads
            Cancel();

            using (var ia = new ImageAttributes())
            {
                if (!_transparentColor.IsEmpty)
                    ia.SetColorKey(_transparentColor, _transparentColor);
#if !PocketPC
                ia.SetWrapMode(WrapMode.TileFlipXY);
#endif
                foreach (TileInfo info in tiles)
                {
                    if (_bitmaps.Find(info.Index) != null)
                    {
                        //draws directly the bitmap
                        var bb = new Envelope(new Coordinate(info.Extent.MinX, info.Extent.MinY),
                                              new Coordinate(info.Extent.MaxX, info.Extent.MaxY));
                        HandleMapNewTileAvaliable(map, graphics, bb, _bitmaps.Find(info.Index), _source.Schema.Width,
                                                  _source.Schema.Height, ia);
                    }
                    else if (_fileCache != null && _fileCache.Exists(info.Index))
                    {

                        Bitmap img = GetImageFromFileCache(info) as Bitmap;
                        _bitmaps.Add(info.Index, img);

                        //draws directly the bitmap
                        var btExtent = info.Extent;
                        var bb = new Envelope(new Coordinate(btExtent.MinX, btExtent.MinY),
                                              new Coordinate(btExtent.MaxX, btExtent.MaxY));
                        HandleMapNewTileAvaliable(map, graphics, bb, _bitmaps.Find(info.Index), _source.Schema.Width,
                                                  _source.Schema.Height, ia);
                    }
                    else
                    {
                        var cancelToken = new CancellationTokenSource();
                        var token = cancelToken.Token;
                        var l_info = info;
                        if (Logger.IsDebugEnabled)
                            Logger.DebugFormat("Starting new Task to download tile {0},{1},{2}", info.Index.Level, info.Index.Col, info.Index.Row);
                        var t = new System.Threading.Tasks.Task(delegate
                        {
                            if (token.IsCancellationRequested)
                                token.ThrowIfCancellationRequested();

                            if (Logger.IsDebugEnabled)
                                Logger.DebugFormat("Task started for download of tile {0},{1},{2}", info.Index.Level, info.Index.Col, info.Index.Row);

                            var res = GetTileOnThread(token, _source.Provider, l_info, _bitmaps, true);
                            if (res)
                            {
                                Interlocked.Decrement(ref _numPendingDownloads);
                                var e = DownloadProgressChanged;
                                if (e != null)
                                    e(_numPendingDownloads);
                            }

                        }, token);
                        var dt = new DownloadTask() { CancellationToken = cancelToken, Task = t };
                        lock (_currentTasks)
                        {
                            _currentTasks.Add(dt);
                            _numPendingDownloads++;
                        }
                        t.Start();
                    }
                }
            }

        }
Beispiel #50
0
 protected override void OnStartSearch()
 {
     Task.WaitAll(SearchAsync());
 }
 public static global::Windows.Foundation.IAsyncOperation <TResult> AsAsyncOperation <TResult>(this System.Threading.Tasks.Task <TResult> source)
 {
     throw null;
 }
Beispiel #52
0
 public static System.Threading.Tasks.Task <TResult> Unwrap <TResult>(this System.Threading.Tasks.Task <System.Threading.Tasks.Task <TResult> > task)
 {
     throw null;
 }
        public override async System.Threading.Tasks.Task RefreshAsync(ModelRefreshType refreshType, bool showTrackedOperation = true)
        {
            if (refreshType.HasFlag(ModelRefreshType.Basic))
            {
                try
                {
                    //await this.Task.RefreshAsync(); TODO: This doesnt' work right now due to bug with OM, so must do GetTask directly
                    Messenger.Default.Send(new UpdateWaitSpinnerMessage(WaitSpinnerPanel.UpperRight, true));

                    System.Threading.Tasks.Task <CloudTask> asyncTask = MainViewModel.dataProvider.Service.GetTaskAsync(
                        this.ParentJob.Id,
                        this.Task.Id,
                        OptionsModel.Instance.ListDetailLevel);

                    if (showTrackedOperation)
                    {
                        AsyncOperationTracker.Instance.AddTrackedOperation(new AsyncOperationModel(
                                                                               asyncTask,
                                                                               new TaskOperation(TaskOperation.Refresh, this.ParentJob.Id, this.Task.Id)));
                    }
                    else
                    {
                        AsyncOperationTracker.Instance.AddTrackedInternalOperation(asyncTask);
                    }

                    this.Task            = await asyncTask;
                    this.LastUpdatedTime = DateTime.UtcNow;

                    //
                    // Fire property change events for this models properties
                    //
                    this.FireChangesOnRefresh(ModelRefreshType.Basic);
                }
                catch (Exception e)
                {
                    this.HandleException(e);
                }
                finally
                {
                    Messenger.Default.Send(new UpdateWaitSpinnerMessage(WaitSpinnerPanel.UpperRight, false));
                }
            }

            if (refreshType.HasFlag(ModelRefreshType.Children))
            {
                try
                {
                    Messenger.Default.Send(new UpdateWaitSpinnerMessage(WaitSpinnerPanel.LowerRight, true));
                    //Set this before the children load so that on revisit we know we have loaded the children (or are in the process)
                    this.HasLoadedChildren = true;
                    try
                    {
                        System.Threading.Tasks.Task <List <NodeFile> > asyncTask = this.ListTaskFilesAsync();
                        AsyncOperationTracker.Instance.AddTrackedOperation(new AsyncOperationModel(
                                                                               asyncTask,
                                                                               new TaskOperation(TaskOperation.ListFiles, this.ParentJob.Id, this.Task.Id)));

                        this.OutputFiles = await asyncTask;
                    }
                    catch (Exception)
                    {
                        this.HasLoadedChildren = false; //On exception, we failed to load children so try again next time
                        //Swallow the exception to stop popups from occuring for every bad VM
                    }

                    this.FireChangesOnRefresh(ModelRefreshType.Children);
                }
                catch (Exception e)
                {
                    this.HasLoadedChildren = false; //On exception, we failed to load children so try again next time
                    this.HandleException(e);
                }
                finally
                {
                    Messenger.Default.Send(new UpdateWaitSpinnerMessage(WaitSpinnerPanel.LowerRight, false));
                }
            }
        }
Beispiel #54
0
        public static void UnpackContinuation (Action continuation, out tTask task) {
            var stateMachine = TryGetStateMachineForDebugger(continuation);
            if (stateMachine == null)
                throw new Exception("Could not extract state machine from continuation");

            var machine = stateMachine.Target;
            var tMachine = machine.GetType();
            TExtractTaskFromStateMachine extractor;

            lock (ExtractorCache)
            if (!ExtractorCache.TryGetValue(tMachine, out extractor))
                ExtractorCache.Add(tMachine, extractor = CreateExtractor(tMachine));

            task = extractor(machine);
        }
 protected override void OnStart(string[] args)
 {
   appTask = app.Start();
 }
Beispiel #56
0
 public static bool TryGet (tTask task, out CancellationScope result) {
     return ScopeRegistry.TryGetValue(task, out result);
 }
Beispiel #57
0
 public static void Set (tTask task, CancellationScope scope) {
     ScopeRegistry.Add(task, scope);
 }
Beispiel #58
0
		private void TimerCallback(object state)
		{
			if (currentTask != null)
				return;

			lock (this)
			{
				if (currentTask != null)
					return;
				currentTask = Task.Factory.StartNew(() =>
				{
					var documentDatabase = Database;
					if (documentDatabase == null)
						return;
					using (LogContext.WithDatabase(documentDatabase.Name))
					{
						try
						{
							var localBackupConfigs = backupConfigs;
							var localBackupStatus = backupStatus;
							if (localBackupConfigs == null)
								return;

							var databaseStatistics = documentDatabase.Statistics;
							// No-op if nothing has changed
							if (databaseStatistics.LastDocEtag == localBackupStatus.LastDocsEtag &&
								databaseStatistics.LastAttachmentEtag == localBackupStatus.LastAttachmentsEtag)
							{
								return;
							}

							var backupPath = localBackupConfigs.LocalFolderName ??
											 Path.Combine(documentDatabase.Configuration.DataDirectory, "PeriodicBackup-Temp");
							var options = new SmugglerOptions
							{
								BackupPath = backupPath,
								LastDocsEtag = localBackupStatus.LastDocsEtag,
								LastAttachmentEtag = localBackupStatus.LastAttachmentsEtag
							};
							var dd = new DataDumper(documentDatabase, options);
							var filePath = dd.ExportData(null, true);

							// No-op if nothing has changed
							if (options.LastDocsEtag == localBackupStatus.LastDocsEtag &&
								options.LastAttachmentEtag == localBackupStatus.LastAttachmentsEtag)
							{
								logger.Info("Periodic backup returned prematurely, nothing has changed since last backup");
								return;
							}

							UploadToServer(filePath, localBackupConfigs);

							localBackupStatus.LastAttachmentsEtag = options.LastAttachmentEtag;
							localBackupStatus.LastDocsEtag = options.LastDocsEtag;

							var ravenJObject = RavenJObject.FromObject(localBackupStatus);
							ravenJObject.Remove("Id");
							var putResult = documentDatabase.Put(PeriodicBackupStatus.RavenDocumentKey, null, ravenJObject,
														 new RavenJObject(), null);

							// this result in backupStatus being refreshed
							localBackupStatus = backupStatus;
							if (localBackupStatus != null)
							{
								if (Etag.Increment(localBackupStatus.LastDocsEtag, 1) == putResult.ETag) // the last etag is with just us
									localBackupStatus.LastDocsEtag = putResult.ETag; // so we can skip it for the next time
							}
						}
						catch (ObjectDisposedException)
						{
							// shutting down, probably
						}
						catch (Exception e)
						{
							logger.ErrorException("Error when performing periodic backup", e);
							Database.AddAlert(new Alert
							{
								AlertLevel = AlertLevel.Error,
								CreatedAt = SystemTime.UtcNow,
								Message = e.Message,
								Title = "Error in Periodic Backup",
								Exception = e.ToString(),
								UniqueKey = "Periodic Backup Error",
							});
						}
					}
				})
				.ContinueWith(_ =>
				{
					currentTask = null;
				});
			}
		}
Beispiel #59
0
        async System.Threading.Tasks.Task
#endif
        LoadModules(IEnumerable <string> filenames)
        /// <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();
        }