Example #1
0
        public ActionResult Send()
        {
            var rendering  = Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull?.Rendering;
            var parameters = rendering?.Parameters;
            var makerKey   = ItemUtil.GetItemById(parameters?[Templates.Parameters.MakerKey])?[Templates.Account.Fields.MakerKey];
            var eventName  = ItemUtil.GetItemById(parameters?[Templates.Parameters.Event])?[Templates.Event.Fields.EventName];
            var threshold  = int.TryParse(parameters?[Templates.Parameters.Threshold], out int num)? num : -1;
            var value1     = parameters?[Templates.Parameters.Value1];
            var value2     = parameters?[Templates.Parameters.Value2];
            var value3     = parameters?[Templates.Parameters.Value3];

            if (threshold > 1)
            {
                var thresholdKey = KeyUtil.MakeKey(
                    $"{nameof(TriggerController)}_{nameof(Send)}_",
                    Sitecore.Context.Item?.ID.ToGuid().ToString(),
                    rendering?.UniqueId
                    );

                if (Threshold.IsMet(threshold, thresholdKey))
                {
                    Ifttt.Trigger(makerKey, eventName, value1, value2, value3);
                    return(Content($"<p>Threshold met, trigger '{eventName}' sent!</p>"));
                }
                else
                {
                    return(Content("<p>Threshold incremented</p>"));
                }
            }

            Ifttt.Trigger(makerKey, eventName, value1, value2, value3);
            return(Content($"<p>Trigger '{eventName}' sent!</p>"));
        }
Example #2
0
        public unsafe void EntityKeyTest()
        {
            //00002001-3000-15D78851776115104102
            ulong flags1       = 1 << 1;                           //RaftType | MvccFlag | OrderFlag
            ulong raftGroupId1 = (1ul << 36) | (flags1 << 32 | 3); //AppId << 36 | flags << 32 | counter

            EntityId id = Guid.Empty;

            id.InitRaftGroupId(raftGroupId1);

            byte *keyPtr = stackalloc byte[KeyUtil.ENTITY_KEY_SIZE];

            KeyUtil.WriteEntityKey(keyPtr, id);
            var hex = StringHelper.ToHexString(new IntPtr(keyPtr), KeyUtil.ENTITY_KEY_SIZE);

            Assert.Equal("00002001300000000000000000000000", hex);

            ulong flags2       = 1 << 1 | 1;
            ulong raftGroupId2 = (1ul << 36) | (flags2 << 32 | 3);

            id = Guid.Empty; //new EntityId();
            id.InitRaftGroupId(raftGroupId2);
            KeyUtil.WriteEntityKey(keyPtr, id);
            hex = StringHelper.ToHexString(new IntPtr(keyPtr), KeyUtil.ENTITY_KEY_SIZE);
            Console.WriteLine(hex);
        }
Example #3
0
        public void ImplicitTransactionsOnStoreAndTrash()
        {
            using (var conn = SQLitePortability.CreateConnection()) {
                conn.Open();

                IDatabaseDetails details = new SQLiteDetails();
                IDatabaseAccess  db      = new DatabaseAccess(conn, details);
                IKeyAccess       keys    = new KeyUtil();
                DatabaseStorage  storage = new DatabaseStorage(details, db, keys);
                IBeanFactory     factory = new BeanFactory();
                IBeanCrud        crud    = new BeanCrud(storage, db, keys, factory);

                storage.EnterFluidMode();

                var bean = crud.Dispense <ThrowingBean>();
                bean["foo"] = "ok";
                var id = crud.Store(bean);

                bean.Throw  = true;
                bean["foo"] = "fail";

                try { crud.Store(bean); } catch { }
                Assert.Equal("ok", db.Cell <string>(true, "select foo from test where id = {0}", id));

                try { crud.Trash(bean); } catch { }
                Assert.True(db.Cell <int>(true, "select count(*) from test") > 0);
            }
        }
