Inheritance: MonoBehaviour
 public static void setValue(Key key, object value)
 {
     if (HttpContext.Current != null)
         HttpContext.Current.Items[key.ToString()] = value;
     else
         CallContext.SetData(key.ToString(), value);
 }
        private void LoadSettings()
        {
            // Kill all
            CreditServiceButton = Key.Unknown;
            DIPSwitch1 = Key.Unknown;
            DIPSwitch2 = Key.Unknown;
            DIPSwitch3 = Key.Unknown;
            DIPSwitch4 = Key.Unknown;
            DIPSwitch5 = Key.Unknown;
            DIPSwitch6 = Key.Unknown;
            DIPSwitch7 = Key.Unknown;
            DIPSwitch8 = Key.Unknown;
            CreditLeftCoinSlot = Key.Unknown;
            CreditRightCoinSlot = Key.Unknown;

            Enum.TryParse<Key>(Settings.Key_VS_CreditServiceButton, out this.CreditServiceButton);
            Enum.TryParse<Key>(Settings.Key_VS_DIPSwitch1, out this.DIPSwitch1);
            Enum.TryParse<Key>(Settings.Key_VS_DIPSwitch2, out this.DIPSwitch2);
            Enum.TryParse<Key>(Settings.Key_VS_DIPSwitch3, out this.DIPSwitch3);
            Enum.TryParse<Key>(Settings.Key_VS_DIPSwitch4, out this.DIPSwitch4);
            Enum.TryParse<Key>(Settings.Key_VS_DIPSwitch5, out this.DIPSwitch5);
            Enum.TryParse<Key>(Settings.Key_VS_DIPSwitch6, out this.DIPSwitch6);
            Enum.TryParse<Key>(Settings.Key_VS_DIPSwitch7, out this.DIPSwitch7);
            Enum.TryParse<Key>(Settings.Key_VS_DIPSwitch8, out this.DIPSwitch8);
            Enum.TryParse<Key>(Settings.Key_VS_CreditLeftCoinSlot, out this.CreditLeftCoinSlot);
            Enum.TryParse<Key>(Settings.Key_VS_CreditRightCoinSlot, out this.CreditRightCoinSlot);  
        }
 public PencilKeyInfo(Pencil.Gaming.Key key, int scancode, KeyAction action, KeyModifiers modifiers)
 {
     Key = key;
     Scancode = scancode;
     Action = action;
     Modifiers = modifiers;
 }
Beispiel #4
0
 public override void ControlHandle(Key k)
 {
     switch (k)
     {
         case Key.Up:
             if (option > 0) option--;
             if (topRow > option) topRow--;
             break;
         case Key.Down:
             if (option < Materiatory.MATERIATORY_SIZE - 1) option++;
             if (topRow < option - rows + 1) topRow++;
             break;
         case Key.X:
             if (trashing)
             {
                 MenuState.MateriaScreen.ChangeControl(MenuState.MateriaArrange);
             }
             else
             {
                 MenuState.MateriaScreen.ChangeToDefaultControl();
             }
             trashing = false;
             break;
         case Key.Circle:
             if (Trashing)
             {
                 MenuState.MateriaScreen.ChangeControl(MenuState.MateriaPrompt);
                 break;
             }
             MateriaOrb neworb = MenuState.Party.Materiatory.Get(option);
             MateriaOrb oldorb;
             switch (MenuState.MateriaTop.OptionY)
             {
                 case 0:
                     oldorb = MenuState.Party.Selected.Weapon.Slots[MenuState.MateriaTop.OptionX];
                     if (oldorb != null)
                         oldorb.Detach(MenuState.Party.Selected);
                     MenuState.Party.Materiatory.Put(oldorb, option);
                     if (neworb != null)
                         neworb.Attach(MenuState.Party.Selected);
                     MenuState.Party.Selected.Weapon.AttachMateria(neworb, MenuState.MateriaTop.OptionX);
                     MenuState.MateriaScreen.ChangeToDefaultControl();
                     break;
                 case 1:
                     oldorb = MenuState.Party.Selected.Armor.Slots[MenuState.MateriaTop.OptionX];
                     if (oldorb != null)
                         oldorb.Detach(MenuState.Party.Selected);
                     MenuState.Party.Materiatory.Put(oldorb, option);
                     if (neworb != null)
                         neworb.Attach(MenuState.Party.Selected);
                     MenuState.Party.Selected.Armor.AttachMateria(neworb, MenuState.MateriaTop.OptionX);
                     MenuState.MateriaScreen.ChangeToDefaultControl();
                     break;
                 default: break;
             }
             break;
         default:
             break;
     }
 }
Beispiel #5
0
 void RefreshData() 
 {
      _Key = null;
      _Group = null;
      
      groupKey.Visible = false;
 }
        public bool WasKeyPressed(Key key)
        {
            var previouseMouseButtonState = _previousKeyboardState[key];
            var currentMouseButtonState = _currentKeyboardState[key];

            return !previouseMouseButtonState && currentMouseButtonState;
        }
        public bool WasKeyReleased(Key key)
        {
            var previouseMouseButtonState = _previousKeyboardState[key];
            var currentMouseButtonState = _currentKeyboardState[key];

            return previouseMouseButtonState && !currentMouseButtonState;
        }
Beispiel #8
0
        /// <summary>
        /// Try and get the KeyInput which corresponds to the given Key and modifiers
        /// TODO: really think about this method
        /// </summary>
        internal bool TryGetKeyInput(Key key, ModifierKeys modifierKeys, out KeyInput keyInput)
        {
            // First just check and see if there is a direct mapping
            var keyType = new KeyType(key, modifierKeys);
            if (_cache.TryGetValue(keyType, out keyInput))
            {
                return true;
            }

            // Next consider only the shift key part of the requested modifier.  We can
            // re-apply the original modifiers later
            keyType = new KeyType(key, modifierKeys & ModifierKeys.Shift);
            if (_cache.TryGetValue(keyType, out keyInput))
            {
                // Reapply the modifiers
                keyInput = KeyInputUtil.ChangeKeyModifiers(keyInput, ConvertToKeyModifiers(modifierKeys));
                return true;
            }

            // Last consider it without any modifiers and reapply
            keyType = new KeyType(key, ModifierKeys.None);
            if (_cache.TryGetValue(keyType, out keyInput))
            {
                // Reapply the modifiers
                keyInput = KeyInputUtil.ChangeKeyModifiers(keyInput, ConvertToKeyModifiers(modifierKeys));
                return true;
            }

            return false;
        }
