Наследование: ObjectInteraction
Пример #1
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="viewModel"></param>
 public CharacterEditor(ViewModel viewModel, Dispatcher uiDispatcher, List<Unit> newRoster = null)
 {
     _uiDispatcher = uiDispatcher;
     DataContext = this;
     Test = "dhsfuifbvosfbo";
     WindowStyle = WindowStyle.ToolWindow;
     ViewModel = viewModel;
     //  Faction unit lists
     Factions = ViewModel.Factions;
     if (newRoster == null)
     {
         Factions[1].Units.Add(new Unit(1, BodyType.Enclave, WeaponType.SMG, Stance.Stand, 10, 10, 10, 10, 10, -1, -1, "James"));
         Factions[2].Units.Add(new Unit(2, BodyType.TribalFemale, WeaponType.Club, Stance.Stand, 10, 10, 10, 10, 10, -1, -1, "John"));
     }
     else
     {
         foreach (Unit u in newRoster)
         {
             Factions[u.OwnerID].Units.Add(u);
         }
     }
     InitializeComponent();
     body.ItemsSource = Enum.GetValues(typeof (BodyType));
     weapon.ItemsSource = Enum.GetValues(typeof (WeaponType));
     
 }
        public void AndItShouldNotDoThat()
        {
            var handlerActivator = new HandlerActivatorForTesting();
            var pipelineInspector = new TrivialPipelineInspector();
            var handleDeferredMessage = Mock<IHandleDeferredMessage>();
            var dispatcher = new Dispatcher(new InMemorySagaPersister(),
                                        handlerActivator,
                                        new InMemorySubscriptionStorage(),
                                        pipelineInspector,
                                        handleDeferredMessage);

            dispatcher.Dispatch(new TimeoutReply
            {
                CorrelationId = TimeoutReplyHandler.TimeoutReplySecretCorrelationId,
                CustomData = TimeoutReplyHandler.Serialize(new Message { Id = "1" })
            });

            dispatcher.Dispatch(new TimeoutReply
            {
                CustomData = TimeoutReplyHandler.Serialize(new Message { Id = "2" })
            });

            handleDeferredMessage.AssertWasCalled(x => x.Dispatch(Arg<Message>.Is.Anything), x => x.Repeat.Once());
            handleDeferredMessage.AssertWasCalled(x => x.Dispatch(Arg<Message>.Matches(y => y.Id == "1")));
        }
Пример #3
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public ViewModel(Dispatcher uiDispatcher, string baseContentDir, Isometry iso)
        {
            //  Reference to the UIDispatcher for thread-safe collection manipulation
            _uiDispatcher = uiDispatcher;

            Factions = new ObservableCollection<FactionList> { new FactionList("AI"), new FactionList("Player 1"), new FactionList("Player 2") };
            
            //  Map setup
            Map = new MapDefinition(new ZTile(baseContentDir + "tiles\\Generic Tiles\\Generic Floors\\DirtSand\\Waste_Floor_Gravel_SandDirtCentre_F_1_NE.til"), iso, baseContentDir);
            MapCanvas = new MapCanvas(Map, uiDispatcher, baseContentDir + "tiles\\", iso, Factions);
            _useAltEditLayer = false;


            //  Create the available TileSets and collection views
            TileSets = new Dictionary<string, ObservableCollection<ZTile>>();
            TileSetViews = new Dictionary<string, ListCollectionView>();
            foreach (var di in new DirectoryInfo(baseContentDir + "tiles\\").GetDirectories())
            {
                TileSets.Add(di.Name, new ObservableCollection<ZTile>());
                TileSetViews.Add(di.Name, new ListCollectionView(TileSets[di.Name]));
            }

            //  Start a new thread to load in the tile images
            ThreadPool.QueueUserWorkItem(GetWholeTileSet, baseContentDir + "tiles\\");
        }
        public LightClawSynchronizationContext(Dispatcher dispatcher, DispatcherPriority priority)
        {
            Contract.Requires<ArgumentNullException>(dispatcher != null);

            this.dispatcher = dispatcher;
            this.priority = priority;
        }
Пример #5
0
 public static void Attach()
 {
     AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
     dispatcher = Dispatcher.CurrentDispatcher;
     dispatcher.UnhandledException += CurrentDispatcher_UnhandledException;
     TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
 }
Пример #6
0
 public Dispatcher()
 {
     Debug.Assert(_instance == null);
     _instance = this;
     _thread = new Thread(run);
     _thread.Start();
 }
		public SoftRigidDynamicsWorld(Dispatcher dispatcher, BroadphaseInterface pairCache,
			ConstraintSolver constraintSolver, CollisionConfiguration collisionConfiguration,
			SoftBodySolver softBodySolver)
            : base(IntPtr.Zero)
		{
            if (softBodySolver != null) {
                _softBodySolver = softBodySolver;
                _ownsSolver = false;
            } else {
                _softBodySolver = new DefaultSoftBodySolver();
                _ownsSolver = true;
            }

            _native = btSoftRigidDynamicsWorld_new2(dispatcher._native, pairCache._native,
                (constraintSolver != null) ? constraintSolver._native : IntPtr.Zero,
                collisionConfiguration._native, _softBodySolver._native);

            _collisionObjectArray = new AlignedCollisionObjectArray(btCollisionWorld_getCollisionObjectArray(_native), this);

            _broadphase = pairCache;
			_constraintSolver = constraintSolver;
			_dispatcher = dispatcher;
            _worldInfo = new SoftBodyWorldInfo(btSoftRigidDynamicsWorld_getWorldInfo(_native), true);
            _worldInfo.Dispatcher = dispatcher;
            _worldInfo.Broadphase = pairCache;
		}
Пример #8
0
        public void ShouldExecuteFunction()
        {
            var engine = new Dispatcher<string>();
            engine.Execute(new OperationDuplex<string>(_function.Object), "Red");

            _function.Verify((f)=>f.Execute("Red"), Times.Exactly(3));
        }
Пример #9
0
        public void AndItShouldNotDoThat()
        {
            var handlerActivator = new HandlerActivatorForTesting();
            var pipelineInspector = new TrivialPipelineInspector();
            var handleDeferredMessage = new MockDeferredMessageHandler();
            var dispatcher = new Dispatcher(new InMemorySagaPersister(),
                                        handlerActivator,
                                        new InMemorySubscriptionStorage(),
                                        pipelineInspector,
                                        handleDeferredMessage,
                                        null);

            dispatcher.Dispatch(new TimeoutReply
            {
                CorrelationId = TimeoutReplyHandler.TimeoutReplySecretCorrelationId,
                CustomData = TimeoutReplyHandler.Serialize(new Message { Id = "1" })
            });

            dispatcher.Dispatch(new TimeoutReply
            {
                CustomData = TimeoutReplyHandler.Serialize(new Message { Id = "2" })
            });

            handleDeferredMessage.DispatchedMessages.Count.ShouldBe(1);
            var dispatchedMessage = handleDeferredMessage.DispatchedMessages[0];
            dispatchedMessage.ShouldBeOfType<Message>();
            ((Message)dispatchedMessage).Id.ShouldBe("1");
        }
Пример #10
0
        private static async Task<IClient> ConnectInternal(ConnectionParams connectionParams, CancellationToken cancellationToken, Dispatcher dispatcher, CancellationTokenSource apiCancellationTokenSource)
        {
            try
            {
                var stream = await SetupConnection(connectionParams.HostName, connectionParams.Port);
                var fieldsStream = new FieldsStream(stream);
                var serializer = new IBSerializer();
                await Handshake(connectionParams.ClientId, fieldsStream, serializer, cancellationToken);

                var connection = new Connection.Connection(fieldsStream, serializer);
                var factory = new ApiObjectsFactory(connection, new IdsDispenser(connection), dispatcher, apiCancellationTokenSource);
                var waitForMarketConnected = factory.CreateWaitForMarketConnectedOperation(cancellationToken);
                var waitForAccountsList = factory.CreateReceiveManagedAccountsListOperation(cancellationToken);

                connection.ReadMessagesAndDispatch();

                await waitForMarketConnected;
                var accountStorage = await factory.CreateAccountStorageOperation(await waitForAccountsList, cancellationToken);
                return factory.CreateClient(accountStorage);
            }
            catch
            {
                apiCancellationTokenSource.Cancel();
                throw;
            }
        }