Example #4
0
        public void ImplicitTransactionsOnStoreAndTrash()
        {
            using(var conn = SQLitePortability.CreateConnection()) {
                conn.Open();

                IDatabaseDetails details = new SQLiteDetails();
                IDatabaseAccess db = new DatabaseAccess(conn, details);
                IKeyAccess keys = new KeyUtil();
                DatabaseStorage storage = new DatabaseStorage(details, db, keys);
                IBeanCrud crud = new BeanCrud(storage, db, keys);

                storage.EnterFluidMode();

                var bean = crud.Dispense<ThrowingBean>();
                bean["foo"] = "ok";
                var id = crud.Store(bean);

                bean.Throw = true;
                bean["foo"] = "fail";

                try { crud.Store(bean); } catch { }
                Assert.Equal("ok", db.Cell<string>(true, "select foo from test where id = {0}", id));

                try { crud.Trash(bean); } catch { }
                Assert.True(db.Cell<int>(true, "select count(*) from test") > 0);
            }
        }
Example #5
0
        /// <summary>
        /// Run the KeyInput directly in the Wpf control
        /// </summary>
        private void RunInWpf(KeyInput keyInput)
        {
            Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof(UIPermissionAttribute));
            var presentationSource = _factory.Create <PresentationSource>();

            // Normalize upper case letters here to lower and add the shift key modifier if
            // necessary
            if (Char.IsUpper(keyInput.Char))
            {
                var lowerKeyInput = KeyInputUtil.CharToKeyInput(Char.ToLower(keyInput.Char));
                keyInput = KeyInputUtil.ChangeKeyModifiers(lowerKeyInput, keyInput.KeyModifiers | KeyModifiers.Shift);
            }

            Key key;

            if (!KeyUtil.TryConvertToKeyOnly(keyInput.Key, out key))
            {
                throw new Exception("Couldn't get the WPF key for the given KeyInput");
            }

            // Update the KeyModifiers while this is being processed by our key processor
            try
            {
                _defaultKeyboardDevice.DownKeyModifiers = keyInput.KeyModifiers;

                // First raise the KeyDown event
                var keyDownEventArgs = new KeyEventArgs(
                    _defaultKeyboardDevice,
                    presentationSource.Object,
                    0,
                    key);
                keyDownEventArgs.RoutedEvent = UIElement.KeyDownEvent;
                _defaultInputController.HandleKeyDown(this, keyDownEventArgs);

                // If the event is handled then return
                if (keyDownEventArgs.Handled)
                {
                    return;
                }

                // Now raise the TextInput event
                var textInputEventArgs = new TextCompositionEventArgs(
                    _defaultKeyboardDevice,
                    new TextComposition(InputManager.Current, _wpfTextView.VisualElement, keyInput.Char.ToString()));
                textInputEventArgs.RoutedEvent = UIElement.TextInputEvent;
                _defaultInputController.HandleTextInput(this, textInputEventArgs);

                var keyUpEventArgs = new KeyEventArgs(
                    _defaultKeyboardDevice,
                    presentationSource.Object,
                    0,
                    key);
                keyUpEventArgs.RoutedEvent = UIElement.KeyUpEvent;
                _defaultInputController.HandleKeyUp(this, keyUpEventArgs);
            }
            finally
            {
                _defaultKeyboardDevice.DownKeyModifiers = KeyModifiers.None;
            }
        }
Example #6
0
        // internal static void DestroyMutex(Mutex m, bool bReleaseFirst)
        // {
        //	if(m == null) return;
        //	if(bReleaseFirst)
        //	{
        //		try { m.ReleaseMutex(); }
        //		catch(Exception) { Debug.Assert(false); }
        //	}
        //	try { m.Close(); }
        //	catch(Exception) { Debug.Assert(false); }
        // }

        private static void ActivatePreviousInstance(string[] args)
        {
            if ((m_nAppMessage == 0) && !NativeLib.IsUnix())
            {
                Debug.Assert(false);
                return;
            }

            try
            {
                if (string.IsNullOrEmpty(m_cmdLineArgs.FileName))
                {
                    // NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST,
                    //	m_nAppMessage, (IntPtr)AppMessage.RestoreWindow, IntPtr.Zero);
                    IpcBroadcast.Send(AppMessage.RestoreWindow, 0, false);
                }
                else
                {
                    string[] vFlt = KeyUtil.MakeCtxIndependent(args);

                    IpcParamEx ipcMsg = new IpcParamEx(IpcUtilEx.CmdOpenDatabase,
                                                       CommandLineArgs.SafeSerialize(vFlt), null, null, null, null);

                    IpcUtilEx.SendGlobalMessage(ipcMsg);
                }
            }
            catch (Exception) { Debug.Assert(false); }
        }