Beispiel #9
0
        public void ColumnName()
        {
            var x = new Key();
            Assert.IsNull(x.ColumnFamily);
            Assert.IsNull(x.ColumnQualifier);
            Assert.IsNull(x.Column);

            x = new Key { ColumnFamily = "CF" };
            Assert.AreEqual("CF", x.ColumnFamily);
            Assert.IsNull(x.ColumnQualifier);
            Assert.AreEqual("CF", x.Column);

            x = new Key { ColumnFamily = "CF", ColumnQualifier = "CQ" };
            Assert.AreEqual("CF", x.ColumnFamily);
            Assert.AreEqual("CQ", x.ColumnQualifier);
            Assert.AreEqual("CF:CQ", x.Column);

            x = new Key { Column = "CF" };
            Assert.AreEqual("CF", x.ColumnFamily);
            Assert.IsNull(x.ColumnQualifier);
            Assert.AreEqual("CF", x.Column);

            x = new Key { Column = "CF:CQ" };
            Assert.AreEqual("CF", x.ColumnFamily);
            Assert.AreEqual("CQ", x.ColumnQualifier);
            Assert.AreEqual("CF:CQ", x.Column);
        }
Beispiel #10
0
		/// <summary>
		/// Initializes a new instance of the <see cref="Xwt.KeyEventArgs"/> class.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="modifiers">The modifier keys.</param>
		/// <param name="isRepeat">the key has been pressed more then once.</param>
		/// <param name="timestamp">The timestamp of the key event.</param>
		public KeyEventArgs (Key key, ModifierKeys modifiers, bool isRepeat, long timestamp)
		{
			this.Key = key;
			this.Modifiers = modifiers;
			this.IsRepeat = isRepeat;
			this.Timestamp = timestamp;
		}
Beispiel #11
0
 protected static KeyEventArgs CreateKeyEventArgs(
     Key key,
     ModifierKeys modKeys = ModifierKeys.None)
 {
     var device = new MockKeyboardDevice(InputManager.Current) { ModifierKeysImpl = modKeys };
     return device.CreateKeyEventArgs(key, modKeys);
 }
Beispiel #12
0
        public static char GetCharFromKey(Key key)
        {
            char ch = ' ';

            int virtualKey = KeyInterop.VirtualKeyFromKey(key);
            byte[] keyboardState = new byte[256];
            GetKeyboardState(keyboardState);

            uint scanCode = MapVirtualKey((uint)virtualKey, MapType.MAPVK_VK_TO_VSC);
            StringBuilder stringBuilder = new StringBuilder(2);

            int result = ToUnicode((uint)virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0);
            switch (result)
            {
                case -1:
                    break;
                case 0:
                    break;
                case 1:
                    {
                        ch = stringBuilder[0];
                        break;
                    }
                default:
                    {
                        ch = stringBuilder[0];
                        break;
                    }
            }
            return ch;
        }
Beispiel #13
0
 public KeyboardState( params Key [] keys )
     : this()
 {
     PressedKeys = new Key [ keys.Length ];
     for ( int i = 0; i < keys.Length; i++ )
         PressedKeys [ i ] = keys [ i ];
 }
		public StoreDataCommand(Key key, object objectToBeStored, DateTime expiry)
			: base(key)
		{
			this.expiry = expiry;
			if (objectToBeStored is int)
			{
				this.objType = StoredObjectType.IntCounter;
				dataToBeStored = Encoding.UTF8.GetBytes(objectToBeStored.ToString());
			}
			else if (objectToBeStored is uint)
			{
				this.objType = StoredObjectType.UIntCounter;
				dataToBeStored = Encoding.UTF8.GetBytes(objectToBeStored.ToString());
			}
			else if (objectToBeStored is long)
			{
				this.objType = StoredObjectType.LongCounter;
				dataToBeStored = Encoding.UTF8.GetBytes(objectToBeStored.ToString());
			}
			else
			{
				this.objType = StoredObjectType.SerializableObject;
				using (MemoryStream ms = new MemoryStream())
				{
					new BinaryFormatter().Serialize(ms, objectToBeStored);
					dataToBeStored = new byte[ms.Length];
					Array.Copy(ms.GetBuffer(), dataToBeStored, dataToBeStored.Length);
				}
			}
		}
        public void KeyUp(Key key)
        {
            if (key == Key.Space)
            {
                SpaceCraft.SetThrottle(0);

                SpaceCraft.Stage();
            }

            if (key == Key.X)
            {
                SpaceCraft.SetThrottle(0);
            }

            if (key == Key.Z)
            {
                SpaceCraft.SetThrottle(100);
            }

            if (key == Key.Q && !IsRetrograde)
            {
                IsPrograde = !IsPrograde;
            }

            if (key == Key.W && !IsPrograde)
            {
                IsRetrograde = !IsRetrograde;
            }
        }