Пример #11
0
 /// <summary>
 /// Initialies a new <see cref="DispatcherContext"/> synchronized with a new <see cref="Thread"/> instance
 /// </summary>
 /// <param name="threadApartmentState">The <see cref="ApartmentState"/> of the <see cref="Dispatcher"/>'s <see cref="Thread"/></param>
 ///<param name="owner">The <see cref="Dispatcher"/> that owns the <see cref="DispatcherContext"/></param>
 public DispatcherContext(Dispatcher owner, ApartmentState threadApartmentState)
 {
     Thread dispatcherThread;
     this.Owner = owner;
     dispatcherThread = new Thread(new ParameterizedThreadStart(this.ExecuteOperations));
     dispatcherThread.SetApartmentState(threadApartmentState);
 }
 public void Given()
 {
     _operation = new FailOnceOperation();
     _invoker = new OperationInvoker<string>(_operation);
     _invoker.Policies.Add(new Retry(null));
     _engine = new Dispatcher<string>();
 }
 private static void FinalizeWorkDispatcher(Dispatcher dispatcher)
 {
     if (dispatcher != null)
     {
         dispatcher.Dispose();
     }
 }
Пример #14
0
    public override void Awake()
    {
		base.Awake();
		
        instance = this;
		if (scriptsToAssign == null)
			scriptsToAssign = new List<string>();
    }	
Пример #15
0
 private static void Main()
 {
     Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
     var database = new IssueTrackerDatabase();
     var issueTracker = new IssueTracker(database);
     var dispatcher = new Dispatcher(issueTracker);
     var engine = new Engine(dispatcher);
     engine.Run();
 }
        /// <summary>
        /// Init and start TT API.
        /// </summary>
        /// <param name="instance">XTraderModeTTAPI instance</param>
        /// <param name="ex">Any exception generated from the XTraderModeDelegate</param>
        public void initTTAPI(XTraderModeTTAPI apiInstance, Exception ex)
        {
            m_dispatcher = Dispatcher.Current;
            m_session = apiInstance.Session;

            m_TTAPI = apiInstance;
            m_TTAPI.ConnectionStatusUpdate += ttapiInstance_ConnectionStatusUpdate;
            m_TTAPI.ConnectToXTrader();
        }
        /// <summary>
        /// Constructor for a new SpreadDetailsForm.
        /// </summary>
        /// <param name="session">Session</param>
        /// <param name="dispatcher">Dispatcher</param>
        public SpreadDetailsForm(Session session, Dispatcher dispatcher)
        {
            InitializeComponent();

            m_isNewSpread = true;
            m_session = session;
            m_dispatcher = dispatcher;
            m_spreadDetails = new SpreadDetails();
            initFields();
        }
        /// <summary>
        /// Constructor for a SpreadDetailsForm from an existing SpreadDetails definition.
        /// </summary>
        /// <param name="session">Session</param>
        /// <param name="dispatcher">Dispatcher</param>
        /// <param name="spreadDetails">SpreadDetails</param>
        public SpreadDetailsForm(Session session, Dispatcher dispatcher, SpreadDetails spreadDetails)
        {
            InitializeComponent();

            m_isNewSpread = false;
            m_session = session;
            m_dispatcher = dispatcher;
            m_spreadDetails = spreadDetails;
            initFields();
        }
Пример #19
0
 internal IncomingMessageAgent(Message.Categories cat, IMessageCenter mc, ActivationDirectory ad, OrleansTaskScheduler sched, Dispatcher dispatcher) :
     base(cat.ToString())
 {
     category = cat;
     messageCenter = mc;
     directory = ad;
     scheduler = sched;
     this.dispatcher = dispatcher;
     OnFault = FaultBehavior.RestartOnFault;
 }
Пример #20
0
        public PositionsProxy(IPosition position, Dispatcher dispatcher)
        {
            System.Diagnostics.Contracts.Contract.Requires(position != null);
            System.Diagnostics.Contracts.Contract.Requires(dispatcher != null);

            this.position = position;
            this.dispatcher = dispatcher;

            this.positionChangedEvent = this.dispatcher.RegisterEvent();
            position.PositionChanged += this.OnPositionChanged;
        }
Пример #21
0
        public Client(GlowListener host, Socket socket, int maxPackageLength, Dispatcher dispatcher)
        {
            Host = host;
             Socket = socket;
             MaxPackageLength = maxPackageLength;
             Dispatcher = dispatcher;

             _reader = new GlowReader(GlowReader_RootReady, GlowReader_KeepAliveRequestReceived);
             _reader.Error += GlowReader_Error;
             _reader.FramingError += GlowReader_FramingError;
        }
Пример #22
0
        public OrdersProxy(IOrder order, Dispatcher dispatcher)
        {
            System.Diagnostics.Contracts.Contract.Requires(order != null);
            System.Diagnostics.Contracts.Contract.Requires(dispatcher != null);

            this.order = order;
            this.dispatcher = dispatcher;

            this.order.OrderChanged += this.OnOrderChanged;
            this.orderChangedEvent = this.dispatcher.RegisterEvent();
        }
Пример #23
0
        private static Dispatcher SetupDispatcher(CancellationTokenSource apiCancellationTokenSource)
        {
            var ctx = new SingleThreadSynchronizationContext(apiCancellationTokenSource.Token);
            var dispatcherThread = new Thread(() => { ctx.Run(); });
            dispatcherThread.Start();

            var taskScheduler = GetTaskScheduler(ctx);
            
            var dispatcher = new Dispatcher(taskScheduler, apiCancellationTokenSource.Token, dispatcherThread);
            return dispatcher;
        }
Пример #24
0
	private ObjectInteraction scribeNurse = null; // send record commands to her.

    public static Dispatcher GetInstance()
    {
		if (instance == null){
			instance = FindObjectOfType(typeof(Dispatcher)) as Dispatcher;
			if (instance == null){ // no dispatcher in the level, add one
				GameObject dgo = new GameObject("Dispatcher");
				instance = dgo.AddComponent<Dispatcher>();
			}
		}
  	    return instance;
    }
Пример #25
0
 /// <summary>
 /// Create a dependency list message and send it to the dispatcher
 /// </summary>
 /// <param name="dispatcher"></param>
 public override void VisitDispatcher(Dispatcher dispatcher)
 {
     if (failure != null)
     {
         dispatcher.Enqueue(failure);
     }
     else
     {
         dispatcher.Enqueue(new DependencyList(instance));
     }
 }
Пример #26
0
        static void Main(string[] args)
        {
            Dispatcher disp = new Dispatcher();
            Chain TheChain = new Chain();

            Dictionary<int, Command> chain = TheChain.getChain();

            foreach (KeyValuePair<int, Command> entry in chain)
            {
                disp.run(entry.Value);
            }
        }
Пример #27
0
    public DispatcherTimer(TimeSpan interval, DispatcherPriority priority, EventHandler callback, Dispatcher dispatcher)
    {
      _interval = interval;
      _priority = priority;

      if (callback != null)
      {
        Tick += callback;
      }

      _dispatcher = dispatcher;
    }