Example #7
0
        public virtual Task <FileContent> GetAsync(string id)
        {
            FileContent file = null;

            // try to find the real id
            string real = KeyUtil.FindKey(id, () => _files.Keys);

            if (real != null)
            {
                // try to get the file by using the real id
                bool succeed = _files.TryGetValue(real, out file);

                if (succeed)
                {
                    _logger.LogDebug($"Found a file by using the id {id} -> {real}.");
                }
                else
                {
                    _logger.LogError($"Did not found a file by using the id {id} -> {real}.");
                }
            }
            else
            {
                _logger.LogDebug($"Unable to find a file by using the id {id}.");
            }

            // return the file or null if no data found
            return(Task.FromResult(file));
        }
Example #8
0
        /// <summary>
        /// When a manager wants to import voter data this is called
        /// </summary>
        /// <param name="voterDataPath">
        /// the file path of the data to be imported
        /// </param>
        /// <param name="precinctDataPath">
        /// the file path of the encryption key
        /// </param>
        /// <returns>
        /// whether or not the import was succesful
        /// </returns>
        public bool ImportData(string voterDataPath, string precinctDataPath, bool local = false)
        {
            AsymmetricKey key = new AsymmetricKey(
                KeyUtil.ToKey(new byte[] { 0x30, 0x81, 0x9F, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48,
                                           0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8D, 0x00, 0x30, 0x81,
                                           0x89, 0x02, 0x81, 0x81, 0x00, 0xA4, 0x1A, 0xB3, 0xC6, 0x86, 0x85, 0x5D, 0xF4, 0xBC,
                                           0x59, 0xC0, 0xBE, 0x89, 0xC4, 0x32, 0xA3, 0x9C, 0x21, 0xEC, 0x4D, 0x4D, 0xD3, 0x2C,
                                           0x53, 0x0E, 0xEA, 0xAB, 0xA5, 0x9A, 0x96, 0xCA, 0x1C, 0xB2, 0xE3, 0xBF, 0x70, 0x52,
                                           0x99, 0xE9, 0x39, 0xD8, 0x25, 0x61, 0x9C, 0x10, 0xBA, 0x5A, 0xAB, 0x86, 0x4C, 0xF7,
                                           0xD0, 0x73, 0xCD, 0xEF, 0x59, 0x9A, 0xE8, 0xE7, 0xBC, 0xEA, 0xF1, 0xAF, 0xA0, 0x90,
                                           0x9D, 0x57, 0xF1, 0x0C, 0x3E, 0x82, 0xC2, 0x2C, 0xF0, 0x1A, 0xDA, 0x6D, 0x40, 0xD4,
                                           0x29, 0xBE, 0x42, 0x4B, 0xA6, 0x09, 0x31, 0x28, 0xA1, 0xBD, 0x58, 0x00, 0x69, 0x89,
                                           0xDA, 0xD6, 0x80, 0x72, 0x93, 0xE1, 0x7D, 0x2E, 0xB7, 0xFD, 0xC3, 0x40, 0x0A, 0xAE,
                                           0x52, 0x44, 0xC1, 0x3D, 0x7F, 0x6A, 0x77, 0x59, 0x72, 0xA4, 0xD1, 0x77, 0x93, 0x17,
                                           0x1F, 0xAB, 0x99, 0xB1, 0x26, 0x81, 0xD5, 0x02, 0x03, 0x01, 0x00, 0x01 }));

            _station = _station ?? new Station(this, key, _masterPassword, local);

            try {
                return(_station.ImportData(ImportVoterData(voterDataPath), ImportPrecinctData(precinctDataPath)));
            } catch (Exception e) {
                Console.WriteLine("Data import exception: " + e);
                return(false);
            }
        }
Example #9
0
    private void ResolveAnsweringPhaseKeyInput(string keyCode)
    {
        if (KeyUtil.IsPlayerArrow(keyCode))
        {
            SetupAnsweringPhase(keyCode);
        }
        else if (KeyUtil.IsSpacebar(keyCode))
        {
            if (questions.Count == 1)
            {
                // END OF ROUND
                return;
            }

            SetupNewChoosingPhase(true);
        }
        else if (KeyUtil.IsCtrl(keyCode))
        {
            GlobalHandler.ActivePlayerFailed(activeQuestion);
            GlobalHandler.DeactivatePlayers();

            if (GlobalHandler.AnyAnsweringPlayerLeft())
            {
                SetupWaitingPhase();
            }
            else
            {
                SetupResolutingPhase();
            }
        }
    }