Beispiel #16
0
 protected override int procKeyEvent(Key key)
 {
     int idx = -1;
     switch (key)
     {
         case Key.UpArrow:
             _selectedIdx = (_selectedIdx - 1 < 0 ?
                 (_selectedIdx + _menuItems.Length - 1) :
                 _selectedIdx - 1) % _menuItems.Length;
             break;
         case Key.DownArrow:
             _selectedIdx = (_selectedIdx + 1) % _menuItems.Length;
             break;
         case Key.Return:
             idx = _selectedIdx; break;
         default:
             idx = 0;
             foreach (MenuItem mi in _menuItems)
             {
                 if (mi.Key == key) break;
                 idx++;
             }
             break;
     }
     return idx;
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="jointType"></param>
 /// <param name="threshold"></param>
 /// <param name="comparator"></param>
 /// <param name="name"></param>
 /// <param name="key"></param>
 protected AThresholdGesture(JointType jointType, double threshold, ThresholdComparator comparator, string name, Key key)
     : base(name, key)
 {
     this.jointType = jointType;
     this.threshold = threshold;
     this.comparator = comparator;
 }
 KeyEventArgs GetKeyEventArgs(Key key)
 {
     return new KeyEventArgs(Keyboard.PrimaryDevice, new FakePresentationSource(), 0, key)
     {
         RoutedEvent = UIElement.KeyDownEvent
     };
 }
Beispiel #19
0
        public SceneTitle()
        {
            sceneType = SceneType.Title;
            _menuItems = new MenuItem[]
            {
                new MenuItem(Key.S, "Start"),
                new MenuItem(Key.O, "Option"),
                new MenuItem(Key.Q, "Quit")
            };
            
            _keys = new Key[]
            {
                Key.UpArrow, Key.DownArrow, Key.Return, Key.M, Key.O, Key.Q
            };

            _cursor = ResourceManager.GetColoredCursorGraphic(Constants.Color_Foreground);

            if (_menuSurfaces == null)
            {
                _menuSurfaces = new SurfaceCollection();
                _menuRects = new Rectangle[_menuItems.Length];
                ImageUtil.CreateStrMenu(_menuItems, Constants.Color_Foreground, ResourceManager.MiddlePFont,
                    ref _menuSurfaces, ref _menuRects, Constants.ScreenWidth);
            }
        }
Beispiel #20
0
        public SceneGameOver()
        {
            sceneType = SceneType.GameOver;

            _menuItems = new MenuItem[]
            {
                new MenuItem(Key.R, Properties.Resources.MenuItem_RetryStage),
                new MenuItem(Key.M, Properties.Resources.MenuItem_MapSelect),
                new MenuItem(Key.T, Properties.Resources.MenuItem_ReturnTitle)
            };

            _keys = new Key[]
            {
                Key.UpArrow, Key.DownArrow, Key.Return, Key.Escape,
                Key.M, Key.R, Key.T
            };

            _cursor = ResourceManager.GetColoredCursorGraphic(_foreColor);

            _overImgSurface = ResourceManager.LoadSurface(Constants.Filename_GameoverImage);
            ImageUtil.SetColor(_overImgSurface, _foreColor);

            _menuSurfaces = new SurfaceCollection();
            _menuRects = new Rectangle[_menuItems.Length];
            ImageUtil.CreateStrMenu(_menuItems, _foreColor, ref _menuSurfaces, ref _menuRects, Constants.ScreenWidth);
        }
 public override bool ConsumeKey(Key key)
 {
     if (ActiveChild.ConsumeKey(key))
     {
         CalculateSize();
         return true;
     }
     if (key == Key.Down)
     {
         if (ActiveChild == mainRowContainer)
         {
             ActiveChild = bottomRowContainer;
             return true;
         }
     }
     else if (key == Key.Up)
     {
         if (ActiveChild == bottomRowContainer)
         {
             ActiveChild = mainRowContainer;
             return true;
         }
     }
     return false;
 }
 public CacheEntry(Key key, QrFactorization qrFactorization)
 {
     Key = key;
     QrFactorization = qrFactorization;
     MatrixCrossproduct = ImmutableMatrix.OfMatrix(ComputeMatrixCrossproduct(key.Matrix, qrFactorization.IndependentColumnIndexes));
     MatrixCrossproductInverse = ImmutableMatrix.OfMatrix(MatrixCrossproduct.Inverse());
 }
Beispiel #23
0
 public override bool TryGetToken(EndpointAddress target, EndpointAddress issuer, out GenericXmlSecurityToken cachedToken)
 {
     if (target == null)
     {
         throw new ArgumentNullException("target");
     }
     cachedToken = null;
     lock (thisLock)
     {
         GenericXmlSecurityToken tmp;
         Key key = new Key(target.Uri, issuer == null ? null : issuer.Uri);
         if (this.cache.TryGetValue(key, out tmp))
         {
             // if the cached token is going to expire soon, remove it from the cache and return a cache miss
             if (tmp.ValidTo < DateTime.UtcNow + TimeSpan.FromMinutes(1))
             {
                 this.cache.Remove(key);
                 OnTokenRemoved(key);
             }
             else
             {
                 cachedToken = tmp;
             }
         }
     }
     return (cachedToken != null);
 }
Beispiel #24
0
 public DomainEvent()
 {
     //AggregateRootId = aggregateRootId;
     //EventVersion = version;
     EventState = EventState.Sequence;
     Key = new Key { KeyName = this.GetType().Name };
 }
        public NesVSUnisystemDIPKeyboardConnection(IntPtr handle, IInputSettingsVSUnisystemDIP settings)
        {
            DirectInput di = new DirectInput();
            keyboard = new Keyboard(di);
            keyboard.SetCooperativeLevel(handle, CooperativeLevel.Nonexclusive | CooperativeLevel.Foreground);

            if (settings.CreditServiceButton != "")
                CreditServiceButton = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.CreditServiceButton);
            if (settings.DIPSwitch1 != "")
                DIPSwitch1 = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.DIPSwitch1);
            if (settings.DIPSwitch2 != "")
                DIPSwitch2 = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.DIPSwitch2);
            if (settings.DIPSwitch3 != "")
                DIPSwitch3 = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.DIPSwitch3);
            if (settings.DIPSwitch4 != "")
                DIPSwitch4 = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.DIPSwitch4);
            if (settings.DIPSwitch5 != "")
                DIPSwitch5 = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.DIPSwitch5);
            if (settings.DIPSwitch6 != "")
                DIPSwitch6 = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.DIPSwitch6);
            if (settings.DIPSwitch7 != "")
                DIPSwitch7 = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.DIPSwitch7);
            if (settings.DIPSwitch8 != "")
                DIPSwitch8 = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.DIPSwitch8);
            if (settings.CreditLeftCoinSlot != "")
                CreditLeftCoinSlot = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.CreditLeftCoinSlot);
            if (settings.CreditRightCoinSlot != "")
                CreditRightCoinSlot = (SlimDX.DirectInput.Key)Enum.Parse(typeof(SlimDX.DirectInput.Key), settings.CreditRightCoinSlot);
            NesEmu.EMUShutdown += NesEmu_EMUShutdown;
        }
        public void The_Corresponding_Relationship_Should_Also_Have_The_Column_Removed()
        {
            // Create database and relationships
            Database db = RelationshipDatabaseLoader.GetDb();

            Relationship relationship = db.Tables[1].Relationships[0];
            Assert.That(relationship.PrimaryKey, Is.SameAs(db.Tables[0].Keys[0]));
            Assert.That(relationship.ForeignKey, Is.SameAs(db.Tables[1].Keys[0]));
            Assert.That(relationship.PrimaryKey.Columns[0].Name, Is.EqualTo("Column1"));
            Assert.That(relationship.PrimaryKey.Columns[1].Name, Is.EqualTo("Column2"));

            IKey originalKey = db.Tables[1].Keys[0];

            IKey newKey = new Key(originalKey.Name, originalKey.Keytype);
            newKey.Parent = new Table("Table2");
            newKey.Parent.AddColumn(new Column("Column2"));
            newKey.Description = "new description";
            newKey.AddColumn("Column2");

            KeyChangeOperation op = new KeyChangeOperation(db.Tables[1].Keys[0], newKey);
            op.RunOperation();
            op.RunSecondStep();

            // Make sure the relationship is still the same, and has the same references.
            Relationship relationship2 = db.Tables[1].Relationships[0];
            Assert.That(relationship2, Is.SameAs(relationship));
            Assert.That(relationship2.PrimaryKey, Is.SameAs(db.Tables[0].Keys[0]));
            Assert.That(relationship2.ForeignKey, Is.SameAs(db.Tables[1].Keys[0]));
            Assert.That(relationship2.PrimaryKey.Columns, Has.Count(2));
            Assert.That(relationship2.ForeignKey.Columns, Has.Count(1));
            Assert.That(relationship2.ForeignKey.Columns[0].Name, Is.EqualTo("Column2"));
        }