Пример #28
0
        public AccountProxy(Dispatcher dispatcher, IAccountInternal internalAccount,
            IOrdersStorage ordersStorage, IExecutionsStorage executionsStorage, IPositionsStorage positionsStorage)
        {
            this.dispatcher = dispatcher;
            this.internalAccount = internalAccount;
            this.ordersStorage = ordersStorage;
            this.executionsStorage = executionsStorage;
            this.positionsStorage = positionsStorage;

            this.internalAccount.AccountChanged += this.OnAccountChanged;
            this.accountChangedEvent = this.dispatcher.RegisterEvent();
        }
Пример #29
0
        public GlowListener(int port, int maxPackageLength, Dispatcher dispatcher)
        {
            Port = port;
             MaxPackageLength = maxPackageLength;
             Dispatcher = dispatcher;

             _listener = new TcpListener(IPAddress.Any, port);
             _listener.Start();
             _listener.BeginAcceptSocket(AcceptCallback, _listener);

             dispatcher.GlowRootReady += Dispatcher_GlowRootReady;
        }
Пример #30
0
        public ApiObjectsFactory(IConnection connection, IIdsDispenser idsDispenser, Dispatcher dispatcher,
            CancellationTokenSource internalCancellationTokenSource)
        {
            System.Diagnostics.Contracts.Contract.Requires(connection != null);
            System.Diagnostics.Contracts.Contract.Requires(idsDispenser != null);
            System.Diagnostics.Contracts.Contract.Requires(dispatcher != null);

            this.connection = connection;
            this.idsDispenser = idsDispenser;
            this.dispatcher = dispatcher;
            this.internalCancellationTokenSource = internalCancellationTokenSource;
            this.proxiesFactory = new ProxiesFactory(dispatcher);
        }
Пример #31
0
 private void BeginInvoke(Action method)
 {
     Dispatcher.BeginInvoke(method);
 }
Пример #32
0
        public RumblePad2Dashboard()
        {
            dataBlock = new ActionBlock <IJoystickSubState>(v => { Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { JoystickDataText = v.ToString(); }).AsTask().Wait(); });

            this.InitializeComponent();
        }
Пример #33
0
 /// <inheritdoc />
 public IPingResponse Ping(IPingRequest request) =>
 Dispatcher.Dispatch <IPingRequest, PingRequestParameters, PingResponse>(
     SetPingTimeout(request),
     (p, d) => LowLevelDispatch.PingDispatch <PingResponse>(p)
     );
Пример #34
0
 public CBeginInvokeOC(Dispatcher dispatcher)
 {
     this.dispatcherUIThread = dispatcher;
 }
Пример #35
0
 public MainForm()
 {
     dispatcher = Dispatcher.CurrentDispatcher;
     InitializeComponent();
     Program.controller.Start();
 }
 public MfTargetDeviceViewModel(Dispatcher disp)
     : base(disp)
 {
     _boards = new ObservableViewCollection <FirmwareHost, FirmwareHostViewModel>(disp);
     _images = new ObservableViewCollection <FirmwareImage, FirmwareImageViewModel>(disp);
 }
 public void SetInformation(string text)
 {
     Dispatcher.InvokeAsync(() => Text.Text = text);
 }