Example #10
0
    //从服务器获取经纬度数据(后期做缓存)
    private IEnumerator getPosFromServer(string address, int total)
    {
        // WWWForm form;
        WWW hostObj;
        //构建数据
        KeyUtil keyObj = new KeyUtil();

        hostObj = new WWW("https://google.cn/maps/api/geocode/json?address=" + address + "&key=" + keyObj.getKey());
        while (!hostObj.isDone)
        {
            yield return(new WaitForEndOfFrame());
        }
        if (hostObj.error != null)
        {
            Debug.LogError(hostObj.error);
        }
        JsonData raw      = JsonMapper.ToObject(hostObj.text);
        JsonData location = JsonMapper.ToObject(raw["results"][0]["geometry"]["location"].ToJson());
        float    lat      = float.Parse(location["lat"].ToString());
        float    lng      = float.Parse(location["lng"].ToString());

        Debug.Log("国家: " + address + " 纬度: " + lat + " 经度: " + lng);
        //开始进行数据渲染
        // earth = this.gameObject;
        GameObject gameObject = new GameObject();

        //gameObject.name = address;
        gameObject.transform.parent = transform;
        ParticleSystem ps   = gameObject.AddComponent <ParticleSystem>();
        var            main = ps.main;

        main.playOnAwake = false;
        renderData(lat, lng, ps, total);
        //posTransform(lat,lng,cube);
    }
Example #11
0
 private void ResolveReadingPhaseKeyInput(string keyCode)
 {
     if (KeyUtil.IsSpacebar(keyCode))
     {
         SetupWaitingPhase();
     }
 }
Example #12
0
 private void ResolveWaitingPhaseKeyInput(string keyCode)
 {
     if (KeyUtil.IsPlayerArrow(keyCode))
     {
         SetupAnsweringPhase(keyCode);
     }
 }
Example #13
0
 public CadPlugin()
 {
     if (KeyUtil.checkRegisted())
     {
         if (TimeUtil.checkOutOfTime())
         {
             canUse = false;
         }
         else
         {
             canUse = true;
         }
     }
     else
     {
         if (!KeyUtil.checkUseTimeOut())
         {
             canUse = true;
             int useTime = KeyUtil.addUseTime();
             logToEditor("未注册版,还可免费体验" + (FREE_USE_TIME - useTime + 1) + "次");
         }
         else
         {
             canUse = false;
         }
     }
 }
Example #14
0
        public bool IsKeyDown(VimKey vimKey)
        {
            Key key;

            return(KeyUtil.TryConvertToKey(vimKey, out key) &&
                   IsKeyDown(key));
        }
Example #15
0
 protected bool checkCanUse()
 {
     if (this.canUse)
     {
         return(true);
     }
     else
     {
         if (KeyUtil.checkRegisted())
         {
             if (TimeUtil.checkOutOfTime())
             {
                 canUse = false;
             }
             else
             {
                 canUse = true;
             }
             return(canUse);
         }
         else
         {
             canUse = false;
         }
         Application.ShowModelessDialog(new RegisterForm());
     }
     logToEditor("请输入注册码");
     return(canUse);
 }
Example #16
0
        private KeyInput ConvertToKeyInput(Key key, ModifierKeys modKeys)
        {
            KeyInput ki;

            Assert.IsTrue(KeyUtil.TryConvertToKeyInput(key, modKeys, out ki));
            return(ki);
        }