Beispiel #27
0
		public KeyEventArgs (KeyboardDevice keyboard, PresentationSource inputSource,
				     int timestamp, Key key)
			: base (keyboard, timestamp)
		{
			this.inputSource = inputSource;
			this.key = key;
		}
Beispiel #28
0
		public IconButton(IGameWindow window, Camera<OrthographicProjection> camera, Vector2 position, IRenderable renderable, Key? hotkey = null)
			: base(window, camera, position)
		{
			Renderable = renderable;
			IsSelected = false;
			Hotkey = hotkey;
		}
 public PlayerViewModel(string name, Key key, int allowedShots)
 {
     Name = name;
     Key = key;
     AllowedShots = allowedShots;
     scores = new Dictionary<string, int>();
 }
Beispiel #30
0
 protected override bool OnKeyPressed(Key key, char? character, bool repeat)
 {
     if (Shortcut == null || repeat || Shortcut != key)
         return false;
     Clicked.Raise();
     return true;
 }
Beispiel #31
0
        internal void MergeRows(DataRow[] rows)
        {
            Debug.Assert(_dataSet != null);

            DataTable?src       = null;
            DataTable?dst       = null;
            DataKey   key       = default(DataKey);
            Index?    ndxSearch = null;

            bool fEnforce = _dataSet.EnforceConstraints;

            _dataSet.EnforceConstraints = false;

            for (int i = 0; i < rows.Length; i++)
            {
                DataRow row = rows[i];

                if (row == null)
                {
                    throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}]");
                }
                if (row.Table == null)
                {
                    throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}].{nameof(DataRow.Table)}");
                }

                //somebody is doing an 'automerge'
                if (row.Table.DataSet == _dataSet)
                {
                    continue;
                }

                if (src != row.Table)
                {                     // row.Table changed from prev. row.
                    src = row.Table;
                    dst = MergeSchema(row.Table);
                    if (dst == null)
                    {
                        Debug.Assert(MissingSchemaAction.Ignore == _missingSchemaAction, "MergeSchema failed");
                        _dataSet.EnforceConstraints = fEnforce;
                        return;
                    }
                    if (dst._primaryKey != null)
                    {
                        key = GetSrcKey(src, dst);
                    }
                    if (key.HasValue)
                    {
                        // Getting our own copy instead. ndxSearch = dst.primaryKey.Key.GetSortIndex();
                        // IMO, Better would be to reuse index
                        // ndxSearch = dst.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added );
                        if (null != ndxSearch)
                        {
                            ndxSearch.RemoveRef();
                            ndxSearch = null;
                        }
                        ndxSearch = new Index(dst, dst._primaryKey !.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, null);
                        ndxSearch.AddRef(); // need to addref twice, otherwise it will be collected
                        ndxSearch.AddRef(); // in past first adref was done in const
                    }
                }

                if (row._newRecord == -1 && row._oldRecord == -1)
                {
                    continue;
                }

                DataRow?targetRow = null;
                if (0 < dst !.Rows.Count && ndxSearch != null)
                {
                    targetRow = dst.FindMergeTarget(row, key, ndxSearch);
                }

                targetRow = dst.MergeRow(row, targetRow, _preserveChanges, ndxSearch);

                if (targetRow.Table._dependentColumns != null && targetRow.Table._dependentColumns.Count > 0)
                {
                    targetRow.Table.EvaluateExpressions(targetRow, DataRowAction.Change, null);
                }
            }
            if (null != ndxSearch)
            {
                ndxSearch.RemoveRef();
                ndxSearch = null;
            }

            _dataSet.EnforceConstraints = fEnforce;
        }
Beispiel #32
0
 public bool IsKeyDown(Key key) => _keysDown.Contains(key);
Beispiel #33
0
 // Gets registered dependencies and lifetimes
 public bool TryGetDependency(Key key, out IoC.IDependency dependency, out ILifetime lifetime)
 => Parent.TryGetDependency(key, out dependency, out lifetime);
Beispiel #34
0
        /// <summary>
        /// Processes keyboard input.
        /// </summary>
        private void processKeyInput()
        {
            if (!Input.anyKeyDown)
            {
                return;
            }

            // Fix for a bug in Linux where typing would still control game elements even if
            // a textbox was focused.
            if (GUIUtility.keyboardControl != 0)
            {
                return;
            }

            // process any key input for settings
            if (waitForKey)
            {
                KeyCode key = NodeTools.fetchKey();
                // if the time is up or we have no key to process, reset.
                if (((keyWaitTime + 5.0) < Planetarium.GetUniversalTime()) || key == KeyCode.None)
                {
                    currentWaitKey = Key.NONE;
                    waitForKey     = false;
                    return;
                }

                // which key are we waiting for?
                switch (currentWaitKey)
                {
                case Key.PROGINC:
                    options.progInc = key;
                    break;

                case Key.PROGDEC:
                    options.progDec = key;
                    break;

                case Key.NORMINC:
                    options.normInc = key;
                    break;

                case Key.NORMDEC:
                    options.normDec = key;
                    break;

                case Key.RADIINC:
                    options.radiInc = key;
                    break;

                case Key.RADIDEC:
                    options.radiDec = key;
                    break;

                case Key.TIMEINC:
                    options.timeInc = key;
                    break;

                case Key.TIMEDEC:
                    options.timeDec = key;
                    break;

                case Key.PAGEINC:
                    options.pageIncrement = key;
                    break;

                case Key.PAGECON:
                    options.pageConics = key;
                    break;

                case Key.HIDEWINDOW:
                    options.hideWindow = key;
                    break;

                case Key.ADDWIDGET:
                    options.addWidget = key;
                    break;
                }
                currentWaitKey = Key.NONE;
                waitForKey     = false;
                return;
            }

            // process normal keyboard input
            // change increment
            if (Input.GetKeyDown(options.pageIncrement))
            {
                if (Event.current.alt)
                {
                    options.downIncrement();
                }
                else
                {
                    options.upIncrement();
                }
            }
            // prograde increment
            if (Input.GetKeyDown(options.progInc))
            {
                curState.addPrograde(options.increment);
            }
            // prograde decrement
            if (Input.GetKeyDown(options.progDec))
            {
                curState.addPrograde(-options.increment);
            }
            // normal increment
            if (Input.GetKeyDown(options.normInc))
            {
                curState.addNormal(options.increment);
            }
            // normal decrement
            if (Input.GetKeyDown(options.normDec))
            {
                curState.addNormal(-options.increment);
            }
            // radial increment
            if (Input.GetKeyDown(options.radiInc))
            {
                curState.addRadial(options.increment);
            }
            // radial decrement
            if (Input.GetKeyDown(options.radiDec))
            {
                curState.addRadial(-options.increment);
            }
            // UT increment
            if (Input.GetKeyDown(options.timeInc))
            {
                curState.addUT(options.increment * (options.largeUTIncrement ? 10.0 : 1.0));
            }
            // UT decrement
            if (Input.GetKeyDown(options.timeDec))
            {
                curState.addUT(-options.increment * (options.largeUTIncrement ? 10.0 : 1.0));
            }
            // Page Conics
            if (Input.GetKeyDown(options.pageConics))
            {
                options.pageConicsMode();
            }
            // hide/show window
            if (Input.GetKeyDown(options.hideWindow))
            {
                shown = !shown;
            }
            // open node gizmo
            if (Input.GetKeyDown(options.addWidget))
            {
                curState.node.CreateNodeGizmo();
            }
        }
