Esempio n. 1
0
        internal static KeyHelper GetVirtualKey(char datChar)
        {
            var helper = new Helper { Value = User32.VkKeyScan(datChar) };

            var ret = new KeyHelper();
            ret.KeyCode = helper.Low;
            ret.ShiftPressed = (helper.High & 1) != 0;
            ret.CtrlPressed = (helper.High & 2) != 0;
            ret.AltPressed = (helper.High & 4) != 0;

            return ret;
        }
 /// <summary>
 /// Generates the RowKey without setting it on the object.
 /// In this case, just returns a key based on username
 /// </summary>
 /// <returns></returns>
 public virtual string PeekRowKey()
 {
     return(KeyHelper.GenerateRowKeyUserName(UserName));
 }
Esempio n. 3
0
        public void UpdateSettings(Settings config)
        {
            lock (settingsMutex)
            {
                // Load the list of domains
                domains.Clear();

                DkimSignatureAlgorithm signatureAlgorithm;

                switch (config.SigningAlgorithm)
                {
                case DkimAlgorithmKind.RsaSha1:
                    signatureAlgorithm = DkimSignatureAlgorithm.RsaSha1;
                    break;

                case DkimAlgorithmKind.RsaSha256:
                    signatureAlgorithm = DkimSignatureAlgorithm.RsaSha256;
                    break;

                default:
                    // ReSharper disable once NotResolvedInText
                    throw new ArgumentOutOfRangeException("config.SigningAlgorithm");
                }


                foreach (DomainElement domainElement in config.Domains)
                {
                    string privateKey = domainElement.PrivateKeyPathAbsolute(
                        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
                    if (String.IsNullOrEmpty(privateKey) || !File.Exists(privateKey))
                    {
                        Logger.LogError("The private key for domain " + domainElement.Domain + " wasn't found: " + privateKey + ". Ignoring domain.");
                    }

                    //check if the private key can be parsed
                    try
                    {
                        KeyHelper.ParseKeyPair(privateKey);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError("Couldn't load private key for domain " + domainElement.Domain + ": " + ex.Message);
                        continue;
                    }

                    MimeKit.Cryptography.DkimSigner signer;
                    try
                    {
                        AsymmetricKeyParameter key = KeyHelper.ParsePrivateKey(privateKey);
                        signer = new MimeKit.Cryptography.DkimSigner(key, domainElement.Domain,
                                                                     domainElement.Selector)
                        {
                            SignatureAlgorithm = signatureAlgorithm
                        };
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError("Could not initialize MimeKit DkimSigner for domain " + domainElement.Domain + ": " + ex.Message);
                        continue;
                    }
                    domains.Add(domainElement.Domain, new DomainElementSigner(domainElement, signer));
                }

                headerCanonicalization = config.HeaderCanonicalization == DkimCanonicalizationKind.Relaxed ? DkimCanonicalizationAlgorithm.Relaxed : DkimCanonicalizationAlgorithm.Simple;

                bodyCanonicalization = config.BodyCanonicalization == DkimCanonicalizationKind.Relaxed ? DkimCanonicalizationAlgorithm.Relaxed : DkimCanonicalizationAlgorithm.Simple;

                List <HeaderId> headerList = new List <HeaderId>();
                foreach (string headerToSign in config.HeadersToSign)
                {
                    HeaderId headerId;
#if EX_2007_SP3 || EX_2010 || EX_2010_SP1 || EX_2010_SP2 || EX_2010_SP3
                    if (!TryParseHeader(headerToSign, out headerId) || (headerId == HeaderId.Unknown))
#else
                    if (!Enum.TryParse(headerToSign, true, out headerId) || (headerId == HeaderId.Unknown))
#endif
                    {
                        Logger.LogWarning("Invalid value for header to sign: '" + headerToSign + "'. This header will be ignored.");
                    }
                    headerList.Add(headerId);
                }

                // The From header must always be signed according to the DKIM specification.
                if (!headerList.Contains(HeaderId.From))
                {
                    headerList.Add(HeaderId.From);
                }
                eligibleHeaders = headerList.ToArray();
            }
        }
Esempio n. 4
0
 private static void CombatThread()
 {
     try
     {
         Logging.Write("Started combat engine");
         if (ObjectManager.MyPlayer.IsMounted && !ObjectManager.MyPlayer.TravelForm)
         {
             KeyHelper.SendKey("GMount");
         }
         MoveHelper.ReleaseKeys();
         if (DefendAgainst() == null)
         {
             Logging.Write("Pulling: " + Unit.Name + " " + Unit.GUID);
             MoveHelper.MoveToUnit(Unit, 30);
             if (!Unit.TargetHostile())
             {
                 if (ObjectManager.GetAttackers.Count == 0)
                 {
                     PPullBlackList.Blacklist(Unit, 800, true);
                 }
             }
             Unit.Face();
             MoveHelper.ReleaseKeys();
             PullResult result = Pull();
             Logging.Write("Pull result: " + result);
             if (result.Equals(PullResult.CouldNotPull))
             {
                 PPullBlackList.Blacklist(Unit, 800, true);
                 return;
             }
             if (PPullBlackList.IsBlacklisted(Unit))
             {
                 return;
             }
         }
         else
         {
             Logging.Write("Got into combat with: " + Unit.Name);
             Unit.TargetHostile();
             Unit.Face();
         }
         Ticker combatTimeout;
         if (ObjectManager.MyPlayer.Level > 10)
         {
             combatTimeout = new Ticker(20 * 1000);
         }
         else
         {
             combatTimeout = new Ticker(40 * 1000);
         }
         while (!Unit.IsDead)
         {
             _combatLoopThread = new Thread(DoCombat)
             {
                 IsBackground = true
             };
             _combatLoopThread.Name = "DoCombat";
             _combatLoopThread.SetApartmentState(ApartmentState.STA);
             _combatLoopThread.Start();
             while (_combatLoopThread.IsAlive)
             {
                 Thread.Sleep(50);
                 if (!Langs.TrainingDummy(Unit.Name) && combatTimeout.IsReady && Unit.Health > 85)
                 {
                     Logging.Write("Combat took to long, bugged - blacklisting");
                     _combatResult = CombatResult.Bugged;
                     if (!PBlackList.IsBlacklisted(Unit))
                     {
                         PBlackList.Blacklist(Unit, 1200, false);
                     }
                     return;
                 }
             }
         }
     }
     catch
     {
     }
 }
        private (List <DynamicTableEntity> targetUserEntities, List <ITableEntity> targetUserIndexes) ConvertToTargetUserEntities(string userId, List <DynamicTableEntity> sourceUserEntities)
        {
            List <DynamicTableEntity> targetUserEntities = new List <DynamicTableEntity>(100);
            List <ITableEntity>       targetUserIndexes  = new List <ITableEntity>(100);

            foreach (DynamicTableEntity sourceEntity in sourceUserEntities)
            {
                if (sourceEntity.PartitionKey.StartsWith(Constants.RowKeyConstants.PreFixIdentityUserId))
                {
                    string targetUserPartitionKey = KeyHelper.GenerateRowKeyUserId(userId);

                    //User record
                    if (sourceEntity.RowKey.StartsWith(Constants.RowKeyConstants.PreFixIdentityUserId))
                    {
                        //New User
                        //Add UserName Index
                        //Add Email Index
                        DynamicTableEntity tgtDte = new DynamicTableEntity(targetUserPartitionKey, targetUserPartitionKey, Constants.ETagWildcard, sourceEntity.Properties);
                        tgtDte.Properties["Id"]         = new EntityProperty(userId);
                        tgtDte.Properties["KeyVersion"] = new EntityProperty(KeyHelper.KeyVersion);
                        targetUserEntities.Add(tgtDte);

                        //UserName index
                        tgtDte.Properties.TryGetValue("UserName", out EntityProperty userNameProperty);
                        string            userNameKey   = KeyHelper.GenerateRowKeyUserName(userNameProperty.StringValue);
                        IdentityUserIndex userNameIndex = new IdentityUserIndex()
                        {
                            Id           = targetUserPartitionKey,
                            PartitionKey = userNameKey,
                            RowKey       = targetUserPartitionKey,
                            KeyVersion   = KeyHelper.KeyVersion,
                            ETag         = Constants.ETagWildcard
                        };
                        targetUserIndexes.Add(userNameIndex);

                        //Email index - only if email exists
                        if (tgtDte.Properties.TryGetValue("Email", out EntityProperty emailProperty))
                        {
                            string            emailKey   = KeyHelper.GenerateRowKeyUserEmail(emailProperty.StringValue);
                            IdentityUserIndex emailIndex = new IdentityUserIndex()
                            {
                                Id           = targetUserPartitionKey,
                                PartitionKey = emailKey,
                                RowKey       = targetUserPartitionKey,
                                KeyVersion   = KeyHelper.KeyVersion,
                                ETag         = Constants.ETagWildcard
                            };
                            targetUserIndexes.Add(emailIndex);
                        }
                        continue;
                    }
                    //User Claim record
                    if (sourceEntity.RowKey.StartsWith(Constants.RowKeyConstants.PreFixIdentityUserClaim))
                    {
                        //New User Claim
                        //Add Claim Index
                        sourceEntity.Properties.TryGetValue("ClaimType", out EntityProperty claimTypeProperty);
                        string claimType = claimTypeProperty.StringValue;
                        sourceEntity.Properties.TryGetValue("ClaimValue", out EntityProperty claimValueProperty);
                        string claimValue = claimValueProperty.StringValue;

                        string             targetUserRowKey = KeyHelper.GenerateRowKeyIdentityUserClaim(claimType, claimValue);
                        DynamicTableEntity tgtDte           = new DynamicTableEntity(targetUserPartitionKey, targetUserRowKey, Constants.ETagWildcard, sourceEntity.Properties);
                        tgtDte.Properties["UserId"]     = new EntityProperty(userId);
                        tgtDte.Properties["KeyVersion"] = new EntityProperty(KeyHelper.KeyVersion);
                        targetUserEntities.Add(tgtDte);

                        //Claim index
                        IdentityUserIndex claimIndex = new IdentityUserIndex()
                        {
                            Id           = targetUserPartitionKey,
                            PartitionKey = targetUserRowKey,
                            RowKey       = targetUserPartitionKey,
                            KeyVersion   = KeyHelper.KeyVersion,
                            ETag         = Constants.ETagWildcard
                        };
                        targetUserIndexes.Add(claimIndex);
                        continue;
                    }
                    //User Logon record
                    if (sourceEntity.RowKey.StartsWith(Constants.RowKeyConstants.PreFixIdentityUserLogin))
                    {
                        //New User Logon
                        //Add Logon Index
                        sourceEntity.Properties.TryGetValue("LoginProvider", out EntityProperty loginProviderProperty);
                        string loginProvider = loginProviderProperty.StringValue;
                        sourceEntity.Properties.TryGetValue("ProviderKey", out EntityProperty providerKeyProperty);
                        string providerKey = providerKeyProperty.StringValue;

                        string             targetUserRowKey = KeyHelper.GenerateRowKeyIdentityUserLogin(loginProvider, providerKey);
                        DynamicTableEntity tgtDte           = new DynamicTableEntity(targetUserPartitionKey, targetUserRowKey, Constants.ETagWildcard, sourceEntity.Properties);
                        tgtDte.Properties["UserId"]     = new EntityProperty(userId);
                        tgtDte.Properties["KeyVersion"] = new EntityProperty(KeyHelper.KeyVersion);
                        targetUserEntities.Add(tgtDte);

                        //Logon index
                        IdentityUserIndex logonIndex = new IdentityUserIndex()
                        {
                            Id           = targetUserPartitionKey,
                            PartitionKey = KeyHelper.GeneratePartitionKeyIndexByLogin(loginProvider, providerKey),
                            RowKey       = KeyHelper.GenerateRowKeyIdentityUserLogin(loginProvider, providerKey),
                            KeyVersion   = KeyHelper.KeyVersion,
                            ETag         = Constants.ETagWildcard
                        };
                        targetUserIndexes.Add(logonIndex);
                        continue;
                    }
                    //User Role record
                    if (sourceEntity.RowKey.StartsWith(Constants.RowKeyConstants.PreFixIdentityUserRole))
                    {
                        //New User Role
                        //Add Role Index
                        sourceEntity.Properties.TryGetValue("RoleName", out EntityProperty roleNameProperty);
                        string roleName = roleNameProperty.StringValue;

                        string             targetUserRowKey = KeyHelper.GenerateRowKeyIdentityUserRole(roleName);
                        DynamicTableEntity tgtDte           = new DynamicTableEntity(targetUserPartitionKey, targetUserRowKey, Constants.ETagWildcard, sourceEntity.Properties);
                        tgtDte.Properties["UserId"]     = new EntityProperty(userId);
                        tgtDte.Properties["KeyVersion"] = new EntityProperty(KeyHelper.KeyVersion);
                        targetUserEntities.Add(tgtDte);

                        //Role index
                        IdentityUserIndex roleIndex = new IdentityUserIndex()
                        {
                            Id           = targetUserPartitionKey,
                            PartitionKey = targetUserRowKey,
                            RowKey       = targetUserPartitionKey,
                            KeyVersion   = KeyHelper.KeyVersion,
                            ETag         = Constants.ETagWildcard
                        };
                        targetUserIndexes.Add(roleIndex);
                        continue;
                    }
                    //User Token record
                    if (sourceEntity.RowKey.StartsWith(Constants.RowKeyConstants.PreFixIdentityUserToken))
                    {
                        //New User Token
                        sourceEntity.Properties.TryGetValue("LoginProvider", out EntityProperty loginProviderProperty);
                        string loginProvider = loginProviderProperty.StringValue;
                        sourceEntity.Properties.TryGetValue("TokenName", out EntityProperty tokenNameProperty);
                        string tokenName = tokenNameProperty.StringValue;

                        string             targetUserRowKey = KeyHelper.GenerateRowKeyIdentityUserToken(loginProvider, tokenName);
                        DynamicTableEntity tgtDte           = new DynamicTableEntity(targetUserPartitionKey, targetUserRowKey, Constants.ETagWildcard, sourceEntity.Properties);
                        tgtDte.Properties["UserId"]     = new EntityProperty(userId);
                        tgtDte.Properties["KeyVersion"] = new EntityProperty(KeyHelper.KeyVersion);
                        targetUserEntities.Add(tgtDte);
                        continue;
                    }
                }
            }
            return(targetUserEntities, targetUserIndexes);
        }
Esempio n. 6
0
        public void Update(Camera cam, bool stateOnly)
        {
            if (mWindow.Focused == false || stateOnly)
            {
                mLastCursorPos = Cursor.Position;
                mLastUpdate    = DateTime.Now;
                return;
            }

            var keyState = new byte[256];

            UnsafeNativeMethods.GetKeyboardState(keyState);

            var positionChanged = false;
            var updateTerrain   = false;
            var diff            = (float)(DateTime.Now - mLastUpdate).TotalSeconds;

            var camBind = KeyBindings.Instance.Camera;

            if (KeyHelper.AreKeysDown(keyState, camBind.Forward))
            {
                positionChanged = true;
                updateTerrain   = true;
                cam.MoveForward(diff * mSpeedFactor);
            }

            if (KeyHelper.AreKeysDown(keyState, camBind.Backward))
            {
                positionChanged = true;
                updateTerrain   = true;
                cam.MoveForward(-diff * mSpeedFactor);
            }

            if (KeyHelper.AreKeysDown(keyState, camBind.Right))
            {
                positionChanged = true;
                updateTerrain   = true;
                cam.MoveRight(diff * mSpeedFactor);
            }

            if (KeyHelper.AreKeysDown(keyState, camBind.Left))
            {
                positionChanged = true;
                updateTerrain   = true;
                cam.MoveRight(-diff * mSpeedFactor);
            }

            if (KeyHelper.AreKeysDown(keyState, camBind.Up))
            {
                positionChanged = true;
                cam.MoveUp(diff * mSpeedFactor);
            }

            if (KeyHelper.AreKeysDown(keyState, camBind.Down))
            {
                positionChanged = true;
                cam.MoveUp(-diff * mSpeedFactor);
            }

            if (KeyHelper.IsKeyDown(keyState, Keys.RButton) && !KeyHelper.IsKeyDown(keyState, Keys.ControlKey) && !KeyHelper.IsKeyDown(keyState, Keys.Menu) && !KeyHelper.IsKeyDown(keyState, Keys.ShiftKey))
            {
                var curPos = Cursor.Position;
                var dx     = curPos.X - mLastCursorPos.X;
                var dy     = curPos.Y - mLastCursorPos.Y;

                if (dx != 0)
                {
                    cam.Yaw(dx * TurnFactor * (InvertX ? 1 : -1));
                }

                if (dy != 0)
                {
                    cam.Pitch(dy * TurnFactor * (InvertY ? 1 : -1));
                }
            }

            if (positionChanged && PositionChanged != null)
            {
                PositionChanged(cam.Position, updateTerrain);
            }

            mLastUpdate    = DateTime.Now;
            mLastCursorPos = Cursor.Position;
        }
Esempio n. 7
0
 //TODO: Do something to this functions, its freaking ugly
 private static bool LetsSearch(UInt128 guid, bool multiclick, bool click)
 {
     if (!Memory.ReadObject(Memory.BaseAddress + (uint)Pointers.Globals.MouseOverGUID, typeof(ulong)).Equals(guid))
     {
         GamePosition.Findpos(Memory.WindowHandle);
         if (!DoSmallestSearch(guid))
         {
             if (!Search(guid, GamePosition.Width / 16))
             {
                 if (!Search(guid, GamePosition.Width / 12))
                 {
                     if (!Search(guid, GamePosition.Width / 10))
                     {
                         if (!Search(guid, GamePosition.Width / 8))
                         {
                             if (!Search(guid, GamePosition.Width / 6))
                             {
                                 // DoSmallSearch(guid);
                             }
                         }
                     }
                 }
             }
         }
     }
     if (ObjectManager.GetAttackers.Count != 0 && ObjectManager.ShouldDefend)
     {
         return(false);
     }
     if (Memory.ReadObject(Memory.BaseAddress + (uint)Pointers.Globals.MouseOverGUID, typeof(ulong)).Equals(guid))
     {
         if (click)
         {
             if (!LazySettings.HookMouse)
             {
                 SetForGround();
             }
             if (multiclick)
             {
                 MoveMouse(MouseHelper.MousePosition.X, MouseHelper.MousePosition.Y - 15);
                 Thread.Sleep(50);
                 KeyHelper.SendKey("InteractWithMouseOver");
                 Thread.Sleep(50);
                 MoveMouse(MouseHelper.MousePosition.X, MouseHelper.MousePosition.Y + 15);
                 Thread.Sleep(50);
                 KeyHelper.SendKey("InteractWithMouseOver");
                 Thread.Sleep(50);
                 MoveMouse(MouseHelper.MousePosition.X - 15, MouseHelper.MousePosition.Y);
                 Thread.Sleep(50);
                 KeyHelper.SendKey("InteractWithMouseOver");
                 MoveMouse(MouseHelper.MousePosition.X + 15, MouseHelper.MousePosition.Y);
                 Thread.Sleep(50);
                 KeyHelper.SendKey("InteractWithMouseOver");
                 Thread.Sleep(50);
             }
             MoveMouse(MouseHelper.MousePosition.X, MouseHelper.MousePosition.Y);
             Thread.Sleep(50);
             KeyHelper.SendKey("InteractWithMouseOver");
             Thread.Sleep(50);
         }
         return(true);
     }
     return(false);
 }
        public override Packet OnPacketReceive(Packet receivedPacket)
        {
            ClientPacketAskUserActivateAccout clientPacketAskUserActivateAccout = receivedPacket as ClientPacketAskUserActivateAccout;

            ConsoleHelper.Write("Receive - ClientPacketAskUserActivateAccout");

            PLFUser user          = clientPacketAskUserActivateAccout.User;
            String  userPassword  = clientPacketAskUserActivateAccout.UserPassword.ToSQL();
            String  userSecretKey = KeyHelper.CreateRandomKey();

            //insert new profile into DB
            MySqlCommand checkUserIdentityCommand = new MySqlCommand();

            checkUserIdentityCommand.Connection  = Program.mySQLManager.MySQLConnection.MysqlConnection;
            checkUserIdentityCommand.CommandText =
                $"SELECT * FROM `T_User` WHERE userNick='{user.UserNickName}' AND userPassword='******'";

            PLFUser downloadedUser = null;

            MySqlDataReader mysqlDataReader = null;

            ServerPacketConfirmation serverPacketConfirmation;

            try
            {
                mysqlDataReader = checkUserIdentityCommand.ExecuteReader();

                //open reader
                while (mysqlDataReader.Read())
                {
                    downloadedUser = new PLFUser(mysqlDataReader.GetInt32(0), mysqlDataReader.GetString(2), mysqlDataReader.GetString(3), mysqlDataReader.GetString(4), mysqlDataReader.GetString(5));
                }

                if (mysqlDataReader != null && !mysqlDataReader.IsClosed)
                {
                    mysqlDataReader.Close();
                }

                if (downloadedUser != null)
                {
                    //insert new profile into DB
                    MySqlCommand registerNewConfirmKey = new MySqlCommand();
                    registerNewConfirmKey.Connection  = Program.mySQLManager.MySQLConnection.MysqlConnection;
                    registerNewConfirmKey.CommandText =
                        $"DELETE FROM `T_RegisterKey` WHERE `regUserMail`='{downloadedUser.UserEMail}';" +
                        $"INSERT INTO `T_RegisterKey`(`regUserMail`, `regKey`, `regKeyDeliver`) VALUES ('{downloadedUser.UserEMail}','{userSecretKey}','{DateTime.Now.Ticks}');";

                    registerNewConfirmKey.ExecuteNonQuery();
                    new Thread(() =>
                    {
                        Program.mailManager.SendMail(downloadedUser.UserEMail, "PET LA FORME - Confirmation",
                                                     $"Bonjour {downloadedUser.UserName}! Voici votre code d'activation de votre compte: "
                                                     + $"{userSecretKey}. Merci de la rentrer dans votre application pour pouvoir activer votre compte ! Bonne journée !");
                    }
                               ).Start();

                    serverPacketConfirmation = new ServerPacketConfirmation(true, NetworkError.NONE);
                }
                else
                {
                    serverPacketConfirmation = new ServerPacketConfirmation(false, NetworkError.SQL_USER_UNKNOWN);
                }
            }
            catch (MySqlException e)
            {
                Console.WriteLine(e.Number + " - " + e.Message);
                NetworkError networkError;
                switch (e.Number)
                {
                case 1062:
                    networkError = NetworkError.SQL_USER_EXIST;
                    break;

                case 1064:
                    networkError = NetworkError.GLOBAL_UNKNOWN;
                    break;

                default:
                    networkError = NetworkError.GLOBAL_UNKNOWN;
                    break;
                }
                serverPacketConfirmation = new ServerPacketConfirmation(false, networkError);
            }
            catch (Exception e)
            {
                serverPacketConfirmation = new ServerPacketConfirmation(false, NetworkError.GLOBAL_UNKNOWN);
                Console.WriteLine(e.Message);
            }

            ConsoleHelper.Write("Send - ServerPacketConfirmation");

            return(serverPacketConfirmation);
        }
Esempio n. 9
0
 private static uint GenerateRegistrationId()
 {
     return(KeyHelper.GenerateRegistrationId(false));
 }
Esempio n. 10
0
        public void UpdateChanges()
        {
            ModelSpawnManager.Instance.OnUpdate();
            ModelEditManager.Instance.Update();

            var diff = DateTime.Now - mLastChange;

            if (diff.TotalMilliseconds < (IsTexturing ? 40 : 20))
            {
                return;
            }

            mLastChange = DateTime.Now;
            if ((CurrentMode & EditMode.Sculpting) != 0)
            {
                TerrainChangeManager.Instance.OnChange(diff);
            }
            else if ((CurrentMode & EditMode.Texturing) != 0)
            {
                TextureChangeManager.Instance.OnChange(diff);
            }
            else if ((CurrentMode & EditMode.Chunk) != 0)
            {
                ChunkEditManager.Instance.OnChange(diff);
            }

            var keyState = new byte[256];

            UnsafeNativeMethods.GetKeyboardState(keyState);
            var altDown   = KeyHelper.IsKeyDown(keyState, Keys.Menu);
            var LMBDown   = KeyHelper.IsKeyDown(keyState, Keys.LButton);
            var RMBDown   = KeyHelper.IsKeyDown(keyState, Keys.RButton);
            var spaceDown = KeyHelper.IsKeyDown(keyState, Keys.Space);
            var MMBDown   = KeyHelper.IsKeyDown(keyState, Keys.MButton);
            var tDown     = KeyHelper.IsKeyDown(keyState, Keys.T);

            var curPos = Cursor.Position;
            var amount = -(mLastCursorPosition.X - curPos.X) / 32.0f;

            if (mIsTabletOn) // All tablet control editing is here.
            {
                if (mIsTablet_PChange)
                {
                    if (EditorWindowController.Instance.TexturingModel != null)
                    {
                        mAmount = TabletManager.Instance.TabletPressure * mPenSensivity / 10.0f;
                        HandleAmountChanged(mAmount);
                    }

                    if (EditorWindowController.Instance.TerrainManager != null)
                    {
                        mIntensity = TabletManager.Instance.TabletPressure * mPenSensivity / 10.0f;
                        HandleIntensityChanged(mIntensity);
                    }
                }

                if (mIsTablet_RChange) // If outer radius change is enabled.
                {
                    if (EditorWindowController.Instance.TexturingModel != null)
                    {
                        mOuterRadius = Math.Max(TabletManager.Instance.TabletPressure * (mAmplitude / 10.0f), 0.1f);

                        mInnerRadius = Math.Min(mInnerRadius, mAmplitude);

                        mInnerRadius = Math.Min(mInnerRadius, mOuterRadius);


                        HandleOuterRadiusChanged(mOuterRadius);
                        HandleInnerRadiusChanged(mInnerRadius);
                    }
                }

                if (mIsTablet_IRChange) // If inner radius change is enabled.
                {
                    if (EditorWindowController.Instance.TexturingModel != null)
                    {
                        mInnerRadius = Math.Max(TabletManager.Instance.TabletPressure * (mInnerAmplitude / 10.0f), 0.1f);

                        mInnerRadius = Math.Min(mInnerRadius, mOuterRadius);


                        HandleInnerRadiusChanged(mInnerRadius);
                    }
                }
            }


            /*if (!LMBDown && IsTabletOn) // When tablet mode is on we always set those to minimal value (NEEDS TO BE MOVED OUT OF HERE).
             * {
             *  mAmount = 1.0f;
             *  mIntensity = 1.0f;
             * }*/


            if (curPos != mLastCursorPosition)
            {
                if (altDown && RMBDown)
                {
                    mInnerRadius += amount;

                    mInnerRadius = Math.Max(mInnerRadius, 0.1f);
                    mInnerRadius = Math.Min(mInnerRadius, 200.0f);
                    mInnerRadius = Math.Min(mInnerRadius, mOuterRadius);

                    HandleInnerRadiusChanged(mInnerRadius);
                }


                if (altDown && LMBDown)
                {
                    mInnerRadius += amount;
                    mOuterRadius += amount;

                    mInnerRadius = Math.Max(mInnerRadius, 0.1f);
                    mInnerRadius = Math.Min(mInnerRadius, 200.0f);

                    mOuterRadius = Math.Max(mOuterRadius, 0.1f);
                    mOuterRadius = Math.Min(mOuterRadius, 200.0f);

                    mInnerRadius = Math.Min(mInnerRadius, mOuterRadius);

                    HandleInnerRadiusChanged(mInnerRadius);
                    HandleOuterRadiusChanged(mOuterRadius);
                }

                if (spaceDown && LMBDown)
                {
                    mIntensity += amount;
                    mAmount    += amount;

                    if (EditorWindowController.Instance.TerrainManager != null)
                    {
                        mIntensity = Math.Max(mIntensity, 1.0f);
                        mIntensity = Math.Min(mIntensity, 40.0f);

                        HandleIntensityChanged(mIntensity);
                    }

                    if (EditorWindowController.Instance.TexturingModel != null)
                    {
                        mAmount = Math.Max(mAmount, 1.0f);
                        mAmount = Math.Min(mAmount, 40.0f);

                        HandleAmountChanged(mAmount);
                    }
                }

                if (altDown && MMBDown)
                {
                    mOpacity += amount;

                    if (EditorWindowController.Instance.TexturingModel != null)
                    {
                        mOpacity = Math.Max(mOpacity, 0.0f);
                        mOpacity = Math.Min(mOpacity, 255.0f);

                        HandleOpacityChanged(mOpacity);
                    }
                }

                if (spaceDown && MMBDown)
                {
                    mPenSensivity += amount / 32.0f;

                    if (EditorWindowController.Instance.TexturingModel != null)
                    {
                        mPenSensivity = Math.Max(mPenSensivity, 0.1f);
                        mPenSensivity = Math.Min(mPenSensivity, 1.0f);

                        HandlePenSensivityChanged(mPenSensivity);
                    }
                }

                if (spaceDown && tDown) // DOES NOT WORK PROPERLY. NEEDS TO BE MOVED OUT OF THIS METHOD.
                {
                    if (mIsTabletOn)
                    {
                        mIsTabletOn = false;
                    }
                    else
                    {
                        mIsTabletOn = true;
                    }
                    HandleTabletControlChanged(mIsTabletOn);
                }

                mLastCursorPosition = Cursor.Position;
            }
        }
Esempio n. 11
0
 protected override void OnPreviewKeyDown(KeyEventArgs e)
 {
     KeyHelper.ViewPreviewKeyDown(this, e);
     base.OnPreviewKeyDown(e);
 }
Esempio n. 12
0
 public void doAutoRun()
 {
     KeyHelper.SentKeyMof(Keys.None, Keys.Oemtilde);
 }
Esempio n. 13
0
 public void doMap()
 {
     KeyHelper.SentKeyMof(Keys.None, Keys.M);
 }
Esempio n. 14
0
 public void doCmd(int index)
 {
     //if (WowCmd.mthis == null) return;
     Keys[,] keylist = WowCmd.mthis.mkeylist1;
     KeyHelper.SentKeyMof(keylist[index, 0], keylist[index, 1]);
 }
        private static void SetKeysOnDeath(Character __instance, ZNetView ___m_nview)
        {
            if (___m_nview is not null && !___m_nview.IsOwner())
            {
                return;
            }

            string name = __instance.gameObject?.name;

            if (string.IsNullOrWhiteSpace(__instance.gameObject?.name))
            {
                return;
            }

            try
            {
                string cleanedName = name.Split('(')[0].Trim().ToUpperInvariant();
                var    newKey      = $"KILLED_{cleanedName}";

                var existingKeys = _globalVariables.GetValue(ZoneSystem.instance) as HashSet <string> ?? new HashSet <string>(0);

#if DEBUG
                Log.LogDebug($"Found {existingKeys.Count} existing keys.");
#endif

                SetKey(newKey, existingKeys);

                //Check early escape. No reason to start doing more costly operations, if we aren't going to add record any more advanced keys.
                if (ConfigurationManager.GeneralConfig?.RecordPlayerKeys?.Value == false && ConfigurationManager.GeneralConfig?.RecordTribeKeys?.Value == false)
                {
                    return;
                }

                if (ConfigurationManager.GeneralConfig.TrackPlayersWithinDistance.Value > 0)
                {
                    List <ZNet.PlayerInfo> players = ZNet.instance.GetPlayerList();

                    var position = __instance.transform.position;

                    List <ZNet.PlayerInfo> playersInDistance = new List <ZNet.PlayerInfo>(players.Count);

                    foreach (var player in players)
                    {
                        var playerZDO = ZDOMan.instance.GetZDO(player.m_characterID);


                        if (playerZDO is null)
                        {
                            Log.LogWarning("Unable to retrieve ZDO for player: " + player.m_name);
                            continue;
                        }

                        var playerPosition = playerZDO.GetPosition();

#if DEBUG
                        Log.LogDebug($"Player at '{playerPosition}'. Death at '{position}'");
#endif


                        var distance = Vector3.Distance(playerPosition, position);
#if DEBUG
                        Log.LogDebug($"Player {player.m_name} is '{distance}' from killed creature. Must be within {ConfigurationManager.GeneralConfig.TrackPlayersWithinDistance.Value} to be tracked.");
#endif

                        if (distance <= ConfigurationManager.GeneralConfig.TrackPlayersWithinDistance.Value)
                        {
                            playersInDistance.Add(player);
                        }
                    }

                    string defaultKey    = __instance.m_defeatSetGlobalKey;
                    bool   hasDefaultKey = !string.IsNullOrWhiteSpace(defaultKey);

                    foreach (var player in playersInDistance)
                    {
                        string playerName = player.m_name;

                        if (ConfigurationManager.GeneralConfig?.RecordPlayerKeys?.Value == true)
                        {
                            //Set default key with player
                            if (hasDefaultKey)
                            {
                                string defaultPlayerKey = KeyHelper.GetPlayerKey(playerName, defaultKey);

                                SetKey(defaultPlayerKey, existingKeys);
                            }

                            string playerKey = KeyHelper.GetPlayerKey(playerName, newKey);
                            SetKey(playerKey, existingKeys);
                        }

                        if (ConfigurationManager.GeneralConfig.RecordTribeKeys.Value)
                        {
                            if (TribeHelper.TryGetPlayerTribe(playerName, out string tribe))
                            {
                                //Set default key with tribe
                                if (hasDefaultKey)
                                {
                                    string defaultTribeKey = KeyHelper.GetTribeKey(playerName, defaultKey);
                                    SetKey(defaultTribeKey, existingKeys);
                                }

                                string tribeKey = KeyHelper.GetTribeKey(playerName, newKey);
                                SetKey(tribeKey, existingKeys);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.LogError("Error while trying to add enhanced keys.", e);
            }
        }
Esempio n. 16
0
 /// <summary>
 /// Generates the RowKey without setting it on the object.
 /// </summary>
 /// <returns></returns>
 public string PeekRowKey()
 {
     return(KeyHelper.GenerateRowKeyIdentityUserLogin(LoginProvider, ProviderKey));
 }
Esempio n. 17
0
        public override int Run(string[] remainingArguments)
        {
            try
            {
                var dir = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}.system";

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var keys = _uow.PublicKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PublicKey>()
                                               .Where(x => x.IdentityId == null && x.Deletable == false).ToLambda(),
                                               new List <Expression <Func <tbl_PublicKey, object> > >()
                {
                    x => x.PrivateKey,
                });

                ConsoleHelper.StdOutKeyPairs(keys);

                Console.Out.Write("  *** Enter GUID of public key to export *** : ");
                var input = Guid.Parse(StandardInput.GetInput());

                var pubKey = keys.Where(x => x.Id == input).SingleOrDefault();

                if (pubKey != null)
                {
                    //public pkcs8 key format
                    var pubPkcs8File  = new FileInfo(dir + Path.DirectorySeparatorChar + "pub." + SshPublicKeyFormat.Pkcs8.ToString().ToLower() + ".txt");
                    var pubPkcs8Bytes = KeyHelper.ExportPubKey(pubKey, SshPublicKeyFormat.Pkcs8);
                    File.WriteAllBytes(pubPkcs8File.FullName, pubPkcs8Bytes);
                    Console.Out.WriteLine("Created " + pubPkcs8File);

                    //public ssh2base64 key format
                    var pubSsh2Base64File  = new FileInfo(dir + Path.DirectorySeparatorChar + "pub." + SshPublicKeyFormat.Ssh2Base64.ToString().ToLower() + ".txt");
                    var pubSsh2Base64Bytes = KeyHelper.ExportPubKey(pubKey, SshPublicKeyFormat.Ssh2Base64);
                    File.WriteAllBytes(pubSsh2Base64File.FullName, pubSsh2Base64Bytes);
                    Console.Out.WriteLine("Created " + pubSsh2Base64File);

                    //public ssh2raw key format
                    var pubSsh2RawFile  = new FileInfo(dir + Path.DirectorySeparatorChar + "pub." + SshPublicKeyFormat.Ssh2Raw.ToString().ToLower());
                    var pubSsh2RawBytes = KeyHelper.ExportPubKey(pubKey, SshPublicKeyFormat.Ssh2Raw);
                    File.WriteAllBytes(pubSsh2RawFile.FullName, pubSsh2RawBytes);
                    Console.Out.WriteLine("Created " + pubSsh2Base64File);

                    if (pubKey.PrivateKey != null)
                    {
                        var privKey = pubKey.PrivateKey;

                        //private key password in cleartext
                        var privKeyPassFile = new FileInfo(dir + Path.DirectorySeparatorChar + "cleartext_passowrd.txt");
                        File.WriteAllText(privKeyPassFile.FullName, AES.DecryptString(privKey.KeyPass, _conf["Databases:AuroraSecret"]));
                        Console.Out.WriteLine("Created " + privKeyPassFile);

                        //private newopenssh key format
                        var privNewOpenSshFile  = new FileInfo(dir + Path.DirectorySeparatorChar + "priv." + SshPrivateKeyFormat.NewOpenSsh.ToString().ToLower() + ".txt");
                        var privNewOpenSshBytes = KeyHelper.ExportPrivKey(_conf, privKey, SshPrivateKeyFormat.NewOpenSsh, privKey.KeyPass);
                        File.WriteAllBytes(privNewOpenSshFile.FullName, privNewOpenSshBytes);
                        Console.Out.WriteLine("Created " + privNewOpenSshFile);

                        //private openssh key format
                        var privOpenSshFile  = new FileInfo(dir + Path.DirectorySeparatorChar + "priv." + SshPrivateKeyFormat.OpenSsh.ToString().ToLower() + ".txt");
                        var privOpenSshBytes = KeyHelper.ExportPrivKey(_conf, privKey, SshPrivateKeyFormat.OpenSsh, privKey.KeyPass);
                        File.WriteAllBytes(privOpenSshFile.FullName, privOpenSshBytes);
                        Console.Out.WriteLine("Created " + privOpenSshFile);

                        //private pkcs8 key format
                        var privPcks8File  = new FileInfo(dir + Path.DirectorySeparatorChar + "priv." + SshPrivateKeyFormat.Pkcs8.ToString().ToLower() + ".txt");
                        var privPcks8Bytes = KeyHelper.ExportPrivKey(_conf, privKey, SshPrivateKeyFormat.Pkcs8, privKey.KeyPass);
                        File.WriteAllBytes(privPcks8File.FullName, privPcks8Bytes);
                        Console.Out.WriteLine("Created " + privPcks8File);

                        //private putty key format
                        var privPuttyFile  = new FileInfo(dir + Path.DirectorySeparatorChar + "priv." + SshPrivateKeyFormat.Putty.ToString().ToLower() + ".txt");
                        var privPuttyBytes = KeyHelper.ExportPrivKey(_conf, privKey, SshPrivateKeyFormat.Putty, privKey.KeyPass);
                        File.WriteAllBytes(privPuttyFile.FullName, privPuttyBytes);
                        Console.Out.WriteLine("Created " + privPuttyFile);
                    }
                }
                else
                {
                    throw new ConsoleHelpAsException($"  *** Public key with GUID {input} not found ***");
                }

                return(StandardOutput.FondFarewell());
            }
            catch (Exception ex)
            {
                return(StandardOutput.AngryFarewell(ex));
            }
        }
Esempio n. 18
0
        private void AZRUN()
        {
            BarMapper.MapBars();
            KeyHelper.LoadKeys();


            string        BossName = "看门者克里克希尔";
            List <string> EmName   = new List <string>();

            EmName.Add("看守者纳尔伊");
            EmName.Add("看守者加什拉");
            EmName.Add("看守者希尔希克");
            List <int> MyBadBuff = new List <int>();

            MyBadBuff.Add(52087);   // 蛛网裹体
            MyBadBuff.Add(52086);   // 蛛网裹体

            while (ObjectManager.MyPlayer.IsAlive)
            {
                // 循环开始
                PUnit boss = new PUnit(0);
                Dictionary <string, PUnit> em = new Dictionary <string, PUnit>();

                // 加buff
                if (!ObjectManager.MyPlayer.HasBuff("钢皮合剂"))
                {
                    KeyHelper.SendLuaOverChat("/use 钢皮合剂");
                }
                if (!ObjectManager.MyPlayer.HasBuff("坚韧"))
                {
                    KeyHelper.SendLuaOverChat("/use 坚韧符文卷轴 II");
                }

                // 找到怪的地址
                int FoundCount = 0;
                em.Clear();
                foreach (PUnit uu in ObjectManager.GetUnits)
                {
                    if (uu.Name.Equals(BossName))
                    {
                        boss = uu;
                        FoundCount++;
                        continue;
                    }
                    foreach (string ename in EmName)
                    {
                        if (uu.Name.Equals(ename))
                        {
                            em.Add(ename, uu);
                            FoundCount++;
                            continue;
                        }
                    }
                }

                if (FoundCount < 4)
                {
                    Logging.Write("找不到怪了");
                    return;
                }

                // 面对boss
                boss.Face();

                // 开机能
                if (!ObjectManager.MyPlayer.HasBuff("野性印记"))
                {
                    BarMapper.CastSpell("野性印记");
                }
                if (!ObjectManager.MyPlayer.HasBuff("猎豹形态"))
                {
                    BarMapper.CastSpell("猎豹形态");
                }
                Thread.Sleep(1000);

                // 定位一个
                int killcount = 0;
                foreach (string ename in EmName)
                {
                    PUnit emUnit = em[ename];
                    while (!emUnit.TargetGUID.Equals(ObjectManager.MyPlayer.GUID))
                    {
                        KeyHelper.SendLuaOverChat("/target " + ename);
                        BarMapper.CastSpell("精灵之火(野性)");
                        Thread.Sleep(100);
                    }
                    //Thread.Sleep(500);

                    // 猛虎之怒
                    if (BarMapper.IsSpellReadyByName("猛虎之怒"))
                    {
                        BarMapper.CastSpell("猛虎之怒");
                        Thread.Sleep(10);
                    }

                    // 树皮术
                    if (BarMapper.IsSpellReadyByName("树皮术"))
                    {
                        BarMapper.CastSpell("树皮术");
                        Thread.Sleep(10);
                    }


                    // 等待怪过来
                    while (emUnit.Location.DistanceToSelf2D > 5)
                    {
                        if (killcount > 0)
                        {
                            BarMapper.CastSpell("横扫");
                        }
                    }
                    ;
                    emUnit.Location.Face();

                    // 杀,直到怪死
                    int count = 0;
                    Logging.Write("血量:" + emUnit.Health + " 怪物名称:" + emUnit.Name + " 是死是活:" + emUnit.IsAlive);
                    int UHealth = 0;
                    UHealth = emUnit.Health;
                    while (UHealth == -1)
                    {
                        UHealth = emUnit.Health;
                    }
                    while (UHealth > 0)
                    {
                        Thread.Sleep(10);
                        if (!ObjectManager.MyPlayer.IsCasting)
                        {
                            //调整朝向
                            if (!emUnit.Location.IsFacing(0.3f))
                            {
                                emUnit.Location.Face();
                            }

                            //Logging.Write("Count is " + count.ToString());

                            // 检查自己的buff
                            while (ObjectManager.MyPlayer.HasBuff(MyBadBuff))
                            {
                            }
                            ;

                            // 猛虎之怒
                            if (BarMapper.IsSpellReadyByName("猛虎之怒"))
                            {
                                BarMapper.CastSpell("猛虎之怒");
                                Thread.Sleep(10);
                            }

                            // 树皮术
                            if (BarMapper.IsSpellReadyByName("树皮术"))
                            {
                                BarMapper.CastSpell("树皮术");
                                Thread.Sleep(10);
                            }

                            // 凶猛撕咬--终结技
                            //if (count == 4 && BarMapper.IsSpellReadyByName("凶猛撕咬"))
                            if (count > 4)
                            {
                                //BarMapper.CastSpell("凶猛撕咬");
                                KeyLowHelper.PressKey(MicrosoftVirtualKeys.LeftShift);
                                KeyLowHelper.PressKey(MicrosoftVirtualKeys.key1);
                                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key1);
                                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.LeftShift);
                                Thread.Sleep(10);
                                KeyLowHelper.PressKey(MicrosoftVirtualKeys.key3);
                                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key3);
                                //Thread.Sleep(10);
                                count = 0;
                            }

                            //// 裂伤
                            //if (BarMapper.IsSpellReadyByName("裂伤") && !emUnit.HasBuff("裂伤"))
                            //{
                            //    BarMapper.CastSpell("裂伤");
                            //    Thread.Sleep(10);
                            //    count++;
                            //}

                            // 斜掠
                            if (BarMapper.IsSpellReadyByName("裂伤"))
                            {
                                //BarMapper.CastSpell("裂伤");
                                KeyLowHelper.PressKey(MicrosoftVirtualKeys.LeftShift);
                                KeyLowHelper.PressKey(MicrosoftVirtualKeys.key1);
                                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key1);
                                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.LeftShift);
                                Thread.Sleep(10);
                                KeyLowHelper.PressKey(MicrosoftVirtualKeys.key2);
                                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key2);
                                count++;
                                //Thread.Sleep(10);
                            }
                            Logging.Write("血量:" + emUnit.Health);
                        }
                        UHealth = emUnit.Health;
                        while (UHealth == -1)
                        {
                            UHealth = emUnit.Health;
                            if (UHealth == 0)
                            {
                                int HealthTry1 = emUnit.Health;
                                int HealthTry2 = emUnit.Health;
                                UHealth = (HealthTry1 >= HealthTry2 ? HealthTry1 : HealthTry2);
                            }
                        }
                        if (ObjectManager.MyPlayer.IsDead)
                        {
                            return;
                        }
                    }
                    killcount++;
                }

                while (ObjectManager.MyPlayer.HasBuff(MyBadBuff))
                {
                }
                ;

                // 一直横扫,直到全死
                //while (true)
                //{
                //    if (!ObjectManager.MyPlayer.HasBuff(MyBadBuff))
                //    {
                //        if (BarMapper.IsSpellReadyByName("生存本能")) { BarMapper.CastSpell("生存本能"); }
                //        if (ObjectManager.MyPlayer.IsDead) return;
                //        break;
                //    }
                //}
                //while (true)
                //{
                //    if (!ObjectManager.MyPlayer.HasBuff(MyBadBuff))
                //    {
                //        if (BarMapper.IsSpellReadyByName("狂暴")) { BarMapper.CastSpell("狂暴"); }
                //        if (ObjectManager.MyPlayer.IsDead) return;
                //        break;
                //    }
                //}
                KeyLowHelper.PressKey(MicrosoftVirtualKeys.LeftShift);
                KeyLowHelper.PressKey(MicrosoftVirtualKeys.key1);
                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key1);
                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.LeftShift);
                Thread.Sleep(10);
                KeyLowHelper.PressKey(MicrosoftVirtualKeys.key4);
                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key4);
                Thread.Sleep(10);
                KeyLowHelper.PressKey(MicrosoftVirtualKeys.key5);
                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key5);
                //while (BarMapper.IsSpellReadyByName("狂暴")) { BarMapper.CastSpell("狂暴"); break; }
                // 加点血
                while (ObjectManager.MyPlayer.Health < 30)
                {
                    if (!ObjectManager.MyPlayer.HasBuff(MyBadBuff))
                    {
                        if (BarMapper.IsSpellReadyByName("回春术"))
                        {
                            BarMapper.CastSpell("回春术"); break;
                        }
                        if (ObjectManager.MyPlayer.IsDead)
                        {
                            return;
                        }
                    }
                }
                while (ObjectManager.MyPlayer.Health < 30)
                {
                    if (!ObjectManager.MyPlayer.HasBuff(MyBadBuff))
                    {
                        if (BarMapper.IsSpellReadyByName("愈合"))
                        {
                            BarMapper.CastSpell("愈合"); break;
                        }
                        if (ObjectManager.MyPlayer.IsDead)
                        {
                            return;
                        }
                    }
                }
                while (!ObjectManager.MyPlayer.HasBuff("猎豹形态"))
                {
                    if (!ObjectManager.MyPlayer.HasBuff(MyBadBuff))
                    {
                        if (BarMapper.IsSpellReadyByName("猎豹形态"))
                        {
                            BarMapper.CastSpell("猎豹形态"); break;
                        }
                        if (ObjectManager.MyPlayer.IsDead)
                        {
                            return;
                        }
                    }
                }

                boss.Face();

                while (true)
                {
                    //ObjectManager.MyPlayer.IsInCombat
                    Thread.Sleep(100);
                    bool  TargetME = false;
                    PUnit emO      = new PUnit(0);
                    foreach (PUnit uu in ObjectManager.GetUnits)
                    {
                        if (uu.IsPlayer)
                        {
                            continue;
                        }
                        if (uu.Name.Equals(boss.Name))
                        {
                            continue;
                        }
                        if (uu.TargetGUID.Equals(ObjectManager.MyPlayer.GUID))
                        {
                            TargetME = true; emO = uu; break;
                        }
                    }
                    if (!TargetME)
                    {
                        break;
                    }
                    emO.Face();
                    KeyLowHelper.PressKey(MicrosoftVirtualKeys.LeftShift);
                    KeyLowHelper.PressKey(MicrosoftVirtualKeys.key5);
                    KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key5);
                    KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.LeftShift);
                    Thread.Sleep(10);
                    KeyLowHelper.PressKey(MicrosoftVirtualKeys.key2);
                    KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key2);
                    Thread.Sleep(10);
                    KeyLowHelper.PressKey(MicrosoftVirtualKeys.key4);
                    KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key4);
                    Thread.Sleep(10);

                    KeyLowHelper.PressKey(MicrosoftVirtualKeys.LeftShift);
                    KeyLowHelper.PressKey(MicrosoftVirtualKeys.key2);
                    KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key2);
                    KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.LeftShift);
                    Thread.Sleep(10);
                    KeyLowHelper.PressKey(MicrosoftVirtualKeys.key5);
                    KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.key5);
                    Thread.Sleep(10);

                    //BarMapper.CastSpell("猛虎之怒");
                    //BarMapper.CastSpell("树皮术");
                    //BarMapper.CastSpell("横扫");
                    if (ObjectManager.MyPlayer.IsDead)
                    {
                        return;
                    }
                }

                // 面对boss
                boss.Face();

                // 召唤“打架赛车”
                KeyHelper.SendLuaOverChat("/use 蓝色打架赛车");
                BarMapper.CastSpell("蓝色打架赛车");
                Thread.Sleep(1000);
                PUnit djsc      = new PUnit(0);
                bool  FoundDJSC = false;
                while (!FoundDJSC)
                {
                    foreach (PUnit uu in ObjectManager.GetUnits)
                    {
                        if (uu.Name.Contains("打架赛车"))
                        {
                            djsc      = uu;
                            FoundDJSC = true;
                        }
                    }
                    if (ObjectManager.MyPlayer.IsDead)
                    {
                        return;
                    }
                }

                Thread.Sleep(500);
                // 走到boss旁边,打架赛车Y不小于646
                //while (djsc.Location.DistanceFromXY(boss.Location) > 6)
                string ddd  = Convert.ToString(djsc.Location.Y);
                float  PosY = djsc.Location.Y;
                while (PosY > 648 || PosY == 0)
                {
                    KeyLowHelper.PressKey(MicrosoftVirtualKeys.Up);
                    Thread.Sleep(100);
                    PosY = djsc.Location.Y;
                    ddd  = ddd + Convert.ToString(PosY);
                    if (ObjectManager.MyPlayer.IsDead)
                    {
                        return;
                    }
                }
                KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.Up);
                Logging.Write(ddd);

                // 一直跳,直到boss消失
                while (boss.Health > 0)
                {
                    KeyLowHelper.PressKey(MicrosoftVirtualKeys.Space);
                    Thread.Sleep(10);
                    KeyLowHelper.ReleaseKey(MicrosoftVirtualKeys.Space);
                    Thread.Sleep(500);
                    if (ObjectManager.MyPlayer.IsDead)
                    {
                        return;
                    }
                }

                while (ObjectManager.MyPlayer.IsInCombat)
                {
                }
                ;
                // 给自己加血
                KeyHelper.SendLuaOverChat("/use 黄油面包卷");
                Thread.Sleep(1000);
                while (ObjectManager.MyPlayer.HasBuff("进食") || ObjectManager.MyPlayer.Health < 100)
                {
                }
                ;

                while (ObjectManager.MyPlayer.Health < 100 && ObjectManager.MyPlayer.ManaPoints > 5590)
                {
                    // 治疗之触
                    if (BarMapper.IsSpellReadyByName("治疗之触"))
                    {
                        BarMapper.CastSpell("治疗之触");
                        Thread.Sleep(100);
                    }
                    if (ObjectManager.MyPlayer.IsDead)
                    {
                        return;
                    }
                }

                // 等待一段时间,直到boss重新出现
                Thread.Sleep(1000);
                bool FoundBoss = false;
                while (!FoundBoss)
                {
                    foreach (PUnit uu in ObjectManager.GetUnits)
                    {
                        if (uu.Name.Equals(BossName))
                        {
                            FoundBoss = true;
                        }
                    }
                    Thread.Sleep(200);
                    if (ObjectManager.MyPlayer.IsDead)
                    {
                        return;
                    }
                }

                // 猎豹形态
                //BarMapper.CastSpell("猎豹形态");
                //MessageBox.Show("OK");

                // 每个小号跳一次
                Process[] wcc = Process.GetProcessesByName("Wow");
                foreach (Process proc in wcc)
                {
                    KeyLowHelper.PressKey(proc.MainWindowHandle, MicrosoftVirtualKeys.Space);
                    Thread.Sleep(10);
                    KeyLowHelper.ReleaseKey(proc.MainWindowHandle, MicrosoftVirtualKeys.Space);
                    Thread.Sleep(100);
                }

                while (ObjectManager.MyPlayer.Health < 100)
                {
                    while (BarMapper.IsSpellReadyByName("生命之血"))
                    {
                        BarMapper.CastSpell("生命之血"); break;
                    }
                    if (ObjectManager.MyPlayer.ManaPoints > 5590)
                    {
                        // 治疗之触
                        if (BarMapper.IsSpellReadyByName("治疗之触"))
                        {
                            BarMapper.CastSpell("治疗之触");
                            Thread.Sleep(100);
                        }
                    }
                    if (ObjectManager.MyPlayer.IsDead)
                    {
                        return;
                    }
                }
            }
        }