Example #17
0
        /// <summary>
        /// Try and convert the Visual Studio command to it's equivalent KeyInput
        /// </summary>
        internal bool TryConvert(Guid commandGroup, uint commandId, IntPtr variantIn, out EditCommand editCommand)
        {
            editCommand = null;

            // Don't ever process a command when we are in an automation function.  Doing so will cause VsVim to
            // intercept items like running Macros and certain wizard functionality
            if (_vsAdapter.InAutomationFunction)
            {
                return(false);
            }

            // Don't intercept commands while incremental search is active.  Don't want to interfere with it
            if (_vsAdapter.IsIncrementalSearchActive(_vimBuffer.TextView))
            {
                return(false);
            }

            var modifiers = KeyUtil.ConvertToKeyModifiers(_vsAdapter.KeyboardDevice.Modifiers);

            if (!OleCommandUtil.TryConvert(commandGroup, commandId, variantIn, modifiers, out editCommand))
            {
                return(false);
            }

            // Don't process Visual Studio commands.  If the key sequence is mapped to a Visual Studio command
            // then that command wins.
            if (editCommand.EditCommandKind == EditCommandKind.VisualStudioCommand)
            {
                return(false);
            }

            return(true);
        }
        private string DecryptConnectionStringPassword(string connectionString)
        {
            // if we're not securing connection strings, just return the original
            if (!secureConnectionStrings)
            {
                return(connectionString);
            }

            SqlConnectionStringBuilder b = new SqlConnectionStringBuilder(connectionString);

            //AM: added this to deal with connection strings using integrated security
            if (String.IsNullOrEmpty(b.Password))
            {
                return(connectionString);
            }

            byte[] cipherText = Convert.FromBase64String(b.Password);
            b.Password = KeyUtil.Decrypt(cipherText);
            return(b.ConnectionString);

            /*     return Regex.Replace(connectionString, @"password=[^;\s]*",
             *       String.Format("password={0}", (string.IsNullOrEmpty(_key)? KeyUtil.ToPlainText(cipherText) :
             *       KeyUtil.ToPlainText(cipherText, _key, _initializationVector))));
             *
             *
             * return connectionString;*/
        }
Example #19
0
        public virtual void HandleDragFinish(object sender, MouseEventArgs e)
        {
            using (Handle.Host.Figure.DirtManager.BeginDirty()) {
                var moveDelta = (Size)e.Location - (Size)_startPoint;
                if (KeyUtil.IsControlPressed())
                {
                    _targets.HideFeedback(_moveRequest);
                    if (_targets.Editors.Any())
                    {
                        var target = _targets.Editors.First().Parent;

                        var cloneRequest = new CloneRequest(_targets.Editors);
                        cloneRequest.MoveDelta = moveDelta;

                        var cmd = target.PerformRequest(cloneRequest) as CloneCommand;
                        if (cmd != null && cmd.ClonedEditors != null)
                        {
                            var select = new SelectMultiCommand(cmd.ClonedEditors, SelectKind.True, true);
                            select.Execute();
                        }
                    }
                }
                else
                {
                    _moveRequest.MoveDelta = moveDelta;
                    _targets.HideFeedback(_moveRequest);
                    _targets.PerformCompositeRequest(_moveRequest, Handle.Host.Site.CommandExecutor);
                }
                Handle.Host.ShowFeedback(new HighlightRequest());
            }
        }
Example #20
0
        public virtual Task <FileContent> RemoveAsync(string id)
        {
            FileContent file = null;

            // try to find the real id
            string real = KeyUtil.FindKey(id, () => _files.Keys);

            if (real != null)
            {
                _logger.LogDebug($"{id} -> {real} will be used when removing the file.");

                // try to remove the file by using the real id
                bool succeed = _files.TryRemove(real, out file);

                if (succeed)
                {
                    _logger.LogDebug($"Successfully removed a file by using the id {id} -> {real}.");
                }
                else
                {
                    _logger.LogError($"Failed to remove a file by using the id {id} -> {real}.");
                }
            }
            else
            {
                _logger.LogDebug($"Unable to find a file to remove by using the id {id}.");
            }

            // return the removed file or null if we didn't remove anything
            return(Task.FromResult(file));
        }
Example #21
0
        private static KeyInput ConvertToKeyInput(string keystroke)
        {
            if (keystroke.Length == 1)
            {
                return(ConvertToKeyInput(keystroke[0]));
            }

            KeyInput vs;

            if (TryConvertVsSpecificKey(keystroke, out vs))
            {
                return(vs);
            }

            try
            {
                var      key = (Key)Enum.Parse(typeof(Key), keystroke, ignoreCase: true);
                KeyInput ki;
                return(KeyUtil.TryConvertToKeyInput(key, out ki) ? ki : null);
            }
            catch (Exception)
            {
            }

            return(null);
        }