Beispiel #35
0
        protected override Expression VisitFieldExpression(FieldExpression expression)
        {
            var tupleExpression = GetTupleExpression(expression);

            // Materialize non-owned field.
            if (expression.Owner == null || expression.UnderlyingProperty == null)
            {
                if (expression.Field.IsEnum)
                {
                    var underlyingType = Enum.GetUnderlyingType(expression.Type.StripNullable());
                    if (expression.Field.IsNullable)
                    {
                        underlyingType = underlyingType.ToNullable();
                    }
                    var result = Expression.Convert(
                        tupleExpression.MakeTupleAccess(underlyingType, expression.Mapping.Offset),
                        expression.Type);
                    return(result);
                }
                if (WellKnownOrmTypes.Key.IsAssignableFrom(expression.Field.ValueType))
                {
                    Expression <Func <Domain, string, Key> > keyParseLambda = (d, s) => Key.Parse(d, s);
                    Expression <Func <ItemMaterializationContext, Domain> > domainExtractorLambda = imc => imc.Session.Domain;
                    var result = keyParseLambda.BindParameters(
                        domainExtractorLambda.BindParameters(itemMaterializationContextParameter),
                        tupleExpression.MakeTupleAccess(WellKnownTypes.String, expression.Mapping.Offset));
                    return(result);
                }

                var tupleAccess = tupleExpression.MakeTupleAccess(expression.Type, expression.Mapping.Offset);
                return(tupleAccess);
            }

            return(MaterializeThroughOwner(expression, tupleExpression));
        }
Beispiel #36
0
 internal static bool IsMouse(this Key @this)
 {
     return((int)@this > (int)Key.KeyCount);
 }
 public static SetRolesRequest Deserialize(Stream stream, SetRolesRequest instance, long limit)
 {
     if (instance.Role == null)
     {
         instance.Role = new List <uint>();
     }
     if (instance.MemberId == null)
     {
         instance.MemberId = new List <EntityId>();
     }
     while (true)
     {
         if (limit < (long)0 || stream.Position < limit)
         {
             int num = stream.ReadByte();
             if (num == -1)
             {
                 if (limit >= (long)0)
                 {
                     throw new EndOfStreamException();
                 }
                 break;
             }
             else if (num == 10)
             {
                 if (instance.AgentId != null)
                 {
                     EntityId.DeserializeLengthDelimited(stream, instance.AgentId);
                 }
                 else
                 {
                     instance.AgentId = EntityId.DeserializeLengthDelimited(stream);
                 }
             }
             else if (num == 18)
             {
                 long position = (long)ProtocolParser.ReadUInt32(stream);
                 position += stream.Position;
                 while (stream.Position < position)
                 {
                     instance.Role.Add(ProtocolParser.ReadUInt32(stream));
                 }
                 if (stream.Position != position)
                 {
                     throw new ProtocolBufferException("Read too many bytes in packed data");
                 }
             }
             else if (num == 26)
             {
                 instance.MemberId.Add(EntityId.DeserializeLengthDelimited(stream));
             }
             else
             {
                 Key key = ProtocolParser.ReadKey((byte)num, stream);
                 if (key.Field == 0)
                 {
                     throw new ProtocolBufferException("Invalid field id: 0, something went wrong in the stream");
                 }
                 ProtocolParser.SkipKey(stream, key);
             }
         }
         else
         {
             if (stream.Position != limit)
             {
                 throw new ProtocolBufferException("Read past max limit");
             }
             break;
         }
     }
     return(instance);
 }