Пример #38
0
        public SparkleSetup()
        {
            Controller.ShowWindowEvent += delegate {
                Dispatcher.Invoke((Action) delegate {
                    Show();
                    Activate();
                    BringIntoView();
                });
            };

            Controller.HideWindowEvent += delegate {
                Dispatcher.Invoke((Action) delegate {
                    Hide();
                });
            };

            Controller.ChangePageEvent += delegate(PageType type, string [] warnings) {
                Dispatcher.Invoke((Action) delegate {
                    Reset();

                    switch (type)
                    {
                    case PageType.Setup: {
                        Header      = "Welcome to Yey Storage!";
                        Description = "Before we get started, what's your email and password?\n" +
                                      "Don't worry, this information will not be shared to anyone..";


                        TextBlock name_label = new TextBlock()
                        {
                            Text          = "Username:"******"Password:"******"Cancel"
                        };

                        Button continue_button = new Button()
                        {
                            Content   = "Continue",
                            IsEnabled = false
                        };


                        ContentCanvas.Children.Add(name_label);
                        Canvas.SetLeft(name_label, 180);
                        Canvas.SetTop(name_label, 200 + 3);

                        ContentCanvas.Children.Add(name_box);
                        Canvas.SetLeft(name_box, 340);
                        Canvas.SetTop(name_box, 200);

                        ContentCanvas.Children.Add(email_label);
                        Canvas.SetLeft(email_label, 180);
                        Canvas.SetTop(email_label, 230 + 3);

                        ContentCanvas.Children.Add(email_box);
                        Canvas.SetLeft(email_box, 340);
                        Canvas.SetTop(email_box, 230);

                        Buttons.Add(continue_button);
                        Buttons.Add(cancel_button);

                        name_box.Focus();
                        name_box.Select(name_box.Text.Length, 0);

                        Controller.UpdateSetupContinueButtonEvent += delegate(bool enabled) {
                            Dispatcher.Invoke((Action) delegate {
                                    continue_button.IsEnabled = enabled;
                                });
                        };

                        name_box.TextChanged += delegate {
                            Controller.CheckSetupPage(name_box.Text, email_box.Text);
                        };

                        email_box.TextChanged += delegate {
                            Controller.CheckSetupPage(name_box.Text, email_box.Text);
                        };

                        cancel_button.Click += delegate {
                            Dispatcher.Invoke((Action) delegate {
                                    SparkleUI.StatusIcon.Dispose();
                                    Controller.SetupPageCancelled();
                                });
                        };

                        continue_button.Click += delegate {
                            Controller.SetupPageCompleted(name_box.Text, email_box.Text);
                        };

                        Controller.CheckSetupPage(name_box.Text, email_box.Text);

                        break;
                    }

                    case PageType.Invite: {
                        Header      = "You've received an invite!";
                        Description = "Do you want to add this project to Yey-Storage?";


                        TextBlock address_label = new TextBlock()
                        {
                            Text          = "Address:",
                            Width         = 150,
                            TextAlignment = TextAlignment.Right
                        };

                        TextBlock address_value = new TextBlock()
                        {
                            Text       = Controller.PendingInvite.Address,
                            Width      = 175,
                            FontWeight = FontWeights.Bold
                        };


                        TextBlock path_label = new TextBlock()
                        {
                            Text          = "Remote Path:",
                            Width         = 150,
                            TextAlignment = TextAlignment.Right
                        };

                        TextBlock path_value = new TextBlock()
                        {
                            Width      = 175,
                            Text       = Controller.PendingInvite.RemotePath,
                            FontWeight = FontWeights.Bold
                        };



                        Button cancel_button = new Button()
                        {
                            Content = "Cancel"
                        };

                        Button add_button = new Button()
                        {
                            Content = "Add"
                        };


                        ContentCanvas.Children.Add(address_label);
                        Canvas.SetLeft(address_label, 180);
                        Canvas.SetTop(address_label, 200);

                        ContentCanvas.Children.Add(address_value);
                        Canvas.SetLeft(address_value, 340);
                        Canvas.SetTop(address_value, 200);

                        ContentCanvas.Children.Add(path_label);
                        Canvas.SetLeft(path_label, 180);
                        Canvas.SetTop(path_label, 225);

                        ContentCanvas.Children.Add(path_value);
                        Canvas.SetLeft(path_value, 340);
                        Canvas.SetTop(path_value, 225);

                        Buttons.Add(add_button);
                        Buttons.Add(cancel_button);


                        cancel_button.Click += delegate {
                            Controller.PageCancelled();
                        };

                        add_button.Click += delegate {
                            Controller.InvitePageCompleted();
                        };

                        break;
                    }

                    case PageType.Add: {
                        Header = "Where's your project hosted?";


                        ListView list_view = new ListView()
                        {
                            Width         = 419,
                            Height        = 195,
                            SelectionMode = SelectionMode.Single
                        };

                        GridView grid_view = new GridView()
                        {
                            AllowsColumnReorder = false
                        };

                        grid_view.Columns.Add(new GridViewColumn());

                        string xaml =
                            "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" +
                            "  xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" +
                            "  <Grid>" +
                            "    <StackPanel Orientation=\"Horizontal\">" +
                            "      <Image Margin=\"5,0,0,0\" Source=\"{Binding Image}\" Height=\"24\" Width=\"24\"/>" +
                            "      <StackPanel>" +
                            "        <TextBlock Padding=\"10,4,0,0\" FontWeight=\"Bold\" Text=\"{Binding Name}\">" +
                            "        </TextBlock>" +
                            "        <TextBlock Padding=\"10,0,0,4\" Opacity=\"0.5\" Text=\"{Binding Description}\">" +
                            "        </TextBlock>" +
                            "      </StackPanel>" +
                            "    </StackPanel>" +
                            "  </Grid>" +
                            "</DataTemplate>";

                        grid_view.Columns [0].CellTemplate = (DataTemplate)XamlReader.Parse(xaml);

                        Style header_style = new Style(typeof(GridViewColumnHeader));
                        header_style.Setters.Add(new Setter(GridViewColumnHeader.VisibilityProperty, Visibility.Collapsed));
                        grid_view.ColumnHeaderContainerStyle = header_style;

                        foreach (SparklePlugin plugin in Controller.Plugins)
                        {
                            // FIXME: images are blurry
                            BitmapFrame image = BitmapFrame.Create(
                                new Uri(plugin.ImagePath)
                                );

                            list_view.Items.Add(
                                new {
                                    Name        = plugin.Name,
                                    Description = plugin.Description,
                                    Image       = image
                                }
                                );
                        }

                        list_view.View          = grid_view;
                        list_view.SelectedIndex = Controller.SelectedPluginIndex;

                        TextBlock address_label = new TextBlock()
                        {
                            Text       = "Address:",
                            FontWeight = FontWeights.Bold
                        };

                        TextBox address_box = new TextBox()
                        {
                            Width     = 200,
                            Text      = Controller.PreviousAddress,
                            IsEnabled = (Controller.SelectedPlugin.Address == null)
                        };

                        TextBlock address_help_label = new TextBlock()
                        {
                            Text       = Controller.SelectedPlugin.AddressExample,
                            FontSize   = 11,
                            Foreground = new SolidColorBrush(Color.FromRgb(128, 128, 128))
                        };

                        TextBlock path_label = new TextBlock()
                        {
                            Text       = "Remote Path:",
                            FontWeight = FontWeights.Bold,
                            Width      = 200
                        };

                        TextBox path_box = new TextBox()
                        {
                            Width     = 200,
                            Text      = Controller.PreviousPath,
                            IsEnabled = (Controller.SelectedPlugin.Path == null)
                        };

                        TextBlock path_help_label = new TextBlock()
                        {
                            Text       = Controller.SelectedPlugin.PathExample,
                            FontSize   = 11,
                            Width      = 200,
                            Foreground = new SolidColorBrush(Color.FromRgb(128, 128, 128))
                        };

                        Button cancel_button = new Button()
                        {
                            Content = "Cancel"
                        };

                        Button add_button = new Button()
                        {
                            Content = "Add"
                        };

                        CheckBox history_check_box = new CheckBox()
                        {
                            Content   = "Fetch prior revisions",
                            IsChecked = Controller.FetchPriorHistory
                        };

                        history_check_box.Click += delegate {
                            Controller.HistoryItemChanged(history_check_box.IsChecked.Value);
                        };

                        ContentCanvas.Children.Add(history_check_box);
                        Canvas.SetLeft(history_check_box, 185);
                        Canvas.SetBottom(history_check_box, 12);

                        ContentCanvas.Children.Add(list_view);
                        Canvas.SetTop(list_view, 70);
                        Canvas.SetLeft(list_view, 185);

                        ContentCanvas.Children.Add(address_label);
                        Canvas.SetTop(address_label, 285);
                        Canvas.SetLeft(address_label, 185);

                        ContentCanvas.Children.Add(address_box);
                        Canvas.SetTop(address_box, 305);
                        Canvas.SetLeft(address_box, 185);

                        ContentCanvas.Children.Add(address_help_label);
                        Canvas.SetTop(address_help_label, 330);
                        Canvas.SetLeft(address_help_label, 185);

                        ContentCanvas.Children.Add(path_label);
                        Canvas.SetTop(path_label, 285);
                        Canvas.SetRight(path_label, 30);

                        ContentCanvas.Children.Add(path_box);
                        Canvas.SetTop(path_box, 305);
                        Canvas.SetRight(path_box, 30);

                        ContentCanvas.Children.Add(path_help_label);
                        Canvas.SetTop(path_help_label, 330);
                        Canvas.SetRight(path_help_label, 30);

                        TaskbarItemInfo.ProgressValue = 0.0;
                        TaskbarItemInfo.ProgressState = TaskbarItemProgressState.None;

                        Buttons.Add(add_button);
                        Buttons.Add(cancel_button);

                        address_box.Focus();
                        address_box.Select(address_box.Text.Length, 0);


                        Controller.ChangeAddressFieldEvent += delegate(string text,
                                                                       string example_text, FieldState state) {
                            Dispatcher.Invoke((Action) delegate {
                                    address_box.Text        = text;
                                    address_box.IsEnabled   = (state == FieldState.Enabled);
                                    address_help_label.Text = example_text;
                                });
                        };

                        Controller.ChangePathFieldEvent += delegate(string text,
                                                                    string example_text, FieldState state) {
                            Dispatcher.Invoke((Action) delegate {
                                    path_box.Text        = text;
                                    path_box.IsEnabled   = (state == FieldState.Enabled);
                                    path_help_label.Text = example_text;
                                });
                        };

                        Controller.UpdateAddProjectButtonEvent += delegate(bool button_enabled) {
                            Dispatcher.Invoke((Action) delegate {
                                    add_button.IsEnabled = button_enabled;
                                });
                        };

                        list_view.SelectionChanged += delegate {
                            Controller.SelectedPluginChanged(list_view.SelectedIndex);
                        };

                        list_view.KeyDown += delegate {
                            Controller.SelectedPluginChanged(list_view.SelectedIndex);
                        };

                        Controller.CheckAddPage(address_box.Text, path_box.Text, list_view.SelectedIndex);

                        address_box.TextChanged += delegate {
                            Controller.CheckAddPage(address_box.Text, path_box.Text, list_view.SelectedIndex);
                        };

                        path_box.TextChanged += delegate {
                            Controller.CheckAddPage(address_box.Text, path_box.Text, list_view.SelectedIndex);
                        };

                        cancel_button.Click += delegate {
                            Controller.PageCancelled();
                        };

                        add_button.Click += delegate {
                            Controller.AddPageCompleted(address_box.Text, path_box.Text);
                        };

                        break;
                    }


                    case PageType.Syncing: {
                        Header      = "Adding project ‘" + Controller.SyncingFolder + "’…";
                        Description = "This may either take a short or a long time depending on the project's size.";

                        Button finish_button = new Button()
                        {
                            Content   = "Finish",
                            IsEnabled = false
                        };

                        Button cancel_button = new Button()
                        {
                            Content = "Cancel"
                        };

                        ProgressBar progress_bar = new ProgressBar()
                        {
                            Width  = 414,
                            Height = 15,
                            Value  = Controller.ProgressBarPercentage
                        };


                        ContentCanvas.Children.Add(progress_bar);
                        Canvas.SetLeft(progress_bar, 185);
                        Canvas.SetTop(progress_bar, 150);

                        TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal;

                        Buttons.Add(finish_button);
                        Buttons.Add(cancel_button);


                        Controller.UpdateProgressBarEvent += delegate(double percentage) {
                            Dispatcher.Invoke((Action) delegate {
                                    progress_bar.Value            = percentage;
                                    TaskbarItemInfo.ProgressValue = percentage / 100;
                                });
                        };

                        cancel_button.Click += delegate {
                            Controller.SyncingCancelled();
                        };

                        break;
                    }


                    case PageType.Error: {
                        Header      = "Something went wrong…";
                        Description = "Please check the following:";


                        TextBlock help_block = new TextBlock()
                        {
                            TextWrapping = TextWrapping.Wrap,
                            Width        = 310
                        };

                        help_block.Inlines.Add("Is the host online?\n\n");
                        help_block.Inlines.Add(new Bold(new Run(Controller.PreviousUrl)));
                        help_block.Inlines.Add(" is the address we've compiled. Does this look alright?\n\n");
                        help_block.Inlines.Add("The host needs to know who you are. Did you upload the key that's in your SparkleShare folder?");

                        TextBlock bullets_block = new TextBlock()
                        {
                            Text = "•\n\n•\n\n\n•"
                        };


                        Button cancel_button = new Button()
                        {
                            Content = "Cancel"
                        };

                        Button try_again_button = new Button()
                        {
                            Content = "Try again…"
                        };



                        ContentCanvas.Children.Add(bullets_block);
                        Canvas.SetLeft(bullets_block, 195);
                        Canvas.SetTop(bullets_block, 100);

                        ContentCanvas.Children.Add(help_block);
                        Canvas.SetLeft(help_block, 210);
                        Canvas.SetTop(help_block, 100);

                        TaskbarItemInfo.ProgressValue = 1.0;
                        TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Error;

                        Buttons.Add(try_again_button);
                        Buttons.Add(cancel_button);


                        cancel_button.Click += delegate {
                            Controller.PageCancelled();
                        };

                        try_again_button.Click += delegate {
                            Controller.ErrorPageCompleted();
                        };

                        break;
                    }

                    case PageType.Finished: {
                        Header      = "Your shared project is ready!";
                        Description = "You can find the files in your SparkleShare folder.";


                        Button finish_button = new Button()
                        {
                            Content = "Finish"
                        };

                        Button open_folder_button = new Button()
                        {
                            Content = string.Format("Open {0}", Path.GetFileName(Controller.PreviousPath))
                        };

                        if (warnings.Length > 0)
                        {
                            Image warning_image = new Image()
                            {
                                Source = Imaging.CreateBitmapSourceFromHIcon(Drawing.SystemIcons.Information.Handle,
                                                                             Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())
                            };

                            TextBlock warning_block = new TextBlock()
                            {
                                Text         = warnings [0],
                                Width        = 310,
                                TextWrapping = TextWrapping.Wrap
                            };

                            ContentCanvas.Children.Add(warning_image);
                            Canvas.SetLeft(warning_image, 193);
                            Canvas.SetTop(warning_image, 100);

                            ContentCanvas.Children.Add(warning_block);
                            Canvas.SetLeft(warning_block, 240);
                            Canvas.SetTop(warning_block, 100);
                        }

                        TaskbarItemInfo.ProgressValue = 0.0;
                        TaskbarItemInfo.ProgressState = TaskbarItemProgressState.None;

                        Buttons.Add(finish_button);
                        Buttons.Add(open_folder_button);


                        finish_button.Click += delegate {
                            Controller.FinishPageCompleted();
                        };

                        open_folder_button.Click += delegate {
                            Controller.OpenFolderClicked();
                        };


                        SystemSounds.Exclamation.Play();

                        break;
                    }

                    case PageType.Tutorial: {
                        switch (Controller.TutorialPageNumber)
                        {
                        case 1: {
                            Header      = "What's happening next?";
                            Description = "SparkleShare creates a special folder on your computer " +
                                          "that will keep track of your projects.";


                            WPF.Image slide_image = new WPF.Image()
                            {
                                Width  = 350,
                                Height = 200
                            };

                            slide_image.Source = SparkleUIHelpers.GetImageSource("tutorial-slide-1-windows");

                            Button skip_tutorial_button = new Button()
                            {
                                Content = "Skip tutorial"
                            };

                            Button continue_button = new Button()
                            {
                                Content = "Continue"
                            };


                            ContentCanvas.Children.Add(slide_image);
                            Canvas.SetLeft(slide_image, 215);
                            Canvas.SetTop(slide_image, 130);

                            Buttons.Add(continue_button);
                            Buttons.Add(skip_tutorial_button);


                            skip_tutorial_button.Click += delegate {
                                Controller.TutorialSkipped();
                            };

                            continue_button.Click += delegate {
                                Controller.TutorialPageCompleted();
                            };

                            break;
                        }

                        case 2: {
                            Header      = "Sharing files with others";
                            Description = "All files added to your project folders are synced automatically with " +
                                          "the host and your team members.";


                            Button continue_button = new Button()
                            {
                                Content = "Continue"
                            };

                            WPF.Image slide_image = new WPF.Image()
                            {
                                Width  = 350,
                                Height = 200
                            };

                            slide_image.Source = SparkleUIHelpers.GetImageSource("tutorial-slide-2-windows");


                            ContentCanvas.Children.Add(slide_image);
                            Canvas.SetLeft(slide_image, 215);
                            Canvas.SetTop(slide_image, 130);

                            Buttons.Add(continue_button);


                            continue_button.Click += delegate {
                                Controller.TutorialPageCompleted();
                            };

                            break;
                        }

                        case 3: {
                            Header      = "The status icon is here to help";
                            Description = "It shows the syncing progress, provides easy access to " +
                                          "your projects and lets you view recent changes.";


                            Button continue_button = new Button()
                            {
                                Content = "Continue"
                            };

                            WPF.Image slide_image = new WPF.Image()
                            {
                                Width  = 350,
                                Height = 200
                            };

                            slide_image.Source = SparkleUIHelpers.GetImageSource("tutorial-slide-3-windows");


                            ContentCanvas.Children.Add(slide_image);
                            Canvas.SetLeft(slide_image, 215);
                            Canvas.SetTop(slide_image, 130);

                            Buttons.Add(continue_button);


                            continue_button.Click += delegate {
                                Controller.TutorialPageCompleted();
                            };

                            break;
                        }

                        case 4: {
                            Header      = "Adding projects to SparkleShare";
                            Description = "You can do this through the status icon menu, or by clicking " +
                                          "magic buttons on webpages that look like this:";


                            Button finish_button = new Button()
                            {
                                Content = "Finish"
                            };

                            WPF.Image slide_image = new WPF.Image()
                            {
                                Width  = 350,
                                Height = 64
                            };

                            slide_image.Source = SparkleUIHelpers.GetImageSource("tutorial-slide-4");

                            CheckBox check_box = new CheckBox()
                            {
                                Content   = "Add SparkleShare to startup items",
                                IsChecked = true
                            };


                            ContentCanvas.Children.Add(slide_image);
                            Canvas.SetLeft(slide_image, 215);
                            Canvas.SetTop(slide_image, 130);

                            ContentCanvas.Children.Add(check_box);
                            Canvas.SetLeft(check_box, 185);
                            Canvas.SetBottom(check_box, 12);

                            Buttons.Add(finish_button);


                            check_box.Click += delegate {
                                Controller.StartupItemChanged(check_box.IsChecked.Value);
                            };

                            finish_button.Click += delegate {
                                Controller.TutorialPageCompleted();
                            };

                            break;
                        }
                        }
                        break;
                    }
                    }

                    ShowAll();
                });
            };
        }
 private void PowerSupply_StatusChanged(IPowerSupplyStatus status)
 {
     Dispatcher.InvokeAsync(() => UpdateStatus(status));
 }