Example #22
0
 private static void ActionSyncDataChanged(Moai.Platform.Menus.Action.ActionSyncData data, ToolStripItem mi)
 {
     // Set properties.
     System.Action act = () =>
     {
         if (mi is ToolStripMenuItem && !(mi is ToolStripDropDownButton))
         {
             mi.Text = data.Text;
             (mi as ToolStripMenuItem).ShortcutKeys     = KeyUtil.FromPlatform(data.Shortcut);
             (mi as ToolStripMenuItem).ShowShortcutKeys = false;
         }
         else
         {
             mi.ToolTipText = data.Text;
         }
         mi.Enabled = data.Enabled && data.Implemented;
         if (data.ItemIcon != null)
         {
             mi.Image = data.ItemIcon;
         }
     };
     if (mi.Owner != null && mi.Owner.InvokeRequired)
     {
         mi.Owner.Invoke(act);
     }
     else
     {
         act();
     }
 }
Example #23
0
        // --- mouse ---
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            ClearDragTarget();
            if (e.Button != MouseButtons.Left || e.Clicks >= 2)
            {
                return;
            }

            var tabPage = GetTabPage(e.Location);

            if (tabPage != null)
            {
                if (e.Button == MouseButtons.Left && !KeyUtil.IsShiftPressed() && !KeyUtil.IsControlPressed())
                {
                    var r = GetCloseButtonBounds(tabPage);
                    if (r.Contains(e.Location))
                    {
                        OnCloseButtonPressed(tabPage);
                        _closeButtonState = CloseButtonState.None;
                        Invalidate(r);
                        return;
                    }
                }
            }

            SetupDragTarget(e.X, e.Y);
        }
        private static CompositeKey KeyFromParams(EcasAction a, int iPassword,
                                                  int iKeyFile, int iUserAccount)
        {
            string strPassword  = EcasUtil.GetParamString(a.Parameters, iPassword, true);
            string strKeyFile   = EcasUtil.GetParamString(a.Parameters, iKeyFile, true);
            bool   bUserAccount = StrUtil.StringToBool(EcasUtil.GetParamString(
                                                           a.Parameters, iUserAccount, true));

            CompositeKey cmpKey = null;

            if (!string.IsNullOrEmpty(strPassword) || !string.IsNullOrEmpty(strKeyFile) ||
                bUserAccount)
            {
                List <string> vArgs = new List <string>();
                if (!string.IsNullOrEmpty(strPassword))
                {
                    vArgs.Add("-" + AppDefs.CommandLineOptions.Password + ":" + strPassword);
                }
                if (!string.IsNullOrEmpty(strKeyFile))
                {
                    vArgs.Add("-" + AppDefs.CommandLineOptions.KeyFile + ":" + strKeyFile);
                }
                if (bUserAccount)
                {
                    vArgs.Add("-" + AppDefs.CommandLineOptions.UserAccount);
                }

                CommandLineArgs cmdArgs = new CommandLineArgs(vArgs.ToArray());
                cmpKey = KeyUtil.KeyFromCommandLine(cmdArgs);
            }

            return(cmpKey);
        }
 public static string ToPlainText(byte[] data)
 {
     if (KeyUtil == null)
     {
         throw new CryptographicException("No IEncryptionManager was provided");
     }
     return(KeyUtil.Decrypt(data));
 }
Example #26
0
        private void WellKnownBothWays(VimKey wellKnownKey, Key key)
        {
            var      left = KeyInputUtil.VimKeyToKeyInput(wellKnownKey);
            KeyInput right;

            Assert.IsTrue(KeyUtil.TryConvertToKeyInput(key, out right));
            Assert.AreEqual(left, right);
        }
Example #27
0
        private void KeyToKeyInput(char c, Key key, ModifierKeys mod)
        {
            var      left = KeyInputUtil.CharToKeyInput(c);
            KeyInput right;

            Assert.IsTrue(KeyUtil.TryConvertToKeyInput(key, mod, out right));
            Assert.AreEqual(left, right);
        }
Example #28
0
        public void EncodeTableId()
        {
            byte appStoreId   = 1;
            uint modelTableId = 0xAABBCC;

            uint encodedTableId = KeyUtil.EncodeTableId(appStoreId, modelTableId);

            Assert.True(encodedTableId == 0xCCBBAA01);
        }