Beispiel #38
0
 protected ForeignKey CreateForeignKey(Key dependentKey, Key principalKey)
 => CreateForeignKey(dependentKey.DeclaringEntityType, dependentKey.Properties, principalKey);
        static void Main(string[] args)
        {
            // The code provided will print ‘Hello World’ to the console.
            // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
            Console.WriteLine("Hello Omnibasis!");

            var testTransfer = false;
            //define connections
            var conn1Config = new Dictionary <string, object>();

            //config connection 1
            conn1Config.Add("baseUrl", "https://test.ipdb.io");
            BlockchainConnection conn1 = new BlockchainConnection(conn1Config);

            var conn2Config = new Dictionary <string, object>();
            var headers2    = new Dictionary <string, string>();

            //config connection 2
            conn2Config.Add("baseUrl", "https://test.ipdb.io");
            BlockchainConnection conn2 = new BlockchainConnection(conn2Config);

            //add connections
            IList <BlockchainConnection> connections = new List <BlockchainConnection>();

            connections.Add(conn1);
            connections.Add(conn2);
            //...You can add as many nodes as you want

            //multiple connections
            var builderWithConnections = BigchainDbConfigBuilder
                                         .addConnections(connections)
                                         .setTimeout(60000); //override default timeout of 20000 milliseconds

            // single connection
            var builder = BigchainDbConfigBuilder
                          .baseUrl("https://test.ipdb.io");

            if (!AsyncContext.Run(() => builder.setup()))
            {
                Console.WriteLine("Failed to setup");
            }
            ;

            // prepare your key
            var algorithm  = SignatureAlgorithm.Ed25519;
            var privateKey = Key.Import(algorithm, Utils.StringToByteArray(privateKeyString), KeyBlobFormat.PkixPrivateKey);
            var publicKey  = PublicKey.Import(algorithm, Utils.StringToByteArray(publicKeyString), KeyBlobFormat.PkixPublicKey);
            //Account account = new Account();

            //Dictionary<string, string> assetData = new Dictionary<string, string>();
            //assetData.Add("msg", "Hello!");

            Random    random    = new Random();
            TestAsset assetData = new TestAsset();

            assetData.msg         = "Hello Omnibasis!";
            assetData.city        = "I was born in San Diego";
            assetData.temperature = random.Next(60, 80);
            assetData.datetime    = DateTime.Now;

            //MetaData metaData = new MetaData();
            //metaData.setMetaData("msg", "My first transaction");
            TestMetadata metaData = new TestMetadata();

            metaData.msg = "My first transaction";

            // Set up, sign, and send your transaction
            var transaction = BigchainDbTransactionBuilder <TestAsset, TestMetadata>
                              .init()
                              .addAssets(assetData)
                              .addMetaData(metaData)
                              .operation(Operations.CREATE)
                              .buildAndSignOnly(publicKey, privateKey);

            //.buildAndSign(account.PublicKey, account.PrivateKey);

            //var info = transaction.toHashInput();
            var    createTransaction = AsyncContext.Run(() => TransactionsApi <TestAsset, TestMetadata> .sendTransactionAsync(transaction));
            string assetId2          = "";

            // the asset's ID is equal to the ID of the transaction that created it
            if (createTransaction != null && createTransaction.Data != null)
            {
                assetId2 = createTransaction.Data.Id;
                //"2984ac294290ce6f15124140dad652fc8a306aca62c38237174988dfcf31a3e6"
                var testTran2 = AsyncContext.Run(() => TransactionsApi <object, object> .getTransactionByIdAsync(assetId2));
                if (testTran2 != null)
                {
                    Console.WriteLine("Hello assetId: " + assetId2);
                }
                else
                {
                    Console.WriteLine("Failed to find assetId: " + assetId2);
                }
            }
            else if (createTransaction != null)
            {
                Console.WriteLine("Failed to send transaction: " + createTransaction.Messsage.Message);
            }


            //}
            if (!string.IsNullOrEmpty(assetId2) && testTransfer)
            {
                // Describe the output you are fulfilling on the previous transaction
                FulFill spendFrom = new FulFill();
                spendFrom.TransactionId = assetId2;
                spendFrom.OutputIndex   = 0;

                // Change the metadata if you want
                //MetaData transferMetadata = new MetaData();
                //metaData.setMetaData("msg", "My second transaction");
                TestMetadata transferMetadata = new TestMetadata();
                transferMetadata.msg = "My second transaction";

                // the asset's ID is equal to the ID of the transaction that created it
                // By default, the 'amount' of a created digital asset == "1". So we spend "1" in our TRANSFER.
                string            amount  = "1";
                BlockchainAccount account = new BlockchainAccount();
                Details           details = null;
                // Use the previous transaction's asset and TRANSFER it
                var build2 = BigchainDbTransactionBuilder <Asset <string>, TestMetadata> .
                             init().
                             addMetaData(metaData).
                             addInput(details, spendFrom, publicKey).
                             addOutput("1", account.Key.PublicKey).
                             addAssets(assetId2).
                             operation(Operations.TRANSFER).
                             buildAndSignOnly(publicKey, privateKey);

                var transferTransaction = AsyncContext.Run(() => TransactionsApi <Asset <string>, TestMetadata> .sendTransactionAsync(build2));

                if (transferTransaction != null && transferTransaction.Data != null)
                {
                    string assetIdTransfer = transferTransaction.Data.Id;
                    var    testTran2       = AsyncContext.Run(() => TransactionsApi <object, object> .getTransactionByIdAsync(assetIdTransfer));
                    if (testTran2 != null)
                    {
                        Console.WriteLine("Hello transfer assetId: " + assetIdTransfer);
                    }
                    else
                    {
                        Console.WriteLine("Failed to find transfer assetId: " + assetIdTransfer);
                    }
                }
                else if (transferTransaction != null)
                {
                    Console.WriteLine("Failed to send transaction: " + createTransaction.Messsage.Message);
                }
            }


            Console.ReadKey(true);

            // Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app!
        }
Beispiel #40
0
        protected ForeignKey CreateForeignKey(EntityType dependEntityType, IReadOnlyList <Property> dependentProperties, Key principalKey)
        {
            var foreignKey = dependEntityType.AddForeignKey(dependentProperties, principalKey, principalKey.DeclaringEntityType);

            foreignKey.IsUnique = true;

            return(foreignKey);
        }
Beispiel #41
0
 object IProjectModelElement.GetProperty(Key propertyName)
 {
     return(_dataHolder.GetData(propertyName));
 }
Beispiel #42
0
        private void HandleKey(Key key, RawKeyEventType type)
        {
            var rawKeyEvent = new RawKeyEventArgs(KeyboardDevice.Instance, (uint)DateTime.Now.Ticks, type, key, InputModifiers.None);

            _view.Input(rawKeyEvent);
        }
Beispiel #43
0
 public void PutData <T>(Key <T> key, T val) where T : class
 {
     _dataHolder.PutData(key, val);
 }
Beispiel #44
0
 void IProjectModelElement.SetProperty(Key propertyName, object propertyValue)
 {
     _dataHolder.PutData(propertyName, propertyValue);
 }
Beispiel #45
0
 public HotKeyIsSetEventArgs(RoutedEvent routedevent, Key key, ModifierKeys modifier)
     : base(routedevent)
 {
     UserKey      = key;
     UserModifier = modifier;
 }
Beispiel #46
0
 public T GetData <T>(Key <T> key) where T : class
 {
     return(_dataHolder.GetData(key));
 }
Beispiel #47
0
        public override void ControlHandle(Key k)
        {
            switch (k)
            {
            case Key.Up:
                if (_option > 0)
                {
                    _option--;
                }
                if (_topRow > _option)
                {
                    _topRow--;
                }
                break;

            case Key.Down:
                if (_option < _equipment.Count - 1)
                {
                    _option++;
                }
                if (_topRow < _option - rows + 1)
                {
                    _topRow++;
                }
                break;

            case Key.Circle:

                MenuState.EquipTop.Changed = true;

                switch (MenuState.EquipTop.Option)
                {
                case 0:
                    MenuState.Party.Materiatory.Swap(MenuState.Party.Selected.Weapon, (Weapon)_equipment[_option].Item, MenuState.Party.Selected);
                    MenuState.Party.Inventory.AddToInventory(MenuState.Party.Selected.Weapon);
                    MenuState.Party.Selected.Weapon = (Weapon)_equipment[_option].Item;
                    break;

                case 1:
                    MenuState.Party.Materiatory.Swap(MenuState.Party.Selected.Armor, (Armor)_equipment[_option].Item, MenuState.Party.Selected);
                    MenuState.Party.Inventory.AddToInventory(MenuState.Party.Selected.Armor);
                    MenuState.Party.Selected.Armor = (Armor)_equipment[_option].Item;
                    break;

                case 2:

                    if (MenuState.Party.Selected.Accessory != null)
                    {
                        MenuState.Party.Inventory.AddToInventory(MenuState.Party.Selected.Accessory);
                    }

                    MenuState.Party.Selected.Accessory = (Accessory)_equipment[_option].Item;
                    break;
                }

                MenuState.Party.Inventory.DecreaseCount(_equipment[_option].Slot);
                MenuState.EquipScreen.ChangeToDefaultControl();

                break;

            case Key.X:
                MenuState.EquipScreen.ChangeToDefaultControl();
                break;
            }
        }
 protected override bool HandleKeyPress(Key key)
 {
     return(Judgement.Result == HitResult.None && UpdateJudgement(true));
 }