Пример #40
0
        private void UpdateInfo(object sender, InfoUpdateEventArgs e)
        {
            switch (e.InfoPart)
            {
            case InfoUpdateEventArgs.InfoParts.BaseInfo:
                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    try
                    {
                        CountryName.Text         = string.IsNullOrWhiteSpace(_selectedCountry.Name) ? "" : _selectedCountry.Name;
                        CountryPhoneCode.Content = _selectedCountry.PhoneCode == 0 ? "" : ("+" + _selectedCountry.PhoneCode);
                        CountryLanguages.Content = string.IsNullOrWhiteSpace(_selectedCountry.FormLanguagesAsString()) ? "" : _selectedCountry.FormLanguagesAsString();
                        CountryCapital.Content   = string.IsNullOrWhiteSpace(_selectedCountry.Capital) ? "" : _selectedCountry.Capital;
                        CountryContinent.Content = _selectedCountry.Continent;
                        CountryCurrencyInfo.Text = string.IsNullOrWhiteSpace(_selectedCountry.FormCurrencyDescription()) ? "" : _selectedCountry.FormCurrencyDescription();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Base info exception " + ex.GetType().ToString() + " " + ex.Message);
                    }

                    //CountryCurrencies.Content
                }));
                break;

            case InfoUpdateEventArgs.InfoParts.FlagImage:

                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    try
                    {
                        CountryFlag.Source = _selectedCountry.Flag;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Flag exception " + ex.GetType().ToString() + " " + ex.Message);
                    }
                }));
                break;

            case InfoUpdateEventArgs.InfoParts.CurrencyConversion:
                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    try
                    {
                        CountryCurrencies.Content = _selectedCountry.FormCurrenciesAsString();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Currencies exception: " + ex.GetType().ToString() + " " + ex.Message + " " + ex.Source);
                    }
                }));
                break;

            case InfoUpdateEventArgs.InfoParts.Population:
                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    try
                    {
                        if (_selectedCountry.Population > 0)
                        {
                            CountryPopulation.Content = string.Format("{0,12:N0}", _selectedCountry.Population);
                        }
                        else
                        {
                            CountryPopulation.Content = "unknown";
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Population exception: " + ex.GetType().ToString() + " " + ex.Message + " " + ex.Source);
                    }
                }));
                break;

            case InfoUpdateEventArgs.InfoParts.CurrencyName:
                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    try
                    {
                        CountryCurrencyInfo.Text = string.IsNullOrWhiteSpace(_selectedCountry.FormCurrencyDescription()) ? "" : _selectedCountry.FormCurrencyDescription();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Currency info exception: " + ex.GetType().ToString() + " " + ex.Message + " " + ex.Source);
                    }
                }));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Пример #41