Esempio n. 19
0
        public bool EngineStart()
        {
            FindNode.LoadHarvest();
            FlyingSettings.LoadSettings();
            KeyHelper.AddKey("FMount", "None", FlyingSettings.FlyingMountBar, FlyingSettings.FlyingMountKey);
            KeyHelper.AddKey("Lure", "None", FlyingSettings.LureBar, FlyingSettings.LureKey);
            KeyHelper.AddKey("Waterwalk", "None", FlyingSettings.WaterwalkBar, FlyingSettings.WaterwalkKey);
            KeyHelper.AddKey("CombatStart", "None", FlyingSettings.ExtraBar, FlyingSettings.ExtraKey);
            if (!ObjectManager.InGame)
            {
                Logging.Write(LogType.Info, "Enter game before starting the bot");
                return(false);
            }
            if (ObjectManager.MyPlayer.IsGhost)
            {
                Logging.Write(LogType.Info, "Please ress before starting the bot");
                return(false);
            }
            if (CurrentProfile == null)
            {
                Logging.Write(LogType.Info, "Please load a profile");
                return(false);
            }
            if (CurrentProfile.WaypointsNormal.Count < 2)
            {
                Logging.Write(LogType.Info, "Profile should have more than 2 waypoints");
                return(false);
            }
            Navigation = new FlyingNavigation(CurrentProfile.WaypointsNormal, true, FlyingWaypointsType.Normal);
            Navigator  = new FlyingNavigator();
            ToTown.SetToTown(false);
            switch (CurrentMode)
            {
            case Mode.Normal:
                FlyingStates = new List <MainState>
                {
                    new StateMount(),
                    new StateMoving(),
                    new StateGather(),
                    new StateCombat(),
                    new StateRess(),
                    new StateResting(),
                    new StateMailbox(),
                    new StateToTown(),
                    new StateVendor(),
                    new StateFullBags(),
                };
                break;

            case Mode.TestNormal:
                Logging.Write(LogType.Warning,
                              "Starting flying engine in TestNormal mode, next start will be in normal mode");
                FlyingStates = new List <MainState>
                {
                    new StateMount(),
                    new StateMoving(),
                    new StateFullBags(),
                };
                break;

            case Mode.TestToTown:
                Logging.Write(LogType.Warning,
                              "Starting flying engine in TestToTown mode, next start will be in normal mode");
                FlyingStates = new List <MainState>
                {
                    new StateMount(),
                    new StateMoving(),
                    new StateCombat(),
                    new StateMailbox(),
                    new StateToTown(),
                    new StateVendor(),
                    new StateFullBags(),
                };
                ToTown.SetToTown(true);     //Set town mode to true
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            Stuck.Run();
            FlyingBlackList.Load();
            CloseWindows();
            CurrentMode = Mode.Normal;
            _harvest    = 0;
            _kills      = 0;
            _death      = 0;
            _startTime  = DateTime.Now;
            UpdateStats(0, 0, 0);
            return(true);
        }
        private DynamicTableEntity ConvertToTargetRoleEntity(DynamicTableEntity sourceEntity, IdentityCloudContext sourcesContext)
        {
            DynamicTableEntity targetEntity = null;

            //RoleClaim record
            if (sourceEntity.PartitionKey.StartsWith(Constants.RowKeyConstants.PreFixIdentityRole) &&
                sourceEntity.RowKey.StartsWith(Constants.RowKeyConstants.PreFixIdentityRoleClaim))
            {
                sourceEntity.Properties.TryGetValue("ClaimType", out EntityProperty claimTypeProperty);
                string claimType = claimTypeProperty.StringValue;

                sourceEntity.Properties.TryGetValue("ClaimValue", out EntityProperty claimValueProperty);
                string claimValue = claimValueProperty.StringValue;

                string roleName = GetRoleNameBySourceId(sourceEntity.PartitionKey, sourcesContext);

                targetEntity = new DynamicTableEntity(KeyHelper.GenerateRowKeyIdentityRole(roleName),
                                                      KeyHelper.GenerateRowKeyIdentityRoleClaim(claimType, claimValue), Constants.ETagWildcard, sourceEntity.Properties);
                targetEntity.Properties["KeyVersion"] = new EntityProperty(KeyHelper.KeyVersion);
            }
            else if (sourceEntity.RowKey.StartsWith(Constants.RowKeyConstants.PreFixIdentityRole))
            {
                sourceEntity.Properties.TryGetValue("Name", out EntityProperty roleNameProperty);
                string roleName = roleNameProperty.StringValue;

                targetEntity = new DynamicTableEntity(KeyHelper.GeneratePartitionKeyIdentityRole(roleName), KeyHelper.GenerateRowKeyIdentityRole(roleName), Constants.ETagWildcard, sourceEntity.Properties);
                targetEntity.Properties["KeyVersion"] = new EntityProperty(KeyHelper.KeyVersion);
            }

            return(targetEntity);
        }
Esempio n. 21
0
        private void OnBindingKeyDown(UIComponent comp, UIKeyEventParameter e)
        {
            var key = e.keycode;

            if (_editingBinding == null || KeyHelper.IsModifierKey(key))
            {
                return;
            }

            e.Use();
            UIView.PopModal();

            InputKey newKey;

            switch (key)
            {
            case KeyCode.Backspace:
                newKey = SavedInputKey.Empty;
                break;

            case KeyCode.Escape:
                newKey = _editingBinding.value;
                break;

            default:
                newKey = SavedInputKey.Encode(key, e.control, e.shift, e.alt);
                break;
            }

            if (IsAlreadyBound(_editingBinding, newKey, out var currentAssigned))
            {
                var text = currentAssigned.Count <= 1
          ? (
                    Locale.Exists("KEYMAPPING", currentAssigned[0].name)
              ? Locale.Get("KEYMAPPING", currentAssigned[0].name)
              : Options.GetShortcutName(currentAssigned[0].name)
                    )
          : Locale.Get("KEYMAPPING_MULTIPLE");
                var message = StringUtils.SafeFormat(Locale.Get("CONFIRM_REBINDKEY", "Message"),
                                                     SavedInputKey.ToLocalizedString("KEYNAME", newKey), text);

                ConfirmPanel.ShowModal(Locale.Get("CONFIRM_REBINDKEY", "Title"), message, (c, ret) =>
                {
                    var btn = (UIButton)comp;
                    if (ret == 1)
                    {
                        _editingBinding.value = newKey;
                        foreach (var asigned in currentAssigned)
                        {
                            asigned.value = SavedInputKey.Empty;
                        }
                        UpdateKeyBinding(newKey, btn, false);
                        RefreshKeyMapping();
                    }
                    _editingBinding = null;
                    btn.text        = ((SavedInputKey)btn.objectUserData).ToLocalizedString("KEYNAME");
                });
            }
            else
            {
                UpdateKeyBinding(newKey, (UIButton)comp, false);
            }
        }
Esempio n. 22
0
        internal static void CheckFollow()
        {
            try
            {
                if (Engine.Running && Timer.IsReady)
                {
                    Timer.Reset();
                    foreach (
                        PPlayer player in
                        ObjectManager.GetPlayers.Where(
                            player =>
                            player.GUID != ObjectManager.MyPlayer.GUID && player.Name != ObjectManager.MyPlayer.Name)
                        )
                    {
                        if (player.GUID == ObjectManager.MyPlayer.GUID)
                        {
                            continue;
                        }

                        if (player.Name == ObjectManager.MyPlayer.Name)
                        {
                            continue;
                        }

                        if (player.Location.DistanceToSelf < Distance && !FollowersList.ContainsKey(player.GUID))
                        {
                            Logging.Write("New player around: " + player.Name);
                            FollowersList.Add(player.GUID, Environment.TickCount);
                        }
                        else if (player.Location.DistanceToSelf >= Distance && FollowersList.ContainsKey(player.GUID))
                        {
                            Logging.Write("Removed player: " + player.Name);
                            FollowersList.Remove(player.GUID);
                        }
                        else if (player.Location.DistanceToSelf < Distance && FollowersList.ContainsKey(player.GUID) &&
                                 FollowersList[player.GUID] +
                                 (Convert.ToInt32(LazySettings.LogOutOnFollowTime) * 60 * 1000) < Environment.TickCount)
                        {
                            FollowersList[player.GUID] = Environment.TickCount;

                            Logging.Write(LogType.Warning,
                                          string.Format(player.Name + " has been following me for {0} minutes !",
                                                        LazySettings.LogOutOnFollowTime));
                            if (LazySettings.SoundFollow)
                            {
                                PlayerSound();
                            }
                            if (LazySettings.LogoutOnFollow)
                            {
                                LazyForms.MainForm.StopBotting(true);
                                Thread.Sleep(3000);
                                KeyHelper.ChatboxSendText("/logout");
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
 /// <summary>
 /// Generates the RowKey without setting it on the object.
 /// </summary>
 /// <returns></returns>
 public string PeekRowKey()
 {
     return(KeyHelper.GenerateRowKeyIdentityUserRole(RoleName));
 }
Esempio n. 24
0
        /// <summary>
        /// Loads the track details from the tags in the associate mp3
        /// </summary>
        /// <param name="track">The track to load the details of.</param>
        /// <param name="updateLength">if set to <c>true</c> [update length].</param>
        public static void LoadTrack(Track track, bool updateLength = true)
        {
            if (!File.Exists(track.Filename))
            {
                return;
            }
            if (!track.Filename.ToLower().EndsWith(".mp3"))
            {
                return;
            }

            DebugHelper.WriteLine("Library - LoadTrack - " + track.Description);

            GuessTrackDetailsFromFileName(track);

            var dateLastModified = GetTrackLastModified(track.Filename);

            track.LastModified = dateLastModified;

            if (ID3v2Tag.DoesTagExist(track.Filename))
            {
                var tags = new ID3v2Tag(track.Filename);

                if (!string.IsNullOrEmpty(tags.Artist))
                {
                    track.Artist = tags.Artist.Trim();
                }
                if (!string.IsNullOrEmpty(tags.Artist))
                {
                    track.AlbumArtist = tags.Artist.Trim();
                }
                if (!string.IsNullOrEmpty(tags.Title))
                {
                    track.Title = tags.Title.Trim();
                }
                if (!string.IsNullOrEmpty(tags.Album))
                {
                    track.Album = tags.Album.Trim();
                }
                if (!string.IsNullOrEmpty(tags.Genre))
                {
                    track.Genre = tags.Genre.Trim();
                }
                if (!string.IsNullOrEmpty(tags.InitialKey))
                {
                    var tagKey = tags.InitialKey.Trim();
                    track.Key = KeyHelper.ParseKey(tagKey);
                }

                LoadArtistAndAlbumArtist(track);

                if (tags.LengthMilliseconds.HasValue)
                {
                    track.Length = (decimal)tags.LengthMilliseconds / 1000M;
                }

                decimal bpm;
                if (decimal.TryParse(tags.BPM, out bpm))
                {
                    track.Bpm = bpm;
                }

                track.Bpm      = BpmHelper.NormaliseBpm(track.Bpm);
                track.EndBpm   = track.Bpm;
                track.StartBpm = track.Bpm;
                track.Bpm      = BpmHelper.GetAdjustedBpmAverage(track.StartBpm, track.EndBpm);

                int trackNumber;
                var trackNumberTag = (tags.TrackNumber + "/").Split('/')[0].Trim();
                if (int.TryParse(trackNumberTag, out trackNumber))
                {
                    track.TrackNumber = trackNumber;
                }

                if (GenreCode.IsGenreCode(track.Genre))
                {
                    track.Genre = GenreCode.GetGenre(track.Genre);
                }
                if (track.Artist == "")
                {
                    track.Artist = NoValue;
                }
                if (track.AlbumArtist == "")
                {
                    track.AlbumArtist = NoValue;
                }
                if (track.Title == "")
                {
                    track.Title = NoValue;
                }
                if (track.Album == "")
                {
                    track.Album = NoValue;
                }
                if (track.Genre == "")
                {
                    track.Genre = NoValue;
                }
            }

            track.OriginalDescription = track.Description;
            track.FullLength          = track.Length;


            var audioFile = AudioFile.Create(track.Filename, true);

            track.Bitrate = audioFile.Bitrate;
            track.Length  = audioFile.TotalSeconds;

            if (updateLength)
            {
                UpdateLength(track);
            }

            //UpdateKey(track);

            track.Bpm = BpmHelper.GetAdjustedBpmAverage(track.StartBpm, track.EndBpm);

            track.OriginalDescription = track.Description;

            if (track.EndBpm == 0 || track.EndBpm == 100)
            {
                track.EndBpm = track.Bpm;
            }
            if (track.StartBpm == 0 || track.StartBpm == 100)
            {
                track.StartBpm = track.Bpm;
            }
        }
Esempio n. 25
0
        private void TestKeyHelper_VirtualCodeToLocaleDisplayText()
        {
            var keyCombination = string.Join(" + ", new[] { VirtualKeyCode.LeftShift, VirtualKeyCode.KeyA }.Select(vk => KeyHelper.VirtualCodeToLocaleDisplayText(vk, false)));

            Assert.NotEmpty(keyCombination);
            Assert.Contains("+ A", keyCombination);
        }
 /// <summary>
 /// Generates the RowKey without setting it on the object.
 /// </summary>
 /// <returns></returns>
 public string PeekRowKey()
 {
     return(KeyHelper.GenerateRowKeyIdentityUserClaim(ClaimType, ClaimValue));
 }
Esempio n. 27
0
        public override async Task <OperationResult <VoidResponse> > ValidatePrivateKey(ValidatePrivateKeyModel model, CancellationToken ct)
        {
            var keys = ToKey(model.PrivateKey);

            if (keys == null)
            {
                switch (model.KeyRoleType)
                {
                case KeyRoleType.Active:
                    return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.WrongPrivateActimeKey)));

                case KeyRoleType.Posting:
                    return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.WrongPrivatePostingKey)));
                }
            }

            var isConnected = await TryReconnectChain(ct);

            if (!isConnected)
            {
                return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.EnableConnectToBlockchain)));
            }

            var result = new OperationResult <VoidResponse>();


            var args = new FindAccountsArgs
            {
                Accounts = new[] { model.Login }
            };
            var resp = await _operationManager.FindAccounts(args, CancellationToken.None);

            if (resp.IsError)
            {
                result.Exception = new RequestException(resp);
                return(result);
            }

            if (resp.Result.Accounts.Length != 1 || resp.Result.Accounts[0] == null)
            {
                return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.UnexpectedProfileData)));
            }

            Authority authority;

            switch (model.KeyRoleType)
            {
            case KeyRoleType.Active:
                authority = resp.Result.Accounts[0].Active;
                break;

            case KeyRoleType.Posting:
                authority = resp.Result.Accounts[0].Posting;
                break;

            default:
                throw new NotImplementedException();
            }

            var isSame = KeyHelper.ValidatePrivateKey(keys, authority.KeyAuths.Select(i => i.Key.Data).ToArray());

            if (isSame)
            {
                return(new OperationResult <VoidResponse>(new VoidResponse()));
            }

            switch (model.KeyRoleType)
            {
            case KeyRoleType.Active:
                return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.WrongPrivateActimeKey)));

            default:
                return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.WrongPrivatePostingKey)));
            }
        }