Beispiel #49
0
        static Клавиатура()
        {
            //var КультураИнфо = InputLanguageManager.Current.CurrentInputLanguage;

            byte первый    = 0;
            byte последний = 172;

            var именаКлавиш = Enum.GetNames(typeof(Key));
            var номер       = Enum.ToObject(typeof(Key), 10);
            var h           = new Key();
            var Юникод      = (int)Key.A;

            foreach (var клавиша in  именаКлавиш)
            {
                Клавиши.Добавить(new СтрокаЮникода(клавиша));
            }



            ЮНИКОДСимволКодыРусскихБуквПрописные = new ГруппаТипизированная()
            {
                ТипХранящихсяОбъектов = typeof(Символ)
            };
            var ЮНИКОДСимволКодыРусскихБуквЗаглавные = new ГруппаТипизированная()
            {
                ТипХранящихсяОбъектов = typeof(Символ)
            };

            ЮНИКОДРусскихБукв = new ГруппаОбъектов();

            char большая;

            for (var с = 'а'; с <= 'е'; с++)
            {
                большая = с.ToString().ToUpper()[0];
                ЮНИКОДСимволКодыРусскихБуквПрописные.Добавить(new Символ(большая));
                ЮНИКОДСимволКодыРусскихБуквПрописные.Добавить(new Символ(с));
                ЮНИКОДРусскихБукв.Добавить(new ЦелоеЧисло(с));
            }
            большая = 'ё'.ToString().ToUpper()[0];
            ЮНИКОДСимволКодыРусскихБуквПрописные.Добавить(new Символ(большая));
            ЮНИКОДСимволКодыРусскихБуквПрописные.Добавить(new Символ('ё'));
            ЮНИКОДРусскихБукв.Добавить(new ЦелоеЧисло('ё'));
            for (var с = 'ж'; с <= 'я'; с++)
            {
                большая = с.ToString().ToUpper()[0];
                ЮНИКОДСимволКодыРусскихБуквПрописные.Добавить(new Символ(большая));
                ЮНИКОДСимволКодыРусскихБуквПрописные.Добавить(new Символ(с));
                ЮНИКОДРусскихБукв.Добавить(new ЦелоеЧисло(с));
            }

            var русскаяРаскладка = new Dictionary <Key, char>
            {
                [Key.F]         = 'а',
                [Key.OemComma]  = 'б',
                [Key.D]         = 'в',
                [Key.U]         = 'г',
                [Key.L]         = 'д',
                [Key.T]         = 'е',
                [Key.Oem3]      = 'ё',
                [Key.Oem1]      = 'ж',
                [Key.P]         = 'з',
                [Key.B]         = 'и',
                [Key.Q]         = 'й',
                [Key.R]         = 'к',
                [Key.K]         = 'л',
                [Key.V]         = 'м',
                [Key.Y]         = 'н',
                [Key.J]         = 'о',
                [Key.G]         = 'п',
                [Key.H]         = 'р',
                [Key.C]         = 'с',
                [Key.N]         = 'т',
                [Key.E]         = 'у',
                [Key.A]         = 'ф',
                [Key.Oem4]      = 'х',
                [Key.W]         = 'ц',
                [Key.I]         = 'ш',
                [Key.O]         = 'щ',
                [Key.M]         = 'ь',
                [Key.Oem6]      = 'ъ',
                [Key.Oem7]      = 'э',
                [Key.OemPeriod] = 'ю',
                [Key.Z]         = 'я'
            };

            усскаяРаскладка = new Dictionary <Key, Адрес>();
            // здесь должна быть пара key, modifiers

            //}; // или Инт это трансформация
            // слварь это описание типа связей между элементами (одностороней поиск по ключу)
            // клавишам можно сопаставить действия (удалить, Вставить,)
            //var словарьЮникода = new Dictionary<Адрес, Строка>(); // либо инт
            foreach (var key in русскаяРаскладка.Keys)
            {
                try
                {
                    var символ = русскаяРаскладка[key];
                    усскаяРаскладка[key] =
                        ЮНИКОДСимволКодыРусскихБуквПрописные.Список.Find(
                            c => ((Символ)c).Значение == символ).СобственныйАдресПримитива;
                }
                catch { }
            }
        }
Beispiel #50
0
 public HotKeyEventArgs(Key key, ModifierKeys modifier, RaiseLocalEvent KeyPressevent)
 {
     Key           = key;
     Modifier      = modifier;
     KeyPressEvent = KeyPressevent;
 }
Beispiel #51
0
        private static Transaction CreateTransaction(Network network, Key inkey, int height, Money amount, Key outKey, uint256 prevOutHash)
        {
            var coinbase = new Transaction();

            coinbase.AddInput(new TxIn(new OutPoint(prevOutHash, 1), inkey.ScriptPubKey));
            coinbase.AddOutput(new TxOut(amount, outKey));
            return(coinbase);
        }
        public static AccountFieldTags Deserialize(Stream stream, AccountFieldTags instance, long limit)
        {
            BinaryReader binaryReader = new BinaryReader(stream);

            if (instance.GameLevelInfoTags == null)
            {
                instance.GameLevelInfoTags = new List <ProgramTag>();
            }
            if (instance.GameStatusTags == null)
            {
                instance.GameStatusTags = new List <ProgramTag>();
            }
            if (instance.GameAccountTags == null)
            {
                instance.GameAccountTags = new List <RegionTag>();
            }
            while (true)
            {
                if (limit < (long)0 || stream.Position < limit)
                {
                    int num = stream.ReadByte();
                    if (num == -1)
                    {
                        if (limit >= (long)0)
                        {
                            throw new EndOfStreamException();
                        }
                        break;
                    }
                    else if (num == 21)
                    {
                        instance.AccountLevelInfoTag = binaryReader.ReadUInt32();
                    }
                    else if (num == 29)
                    {
                        instance.PrivacyInfoTag = binaryReader.ReadUInt32();
                    }
                    else if (num == 37)
                    {
                        instance.ParentalControlInfoTag = binaryReader.ReadUInt32();
                    }
                    else if (num == 58)
                    {
                        instance.GameLevelInfoTags.Add(ProgramTag.DeserializeLengthDelimited(stream));
                    }
                    else if (num == 74)
                    {
                        instance.GameStatusTags.Add(ProgramTag.DeserializeLengthDelimited(stream));
                    }
                    else if (num == 90)
                    {
                        instance.GameAccountTags.Add(RegionTag.DeserializeLengthDelimited(stream));
                    }
                    else
                    {
                        Key key = ProtocolParser.ReadKey((byte)num, stream);
                        if (key.Field == 0)
                        {
                            throw new ProtocolBufferException("Invalid field id: 0, something went wrong in the stream");
                        }
                        ProtocolParser.SkipKey(stream, key);
                    }
                }
                else
                {
                    if (stream.Position != limit)
                    {
                        throw new ProtocolBufferException("Read past max limit");
                    }
                    break;
                }
            }
            return(instance);
        }