0
 /// <inheritdoc cref="CreateAutoFollowPattern(Name, System.Func{Nest6.CreateAutoFollowPatternDescriptor,Nest6.ICreateAutoFollowPatternRequest})" />
 public ICreateAutoFollowPatternResponse CreateAutoFollowPattern(ICreateAutoFollowPatternRequest request) =>
 Dispatcher.Dispatch <ICreateAutoFollowPatternRequest, CreateAutoFollowPatternRequestParameters, CreateAutoFollowPatternResponse>(
     request,
     (p, d) => LowLevelDispatch.CcrPutAutoFollowPatternDispatch <CreateAutoFollowPatternResponse>(p, d)
     );
Пример #42
0
 public static void Reset()
 {
     Dispatcher = null;
 }
Пример #43
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            FlurryWP7SDK.Api.LogEvent("Chat - Chat started", true);

            App.Current.LastPage = e.Uri.OriginalString;

            gtalk       = App.Current.GtalkClient;
            gtalkHelper = App.Current.GtalkHelper;
            settings    = App.Current.Settings;

            App.Current.GtalkHelper.SetCorrectOrientation(this);

            currentContact = null;

            if (NavigationContext.QueryString.ContainsKey("from"))
            {
                to    = NavigationContext.QueryString["from"];
                email = to;

                if (email.Contains("/"))
                {
                    email = email.Substring(0, email.IndexOf('/'));
                }

                App.Current.CurrentChat = email;

                to = email;

                if (App.Current.Roster.Contains(email))
                {
                    currentContact = App.Current.Roster[email];
                }
            }

            gtalkHelper.MessageReceived += DisplayMessage;

            if (gtalkHelper.RosterLoaded && gtalk.LoggedIn && App.Current.Roster.Contains(email))
            {
                Initialize();

                if (e.NavigationMode == NavigationMode.Back)
                {
                    ShowProgressBar(AppResources.Chat_ProgressGettingMessages);
                    gtalkHelper.GetOfflineMessages(() => Dispatcher.BeginInvoke(() => HideProgressBar()));
                }
            }
            else
            {
                ShowProgressBar(AppResources.Chat_ProgressGettingMessages);
                gtalkHelper.RosterUpdated += () => HideProgressBar();
                gtalkHelper.RosterUpdated += Initialize;
            }

            object savedText;

            if (State.TryGetValue("message", out savedText))
            {
                MessageText.Text = (string)savedText;
            }

            gtalkHelper.LoginIfNeeded();

            ScrollToBottom();
        }
 private async void LogToScreen (string text, CoreDispatcherPriority priority = CoreDispatcherPriority.Low)
 {
     await Dispatcher.RunAsync(priority, () => { Status.Text += text + "\n"; });
 }
Пример #45
0
        ////////////////
        // Debugging
        ////////////////

        protected void AppendLogLine(string logLine)
        {
            Dispatcher.RequestMainThreadAction(() => Log.Add(new LogMessage(logLine)));
        }
 private void OnManualRefreshHardwareButtonPressed(object sender, EventArgs e)
 {
     Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ViewModel.Refresh.Execute(null));
 }
Пример #47
0
        public void bulletHandling(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
        {
            List <Bullet> bulletsToRemove = new List <Bullet>();
            // Create a list for bullets to delete
            List <int> enemiesToRemove = new List <int>();

            // Create a list for enemies to delete

            // Show bullets
            foreach (Bullet bullet in bullets)
            {
                bullet.x += bullet.velX;
                bullet.y += bullet.velY;
                // Move the bullets with choosen velocity
                args.DrawingSession.DrawImage(Bullets, bullet.x, bullet.y);


                if (levels.getPlayerTile(bullet.x, bullet.y, levels.gekozenLevel).TileType.Contains("wall") || // If the bullet hits a wall
                    levels.getPlayerTile(bullet.x, bullet.y, levels.gekozenLevel).TileType.Contains("tree"))    // If the bullet hits a tree
                {
                    bulletsToRemove.Add(bullet);
                    // Add the bullet to the list of bullets to remove
                }

                if (bullet.y < 0f || bullet.y > 1080 || bullet.x > 1920f || bullet.x < 0f) // Als de kogel buiten beeld gaat
                {
                    bulletsToRemove.Add(bullet);
                    // Add the bullet to the list of bullets to remove
                }

                int enemiesCount = 0;
                foreach (Enemy enemy in enemies)                                                                                                                         // Loop though all the enemies
                {
                    if ((bullet.y > enemy.y - 16 && bullet.y < enemy.y + 16) && (bullet.x > enemy.x - 16 && bullet.x < enemy.x + 16) && (bullet.eigenaar != enemy.name)) // If the bullet isnt from yourself
                    {
                        enemy.hit(player.currentWeapon.getDamage());
                        // Give the enemy damage from the bullet
                        if (enemy.getHealth() <= 0)
                        {
                            addItem(enemy);
                            // Drop the weapon
                            enemiesToRemove.Add(enemiesCount);
                            // Add the enemy to the enemies to delete
                        }
                        bulletsToRemove.Add(bullet);
                        // Add the bullet to the list of bullets to remove
                    }
                    enemiesCount++;
                    // Increase the enemiesCount
                }

                if ((player.y > player.y - 16 && bullet.y < player.y + 16) && (bullet.x > player.x - 16 && bullet.x < player.x + 16) && (bullet.eigenaar != player.name)) // If the bullet hits the player
                {
                    player.hit(bullet.damage);
                    // Let the player take damage from the bullet
                    bulletsToRemove.Add(bullet);
                    // Add the bullet to the list of bullets to remove

                    if (!player.alive)
                    {
                        Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            Frame.Navigate(typeof(GameOver));
                        }).AsTask().Wait();
                    }
                }
            }


            // Remove Bullets
            foreach (Bullet bullet in bulletsToRemove)
            {
                bullets.Remove(bullet);
                // Remove bullet
            }

            // Remove enemies
            foreach (int removeEnemy in enemiesToRemove)
            {
                enemies.RemoveAt(removeEnemy);
                // Remove enemy

                // Check if there are enemies left. If not; game is finished
                if (enemies.Count == 0)
                {
                    // Run on UI thread
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                            () =>
                    {
                        // Navigate to success page
                        Frame.Navigate(typeof(SuccessPage));
                    });
                }
            }
        }