Example #29
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (this.pwd.Text == "527014" &&
         this.mNum.Text != null &&
         this.mNum.Text.Length > 0)
     {
         this.regKey.Text = KeyUtil.GetRegisterKey(this.mNum.Text);
     }
 }
Example #30
0
 private void OnBtnOK(object sender, EventArgs e)
 {
     m_pKey = KeyUtil.KeyFromUI(m_cbPassword, null, m_tbPassword,
                                m_cbKeyFile, m_cmbKeyFile, m_cbUserAccount, m_ioInfo, m_bSecureDesktop);
     if (m_pKey == null)
     {
         this.DialogResult = DialogResult.None;
     }
 }
Example #31
0
        public static PointOfSale CreatePos(string posId, string posKeyPath)
        {
            AsymmetricCipherKeyPair keys = null;

            using (var fs = new FileStream(posKeyPath, FileMode.Open)) {
                keys = KeyUtil.LoadCipherKeyPairFromPem(fs);
            }

            return(Client.CreatePos(posId, keys.Private));
        }
Example #32
0
        public static void CheckCompoundKey(DatabaseStorage storage, KeyUtil keys)
        {
            storage.EnterFluidMode();

            keys.RegisterKey("foo", new[] { "k1", "k2" }, null);

            var row = MakeRow(
                "k1", "text",
                "k2", Guid.NewGuid(),
                "v", "hello"
            );

            var id = storage.Store("foo", row) as CompoundKey;
            Assert.Equal(row["k1"], id["k1"]);
            Assert.Equal(row["k2"], id["k2"]);

            row = storage.Load("foo", id);
            Assert.Equal("hello", row["v"]);
        }
        public DatabaseBeanFinderTests()
        {
            _conn = SQLitePortability.CreateConnection();
            _conn.Open();

            IDatabaseDetails details = new SQLiteDetails();
            IDatabaseAccess db = new DatabaseAccess(_conn, details);
            IKeyAccess keys = new KeyUtil();
            IStorage storage = new DatabaseStorage(details, db, keys);
            IBeanCrud crud = new BeanCrud(storage, db, keys);
            IBeanFinder finder = new DatabaseBeanFinder(details, db, crud);

            db.Exec("create table foo(x)");
            db.Exec("insert into foo(x) values(1)");
            db.Exec("insert into foo(x) values(2)");
            db.Exec("insert into foo(x) values(3)");

            _db = db;
            _finder = finder;
        }
Example #34
0
        private void LoadGameDirectory( KeyUtil keyUtil, string gameName )
        {
            using (new WaitCursor(this))
            {
                FileSystem fs = new RealFileSystem();

                string gamePath = keyUtil.FindGameDirectory();
                while (gamePath == null)
                {
                    var fbd = new FolderBrowserDialog
                    {
                        Description =
                            "Could not find the " + gameName + " game directory. Please select the directory containing " + keyUtil.ExecutableName,
                        ShowNewFolderButton = false
                    };

                    if (fbd.ShowDialog() == DialogResult.Cancel)
                    {
                        MessageBox.Show(
                            keyUtil.ExecutableName +
                            " is required to extract cryptographic keys for this program to function. " +
                            "SparkIV can not run without this file.", "Error", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        return;
                    }
                    if (System.IO.File.Exists(Path.Combine(fbd.SelectedPath, keyUtil.ExecutableName)))
                    {
                        gamePath = fbd.SelectedPath;
                    }
                }

                byte[] key = keyUtil.FindKey( gamePath, gameName );

                if (key == null)
                {
                    string message = "Your " + keyUtil.ExecutableName + " seems to be modified or is a newer version than this tool supports. " +
                                    "SparkIV can not run without a supported " + keyUtil.ExecutableName + " file." + "\n" + "Would you like to check for updates?";
                    string caption = "Newer or Modified " + keyUtil.ExecutableName;

                    if (MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                    {
                        Updater.CheckForUpdate();
                    }

                    return;
                }

                KeyStore.SetKeyLoader(() => key);

                fs.Open(gamePath);

                if (_fs != null)
                {
                    _fs.Close();
                }
                _fs = fs;

                Text = Application.ProductName + " - Browse Game Directory";

                PopulateUI();
            }
        }