Beispiel #53
0
        private static ChainIndexer GenerateChainWithHeightAndActivatedBip9(int blockAmount, Network network, Key key, BIP9DeploymentsParameters parameter, Target bits = null)
        {
            var     chain         = new ChainIndexer(network);
            uint    nonce         = RandomUtils.GetUInt32();
            uint256 prevBlockHash = chain.Genesis.HashBlock;

            for (int i = 0; i < blockAmount; i++)
            {
                Block       block    = network.Consensus.ConsensusFactory.CreateBlock();
                Transaction coinbase = CreateCoinbaseTransaction(network, key, chain.Height + 1);

                block.AddTransaction(coinbase);
                block.UpdateMerkleRoot();
                block.Header.BlockTime     = new DateTimeOffset(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddDays(i));
                block.Header.HashPrevBlock = prevBlockHash;
                block.Header.Nonce         = nonce;

                if (bits != null)
                {
                    block.Header.Bits = bits;
                }

                if (parameter != null)
                {
                    uint version = ThresholdConditionCache.VersionbitsTopBits;
                    version |= ((uint)1) << parameter.Bit;
                    block.Header.Version = (int)version;
                }

                chain.SetTip(block.Header);
                prevBlockHash = block.GetHash();
            }

            return(chain);
        }
Beispiel #54
0
        private void OtpInformation_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            try
            {
                if (string.IsNullOrEmpty(this.textBoxKey.Text))
                {
                    MessageBox.Show("A key must be set");
                    e.Cancel = true;
                    return;
                }

                if (this.textBoxKey.Text.Length < 8)
                {
                    MessageBox.Show("Key must be at least 8 characters.  If you are provided with less data then pad it up to 8 characters with '='s");
                    e.Cancel = true;
                    return;
                }

                // set the default settings
                int         size     = 6;
                int         step     = 30;
                OtpHashMode hashMode = OtpHashMode.Sha1;
                Key         key      = null;

                if (this.checkBoxCustomSettings.Checked)
                {
                    size = (this.radioButtonEight.Checked) ? 8 : 6;
                    if (int.TryParse(this.textBoxStep.Text, out step))
                    {
                        if (step != 30)
                        {
                            if (step <= 0)
                            {
                                this.textBoxStep.Text = "30";
                                MessageBox.Show("The time step must be a non-zero positive integer.  The standard value is 30.  If you weren't specifically given an alternate value just use 30.");
                                e.Cancel = true;
                                return;
                            }
                            else if (MessageBox.Show("You have selected a non-standard time step.  30 is the standard recommended value.  You should only proceed if you were specifically told to use this time step size.  Do you wish to proceed?", "Non-standard time step size", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                            {
                                e.Cancel = true;
                                return;
                            }
                        }
                    }
                    else
                    {
                        this.textBoxStep.Text = "30";
                        MessageBox.Show("The time step must be a non-zero positive integer.  The standard value is 30.  If you weren't specifically given an alternate value just use 30.");
                        e.Cancel = true;
                        return;
                    }
                    // need to do encoding here
                    key = ProtectedKey.CreateProtectedKeyAndDestroyPlaintextKey(Base32.Decode(this.textBoxKey.Text.Replace(" ", string.Empty).Replace("-", string.Empty)));
                }
                else
                {
                    key = ProtectedKey.CreateProtectedKeyAndDestroyPlaintextKey(Base32.Decode(this.textBoxKey.Text.Replace(" ", string.Empty).Replace("-", string.Empty)));
                }

                // hashmode
                if (this.radioButtonSha1.Checked)
                {
                    hashMode = OtpHashMode.Sha1;
                }
                else if (this.radioButtonSha256.Checked)
                {
                    hashMode = OtpHashMode.Sha256;
                }
                else if (this.radioButtonSha512.Checked)
                {
                    hashMode = OtpHashMode.Sha512;
                }

                this.Data = new OtpAuthData()
                {
                    Key         = key,
                    Size        = size,
                    Step        = step,
                    OtpHashMode = hashMode
                };
            }
            catch
            {
                e.Cancel = true;
            }
        }
Beispiel #55
0
 /// Checks to see if the given key is held down. Will poll the keyboard for fresh data before checking.
 /// </summary>
 /// <param name="k">The key to check.</param>
 /// <returns>True if the key is held down, false otherwise.</returns>
 public static bool isKeyHeldDown(Key k)
 {
     return(isKeyHeldDown(k, true));
 }
Beispiel #56
0
 private static ChainIndexer GenerateChainWithHeight(int blockAmount, Network network, Key key, Target bits = null)
 {
     return(GenerateChainWithHeightAndActivatedBip9(blockAmount, network, key, null, bits));
 }
Beispiel #57
0
 public DasState(Key key)
 {
     PressedKey = key;
 }
Beispiel #58
0
 /// <summary>
 /// Checks to see if the press of this key is the first press, and polls the keyboard for the most up-to-date data.
 /// </summary>
 /// <param name="k">The key to check.</param>
 /// <returns>True if this is the first press; else false</returns>
 public static bool isFirstPress(Key k)
 {
     return(isFirstPress(k, true));
 }
Beispiel #59
0
 /// <summary>
 /// Returns the hash code value for this map entry.
 /// </summary>
 /// <returns>Hash code.</returns>
 public override int GetHashCode()
 {
     return(((Key == null)    ? 0 : Key.GetHashCode()) ^
            ((Value == null) ? 0 : Value.GetHashCode()));
 }
Beispiel #60
0
 public AutoShiftState(Key key)
 {
     PressedKey = key;
 }