Пример #48
0
        public async Task TestSetEndpoint()
        {
            var endpoint1 = new TestEndpoint("id1");
            var endpoint2 = new TestEndpoint("id1");
            var endpoint3 = new TestEndpoint("id3");
            var endpoint4 = new TestEndpoint("id4");

            var endpoints = new HashSet <Endpoint> {
                endpoint1, endpoint3
            };

            using (Dispatcher dispatcher = await Dispatcher.CreateAsync("dispatcher", "hub", endpoints, SyncExecutorFactory))
            {
                Assert.Equal(new List <IMessage>(), endpoint1.Processed);
                Assert.Equal(new List <IMessage>(), endpoint3.Processed);

                await Assert.ThrowsAsync <ArgumentNullException>(() => dispatcher.SetEndpoint(null));

                await dispatcher.DispatchAsync(Message1, new HashSet <Endpoint> {
                    endpoint1, endpoint3
                });

                await dispatcher.DispatchAsync(Message1, new HashSet <Endpoint> {
                    endpoint1, endpoint3
                });

                await dispatcher.SetEndpoint(endpoint2);

                await dispatcher.DispatchAsync(Message2, new HashSet <Endpoint> {
                    endpoint1, endpoint3
                });

                await dispatcher.DispatchAsync(Message3, new HashSet <Endpoint> {
                    endpoint1, endpoint3
                });

                await dispatcher.SetEndpoint(endpoint4);

                await dispatcher.DispatchAsync(Message2, new HashSet <Endpoint> {
                    endpoint1, endpoint3, endpoint4
                });

                await dispatcher.DispatchAsync(Message3, new HashSet <Endpoint> {
                    endpoint1, endpoint3, endpoint4
                });

                await dispatcher.CloseAsync(CancellationToken.None);

                await Assert.ThrowsAsync <InvalidOperationException>(() => dispatcher.SetEndpoint(endpoint2));
            }

            var expected = new List <IMessage> {
                Message1, Message1, Message2, Message3, Message2, Message3
            };

            Assert.Equal(expected, endpoint1.Processed.Concat(endpoint2.Processed));
            Assert.Equal(expected, endpoint3.Processed);
            Assert.Equal(new List <IMessage> {
                Message2, Message3
            }, endpoint4.Processed);
        }
 private async Task ClearScreen(CoreDispatcherPriority priority = CoreDispatcherPriority.Low)
 {
     await Dispatcher.RunAsync(priority, () => { Status.Text = ""; });
 }
Пример #50
0
 public DownloadViewModel()
 {
     _dispatcher = Deployment.Current.Dispatcher;
 }
Пример #51
0
 void g_CurrentValueChanged(object sender, SensorReadingEventArgs <GyroscopeReading> e)
 {
     Dispatcher.BeginInvoke(() => UpdateUI(e.SensorReading));
 }
Пример #52
0
 private void OptionWindow_OnInitialized(object sender, EventArgs e)
 {
     Dispatcher.BeginInvoke(new Action(LoadLighter), DispatcherPriority.ContextIdle, null);
     DwmHelper.DropShadowToWindow(this);
 }
Пример #53
0
 public async Task TestConstructor()
 {
     await Assert.ThrowsAsync <ArgumentNullException>(() => Dispatcher.CreateAsync(null, null, null, null));
 }
Пример #54
0
        private void ViewContactList_Click(object sender, EventArgs e)
        {
            FlurryWP7SDK.Api.LogEvent("Chat - ViewContactList clicked");

            Dispatcher.BeginInvoke(() => App.Current.RootFrame.Navigate(new Uri("/Pages/ContactList.xaml", UriKind.Relative)));
        }
Пример #55
0
 /// <inheritdoc />
 public Task <IPingResponse> PingAsync(IPingRequest request, CancellationToken cancellationToken = default(CancellationToken)) =>
 Dispatcher.DispatchAsync <IPingRequest, PingRequestParameters, PingResponse, IPingResponse>(
     SetPingTimeout(request),
     cancellationToken,
     (p, d, c) => LowLevelDispatch.PingDispatchAsync <PingResponse>(p, c)
     );
Пример #56
0
        private void Initialize()
        {
            gtalkHelper.RosterUpdated -= Initialize;

            Dispatcher.BeginInvoke(() => {
                string displayName = email;
                string status      = string.Empty;
                if (App.Current.Roster.Contains(to))
                {
                    Contact t   = App.Current.Roster[to];
                    displayName = t.NameOrEmail;
                    status      = t.Status;
                }

                PageTitle.Text = displayName.ToUpper();
                if (status != string.Empty)
                {
                    PageTitle.Text += ", " + char.ToUpper(status[0]) + status.Substring(1);
                }

                TypingStatus.Text = String.Format(AppResources.Chat_NoticeTyping, displayName);

                if (gtalkHelper.IsContactPinned(email))
                {
                    pinButton.IsEnabled = false;
                }

                chatLog = gtalkHelper.ChatLog(to);

                MessageList.Visibility = System.Windows.Visibility.Collapsed;

                MessageList.Children.Clear();

                lock (chatLog) {
                    var otr = false;

                    foreach (var message in chatLog)
                    {
                        UserControl bubble;

                        if (message.OTR != otr)
                        {
                            if (message.OTR)
                            {
                                ShowStartOtr();
                            }
                            else
                            {
                                ShowEndOtr();
                            }

                            otr = message.OTR;
                        }

                        if (message.Body == null)
                        {
                            continue;
                        }

                        if (message.Outbound)
                        {
                            bubble = new SentChatBubble();

                            (bubble as SentChatBubble).Text      = message.Body;
                            (bubble as SentChatBubble).TimeStamp = message.Time;
                        }
                        else
                        {
                            bubble = new ReceivedChatBubble();

                            (bubble as ReceivedChatBubble).Text      = message.Body;
                            (bubble as ReceivedChatBubble).TimeStamp = message.Time;
                        }

                        MessageList.Children.Add(bubble);
                    }
                }

                MessageList.Visibility = System.Windows.Visibility.Visible;
                MessageList.UpdateLayout();
                Scroller.UpdateLayout();
                Scroller.ScrollToVerticalOffset(Scroller.ExtentHeight);

                var unread = settings["unread"] as Dictionary <string, int>;
                lock (unread) {
                    unread[email] = 0;
                }
                if (App.Current.Roster.Contains(email))
                {
                    App.Current.Roster[email].UnreadCount = 0;
                }

                Uri url            = gtalkHelper.GetPinUri(email);
                ShellTile existing = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri == url);

                if (existing != null)
                {
                    existing.Update(
                        new StandardTileData {
                        Count = 0
                    }
                        );
                }

                var contact = App.Current.Roster[email];

                if (contact != null)
                {
                    contact.UnreadCount = 0;
                }

                // Sets to broadcast the first message in a conversation
                to = email;
            });
        }