Esempio n. 28
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {
                try
                {
                    AsymmetricKeyAlgorithm.Register(Curve25519.Create);
                    AsymmetricKeyAlgorithm.Register(Ed25519.Create);
                    AsymmetricKeyAlgorithm.Register(EllipticCurveAlgorithm.Create);

                    using (var scope = _factory.CreateScope())
                    {
                        var conf = scope.ServiceProvider.GetRequiredService <IConfiguration>();
                        var uow  = scope.ServiceProvider.GetRequiredService <IUnitOfWork>();

                        if (!Enum.TryParse <LogLevel>(conf["Rebex:LogLevel"], true, out _level))
                        {
                            throw new InvalidCastException();
                        }

                        var license = uow.Settings.Get(QueryExpressionFactory.GetQueryExpression <tbl_Setting>()
                                                       .Where(x => x.ConfigKey == "RebexLicense").ToLambda()).OrderBy(x => x.Created)
                                      .Last();

                        Rebex.Licensing.Key = license.ConfigValue;

                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.DSS, 1024, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.RSA, 4096, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.ECDsaNistP256, 256, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.ECDsaNistP384, 384, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.ECDsaNistP521, 521, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);
                        KeyHelper.CheckPrivKey(conf, uow, SshHostKeyAlgorithm.ED25519, 256, AlphaNumeric.CreateString(32), SignatureHashAlgorithm.SHA256);

                        var secret = conf["Databases:AuroraSecret"];

                        var dsaStr     = SshHostKeyAlgorithm.DSS.ToString();
                        var dsaPrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                             .Where(x => x.KeyAlgo == dsaStr && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                         .Single();

                        var dsaBytes = Encoding.ASCII.GetBytes(dsaPrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(dsaBytes, AES.DecryptString(dsaPrivKey.KeyPass, secret)));

                        var rsaStr     = SshHostKeyAlgorithm.RSA.ToString();
                        var rsaPrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                             .Where(x => x.KeyAlgo == rsaStr && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                         .Single();

                        var rsaBytes = Encoding.ASCII.GetBytes(rsaPrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(rsaBytes, AES.DecryptString(rsaPrivKey.KeyPass, secret)));

                        var ecdsa256Str     = SshHostKeyAlgorithm.ECDsaNistP256.ToString();
                        var ecdsa256PrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                                  .Where(x => x.KeyAlgo == ecdsa256Str && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                              .Single();

                        var ecdsa256Bytes = Encoding.ASCII.GetBytes(ecdsa256PrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(ecdsa256Bytes, AES.DecryptString(ecdsa256PrivKey.KeyPass, secret)));

                        var ecdsa384Str     = SshHostKeyAlgorithm.ECDsaNistP384.ToString();
                        var ecdsa384PrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                                  .Where(x => x.KeyAlgo == ecdsa384Str && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                              .Single();

                        var ecdsa384Bytes = Encoding.ASCII.GetBytes(ecdsa384PrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(ecdsa384Bytes, AES.DecryptString(ecdsa384PrivKey.KeyPass, secret)));

                        var ecdsa521Str     = SshHostKeyAlgorithm.ECDsaNistP521.ToString();
                        var ecdsa521PrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                                  .Where(x => x.KeyAlgo == ecdsa521Str && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                              .Single();

                        var ecdsa521Bytes = Encoding.ASCII.GetBytes(ecdsa521PrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(ecdsa521Bytes, AES.DecryptString(ecdsa521PrivKey.KeyPass, secret)));

                        var ed25519Str     = SshHostKeyAlgorithm.ED25519.ToString();
                        var ed25519PrivKey = uow.PrivateKeys.Get(QueryExpressionFactory.GetQueryExpression <tbl_PrivateKey>()
                                                                 .Where(x => x.KeyAlgo == ed25519Str && x.IdentityId == null).ToLambda()).OrderBy(x => x.Created)
                                             .Single();

                        var ed25519Bytes = Encoding.ASCII.GetBytes(ed25519PrivKey.KeyValue);
                        _server.Keys.Add(new SshPrivateKey(ed25519Bytes, AES.DecryptString(ed25519PrivKey.KeyPass, secret)));

                        _binding = conf.GetSection("Daemons:SftpService:Bindings").GetChildren().Select(x => x.Value);
                    }

                    foreach (var binding in _binding)
                    {
                        var pair = binding.Split("|");

                        _server.Bind(new IPEndPoint(IPAddress.Parse(pair[0]), int.Parse(pair[1])), FileServerProtocol.Sftp);
#if DEBUG
                        _server.Bind(new IPEndPoint(IPAddress.Parse(pair[0]), int.Parse(pair[1])), FileServerProtocol.Shell);
#endif
                    }

                    _server.LogWriter = new ConsoleLogWriter(_level);
                    _server.Settings.AllowedAuthenticationMethods        = AuthenticationMethods.PublicKey | AuthenticationMethods.Password;
                    _server.Settings.SshParameters.EncryptionAlgorithms  = SshEncryptionAlgorithm.Any;
                    _server.Settings.SshParameters.EncryptionModes       = SshEncryptionMode.Any;
                    _server.Settings.SshParameters.KeyExchangeAlgorithms = SshKeyExchangeAlgorithm.Any;
                    _server.Settings.SshParameters.HostKeyAlgorithms     = SshHostKeyAlgorithm.Any;
                    _server.Settings.SshParameters.MacAlgorithms         = SshMacAlgorithm.Any;
                    _server.Authentication    += FsUser_Authentication;
                    _server.Connecting        += FsUser_Connecting;
                    _server.Disconnected      += FsUser_Disconnected;
                    _server.FileDownloaded    += FsUser_FileDownloaded;
                    _server.FileUploaded      += FsUser_FileUploaded;
                    _server.PreAuthentication += FsUser_PreAuthentication;
                    _server.Start();
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                }
            }, cancellationToken);
        }
Esempio n. 29
0
 /// <summary>
 /// Generates the RowKey without setting it on the object.
 /// In this case, just returns a key based on username
 /// </summary>
 /// <returns></returns>
 public string PeekRowKey()
 {
     return(KeyHelper.GenerateRowKeyUserId(Id));
 }
Esempio n. 30
0
 /// <summary>
 /// Generates the RowKey without setting it on the object.
 /// </summary>
 /// <returns></returns>
 public string PeekRowKey()
 {
     return(KeyHelper.GenerateRowKeyIdentityUserToken(LoginProvider, Name));
 }
Esempio n. 31
0
 bool _ismacrostart = true; // right double click to start/stop;
 public void pushMacrobtn()
 {
     _ismacrostart = !_ismacrostart;
     //if (!_ismacrostart)
     KeyHelper.SentKeyMof(Keys.None, Keys.Space);
 }