Пример #57
0
        private async void CameraHelper_FrameArrived(object sender, FrameEventArgs e)
        {
            VideoFrame     videoFrame     = e.VideoFrame;
            SoftwareBitmap softwareBitmap = videoFrame.SoftwareBitmap;

            if (_ready)
            {
                _ready = false;

                try
                {
                    IList <PredictionModel> faces = await objectDetection.PredictImageAsync(VideoFrame.CreateWithSoftwareBitmap(await ResizeBitmap(softwareBitmap, YOLO_INPUT, YOLO_INPUT)));

                    PredictionModel face = faces[0];

                    if (faces.Count > 0 && face.BoundingBox.Height * face.BoundingBox.Width > MIN_SIZE)
                    {
                        SoftwareBitmap softwareBitmapFace = await CorpBitmap(softwareBitmap,
                                                                             new Rect(Math.Max(0, softwareBitmap.PixelWidth *face.BoundingBox.Left),
                                                                                      Math.Max(0, softwareBitmap.PixelHeight *face.BoundingBox.Top),
                                                                                      Math.Max(0, softwareBitmap.PixelWidth *face.BoundingBox.Width),
                                                                                      Math.Max(0, softwareBitmap.PixelHeight *face.BoundingBox.Height)));

                        _softwareBitmapFace = await ResizeBitmap(softwareBitmapFace, ARC_FACE_INPUT, ARC_FACE_INPUT);

                        List <float> embedding = await ArcFace(_softwareBitmapFace);

                        List <double> result = new List <double>();

                        await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                        {
                            for (int i = 0; i < GridViewImage.Items.Count; i++)
                            {
                                ImageFile imageFile = (GridViewImage.Items[i] as ImageFile);

                                result.Add(GetCosineSimilarity(embedding, imageFile.Embedding));
                            }

                            CanvasPreview.Children.Clear();

                            CanvasPreview.Children.Add(new Rectangle()
                            {
                                Height          = Convert.ToInt32(GridPreview.Height *face.BoundingBox.Height),
                                Margin          = new Thickness(GridPreview.Width *face.BoundingBox.Left, GridPreview.Height *face.BoundingBox.Top, 0, 0),
                                Stroke          = new SolidColorBrush(Windows.UI.Colors.Red),
                                StrokeThickness = 3,
                                Width           = Convert.ToInt32(GridPreview.Width *face.BoundingBox.Width),
                            });

                            if (GridViewImage.Items.Count > 0)
                            {
                                var maxIndex = result.IndexOf(result.Max());

                                if (result[maxIndex] > MIN_SIMILARITY)
                                {
                                    CanvasPreview.Children.Add(new TextBlock()
                                    {
                                        FontSize   = 24,
                                        Foreground = new SolidColorBrush(Windows.UI.Colors.Red),
                                        Margin     = new Thickness(GridPreview.Width *face.BoundingBox.Left, GridPreview.Height *face.BoundingBox.Top - 30, 0, 0),
                                        Text       = $"{(GridViewImage.Items[maxIndex] as ImageFile).DisplayName}: {result[maxIndex].ToString("N2")}"
                                    });

                                    Thread.Sleep(1000);
                                }
                            }
                        });
                    }
                    else
                    {
                        await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                        {
                            CanvasPreview.Children.Clear();
                        });
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }

                _ready = true;
            }
        }
Пример #58
0
        private void SendButton_Click(object sender, EventArgs e)
        {
            if (MessageText.Text.Length == 0)
            {
                return;
            }

            ShowProgressBar(AppResources.Chat_ProgressSendingMessage);

            sendButton.IsEnabled = false;

            try {
                gtalk.SendMessage(to, MessageText.Text, data => Dispatcher.BeginInvoke(() => {
                    HideProgressBar();

                    var bubble       = new SentChatBubble();
                    bubble.Text      = MessageText.Text;
                    bubble.TimeStamp = DateTime.Now;

                    App.Current.GtalkHelper.AddRecentContact(currentContact);

                    MessageList.Children.Add(bubble);

                    sendButton.IsEnabled = true;

                    MessageList.UpdateLayout();
                    Scroller.UpdateLayout();
                    Scroller.ScrollToVerticalOffset(Scroller.ExtentHeight);

                    lock (chatLog) {
                        while (chatLog.Count >= GoogleTalkHelper.MaximumChatLogSize)
                        {
                            chatLog.RemoveAt(0);
                        }
                        chatLog.Add(new Message {
                            Body     = MessageText.Text,
                            Outbound = true,
                            Time     = DateTime.Now,
                            OTR      = otr
                        });
                    }

                    MessageText.Text = "";

                    FlurryWP7SDK.Api.LogEvent("Chat - Chat sent");
                }), error => {
                    HideProgressBar();
                    if (error.StartsWith("403"))
                    {
                        settings.Remove("token");
                        settings.Remove("rootUrl");
                        gtalkHelper.LoginIfNeeded();
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(
                            () => {
                            sendButton.IsEnabled = true;
                            gtalkHelper.ShowToast(AppResources.Chat_ErrorMessageNotSent);
                        }
                            );
                    }
                });
            } catch (InvalidOperationException) {
                Dispatcher.BeginInvoke(
                    () => {
                    HideProgressBar();
                    MessageBox.Show(
                        AppResources.Chat_ErrorAuthExpiredBody,
                        AppResources.Chat_ErrorAuthExpiredTitle,
                        MessageBoxButton.OK
                        );
                    App.Current.RootFrame.Navigate(new Uri("/Pages/Login.xaml", UriKind.Relative));
                }
                    );
            }
        }
Пример #59
0
        private async void SetTextKey(Key key)
        {
            switch (key)
            {
            case Key.Enter:
                break;

            case Key.F1:
                Text = "F1";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F2:
                Text = "F2";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F3:
                Text = "F3";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F4:
                Text = "F4";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F5:
                Text = "F5";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F6:
                Text = "F6";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F7:
                Text = "F7";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F8:
                Text = "F9";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F9:
                Text = "F9";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F10:
                Text = "F10";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F11:
                Text = "F11";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.F12:
                Text = "F12";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.Space:
                Text = "Space";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.Back:
                Text = "Back";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            case Key.Delete:
                Text = "Delete";
                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;

            default:
                Text = Key.GetCharFromKey().ToString();

                await Dispatcher.Yield();

                OnKeyChanged(Key);
                break;
            }
        }
Пример #60
0
 /// <inheritdoc cref="CreateAutoFollowPattern(Name, System.Func{Nest6.CreateAutoFollowPatternDescriptor,Nest6.ICreateAutoFollowPatternRequest})" />
 public Task <ICreateAutoFollowPatternResponse> CreateAutoFollowPatternAsync(ICreateAutoFollowPatternRequest request, CancellationToken cancellationToken = default) =>
 Dispatcher.DispatchAsync <ICreateAutoFollowPatternRequest, CreateAutoFollowPatternRequestParameters, CreateAutoFollowPatternResponse, ICreateAutoFollowPatternResponse>(
     request,
     cancellationToken,
     (p, d, c) => LowLevelDispatch.CcrPutAutoFollowPatternDispatchAsync <CreateAutoFollowPatternResponse>(p, d, c)
     );