public void Logout()
        {
            Settings.Current.UserName     = string.Empty;
            Settings.Current.SocialUserID = string.Empty;

            System.Collections.Generic.IEnumerable <Account> accounts = AccountStore.Create().FindAccountsForService("Facebook");
            if (accounts != null)
            {
                if (accounts.FirstOrDefault() != null)
                {
                    AccountStore.Create().Delete(accounts.FirstOrDefault(), "Facebook");
                }
            }
            m_NavigationService.NavigateAsync("/LoginPage");
        }
示例#2
0
        public (bool verified, UserViewModel user) Login(string Email, string Password)
        {
            UserViewModel userModel = new UserViewModel();

            Data.Repositories.IRepository <User>         userRepository = _unitOfWork.GetRepository <User>();
            Data.Repositories.IRepository <UserPassword> passRepository = _unitOfWork.GetRepository <UserPassword>();

            System.Collections.Generic.IEnumerable <User> user = userRepository.Find(x => x.Email == Email);
            if (!user.Any())
            {
                return(false, userModel);
            }

            userModel = _mapper.Map <User, UserViewModel>(user.FirstOrDefault());
            System.Collections.Generic.IEnumerable <UserPassword> password = passRepository.Find(x => x.UserId == user.FirstOrDefault().Id);
            if (!password.Any())
            {
                return(false, userModel);
            }

            (bool Verified, bool NeedsUpgrade)validation = _passwordHasher.Check(password.FirstOrDefault().Password, Password);
            if (!validation.Verified)
            {
                return(false, userModel);
            }

            return(true, userModel);
        }
示例#3
0
        public string DecryptFirstCreditCardNo()
        {
            var result = string.Empty;

            try {
                EnsureEncryptedCreditCardNoColExists();

                _adventureWorksContext = new AdventureWorks2017Entities();
                System.Collections.Generic.IEnumerable <CreditCard> res = _adventureWorksContext.Database.SqlQuery <CreditCard>("SELECT TOP 1 * FROM Sales.CreditCard WHERE CardNumberEncrypted IS NOT NULL");

                var cardNo      = res.FirstOrDefault().CardNumber;
                var dmlOpenCert = "OPEN SYMMETRIC KEY CreditCardNoKey DECRYPTION BY CERTIFICATE CreditCardNoCert;";
                var dmlDecrypt  = "SELECT CONVERT(nvarchar, DecryptByKey(CardNumberEncrypted, 1, HashBytes('SHA1', " +
                                  "CONVERT(varbinary, CreditCardID)))) AS 'CardNumberDec' FROM Sales.CreditCard WHERE CardNumber = '" + cardNo + "';";
                var dmlCloseCert = "CLOSE SYMMETRIC KEY CreditCardNoKey;";

                // Carsten Thomsen 07/06/2018: Surprisingly this works, with the combination of DML and a query. I got lucky as I was running out of luck
                //                             with EF closing the connection after each query or DML, meaning the Cert would be closed too, effectively
                //                             preventing encryption and decryption.
                result = _adventureWorksContext.Database.SqlQuery <string>(dmlOpenCert + dmlDecrypt + dmlCloseCert).FirstOrDefault();
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
            finally {
                _adventureWorksContext.Dispose();
            }

            return(result);
        }
示例#4
0
        /// <summary>
        /// NamespaceName = "DataModels"; DataContextName = "Model"; BaseDataContextClass = "LinqToDB.Entitys"; PluralizeDataContextPropertyNames = false;
        /// </summary>
        /// <param name="connectionStringSettings"></param>
        /// <param name="defaultConfiguration"></param>
        public LinqToDBSection(System.Collections.Generic.IEnumerable <ConnectionStringSettings> connectionStringSettings, string defaultConfiguration = null)
        {
            this.connectionStringSettings = connectionStringSettings;
            var first = connectionStringSettings?.FirstOrDefault();

            DefaultConfiguration = defaultConfiguration ?? first?.Name;
            DefaultDataProvider  = first?.ProviderName;
        }
        public BasePlayerItem TryGetItem(ItemTemplate template, System.Collections.Generic.IEnumerable <EffectBase> effects, CharacterInventoryPositionEnum position, BasePlayerItem except)
        {
            System.Collections.Generic.IEnumerable <BasePlayerItem> source =
                from entry in base.Items.Values
                where entry != except && entry.Template.Id == template.Id && entry.Position == position && effects.CompareEnumerable(entry.Effects)
                select entry;

            return(source.FirstOrDefault <BasePlayerItem>());
        }
示例#6
0
        protected override ModelMetadata CreateMetadata(System.Collections.Generic.IEnumerable <Attribute> attributes, Type containerType, Func <object> modelAccessor, Type modelType, string propertyName)
        {
            var metadata           = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            var formInputAttribute = (FormInputAttribute)attributes.FirstOrDefault(x => x is FormInputAttribute);

            if (formInputAttribute != null)
            {
                metadata.TemplateHint = formInputAttribute.TemplateHint;
            }
            return(metadata);
        }
示例#7
0
        /// <summary>
        /// Toucheses the began.
        /// </summary>
        /// <returns><c>true</c>, if began was touchesed, <c>false</c> otherwise.</returns>
        /// <param name="points">Points.</param>
        public override bool TouchesBegan(System.Collections.Generic.IEnumerable <NGraphics.Point> points)
        {
            base.TouchesBegan(points);

            var point = points.FirstOrDefault();

            _rippler.RippleAsync(point.X, point.Y, true);
            _labelText.TextColor = Color.Accent;

            return(true);
        }
示例#8
0
 internal void ReviseParValue(System.Collections.Generic.IEnumerable <Flight> flights)
 {
     foreach (var detail in this.Details)
     {
         var flight = flights.FirstOrDefault(item => item.Id == detail.Flight.Id);
         if (flight != null)
         {
             detail.Flight.Fare = flight.Fare;
         }
     }
     RefreshFare();
 }
示例#9
0
        public StartScreen(System.Collections.Generic.IEnumerable <Robot> enumerable)
        {
            this.redPlayer    = enumerable.FirstOrDefault(x => x.PlayerColor == PlayerColor.RoterRoboter);
            this.bluePlayer   = enumerable.FirstOrDefault(x => x.PlayerColor == PlayerColor.BlauerRoboter);
            this.yellowPlayer = enumerable.FirstOrDefault(x => x.PlayerColor == PlayerColor.GelberRoboter);
            this.greenPlayer  = enumerable.FirstOrDefault(x => x.PlayerColor == PlayerColor.GruenerRoboter);

            this.background = new Sprite("StartScreen/HintergrundMitSchatten")
            {
                Origin = new Vector2(1258 + 600 / 2, 285 + 754 / 2),
            };
            this.green = new Sprite("StartScreen/GruenerRoboterWolke")
            {
                Origin = new Vector2(429, 932),
            };
            this.yellow = new Sprite("StartScreen/GelberRoboterWolke")
            {
                Origin = new Vector2(1174, 719),
            };
            this.red = new Sprite("StartScreen/RoterRoboterWolke")
            {
                Origin = new Vector2(867, 841),
            };
            this.blue = new Sprite("StartScreen/BlauerRoboterWolke")
            {
                Origin = new Vector2(1470, 952),
            };

            this.Add(this.background);
            this.Add(this.yellow);
            this.Add(this.red);
            this.Add(this.green);
            this.Add(this.blue);

            foreach (var item in this.OfType <Sprite>())
            {
                item.Position = item.Origin;
            }
        }
示例#10
0
        /// <summary>
        /// Toucheses the began.
        /// </summary>
        /// <returns><c>true</c>, if began was touchesed, <c>false</c> otherwise.</returns>
        /// <param name="points">Points.</param>
        public override bool TouchesBegan(System.Collections.Generic.IEnumerable <NGraphics.Point> points)
        {
            base.TouchesBegan(points);

            var point = points.FirstOrDefault();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            _rippler.RippleAsync(point.X, point.Y, true);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            _labelText.TextColor = Color.Accent;

            return(true);
        }
        /// <summary>
        /// Authorizes the payment amount.
        /// </summary>
        /// <returns>A task.</returns>
        public async Task ExecuteAsync()
        {
            // retrieve the subscription
            System.Collections.Generic.IEnumerable <CustomerSubscriptionEntity> customerSubscriptions = await repository.RetrieveAsync(desiredSubscriptionUpdates.CustomerId).ConfigureAwait(false);

            originalSubscriptionState = customerSubscriptions.FirstOrDefault(subscription => subscription.SubscriptionId == desiredSubscriptionUpdates.SubscriptionId);

            if (originalSubscriptionState == null)
            {
                throw new PartnerDomainException(ErrorCode.SubscriptionNotFound);
            }

            // update the subscription
            Result = await repository.UpdateAsync(desiredSubscriptionUpdates).ConfigureAwait(false);
        }
        public static void MapNavigationValueToObject <T>(this NavigationParameters navigationParameter, T data)
            where T : class
        {
            if (data == null)
            {
                return;
            }

            System.Collections.Generic.IEnumerable <PropertyInfo> properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                                                               .Where(p => p.CanRead && p.CanWrite);

            foreach (System.Collections.Generic.KeyValuePair <string, object> np in navigationParameter)
            {
                properties.FirstOrDefault(p => p.Name == np.Key)?.SetValue(data, np.Value);
            }
        }
示例#13
0
        public async Task <IActionResult> OnPostAsync()
        {
            System.Collections.Generic.IEnumerable <User> dbUsers = await userRepository.GetUsers();

            if (dbUsers.Any(x => x.Username.ToLower() == SUser.Username.ToLower().Trim() && x.Id != SUser.Id))
            {
                HasError          = true;
                ViewData["Error"] = "Υπάρχει ήδη χρήστης με Όνομα Χρήστη (Username) που δώσατε.";
                return(Page());
            }

            if (dbUsers.Any(x => x.Email.ToLower() == SUser.Email.ToLower().Trim() && x.Id != SUser.Id))
            {
                HasError          = true;
                ViewData["Error"] = "Υπάρχει ήδη χρήστης με την Ηλεκτρονική Διεύθυνση που δώσατε.";
                return(Page());
            }

            if (string.IsNullOrEmpty(SUser.Password))
            {
                SUser.Password = dbUsers.FirstOrDefault(x => x.Id == SUser.Id).Password;
            }
            else
            {
                SUser.Password = CrypterAlgorithm.ComputeSha256Hash(SUser.Password);
            }

            User dbUser = await userRepository.GetUser(SUser.Id);

            dbUser.Username   = SUser.Username;
            dbUser.Password   = SUser.Password;
            dbUser.Email      = SUser.Email;
            dbUser.FamilyName = SUser.FamilyName;
            dbUser.IsAdmin    = SUser.IsAdmin;

            if (await userRepository.UpdateUser(dbUser))
            {
                HasError = false;
                TempData["SuccessMessage"] = "Ο Χρήστης προστέθηκε με επιτυχία.";
                return(RedirectToPage(Url.Content("~/Admin/UserList")));
            }

            HasError          = true;
            ViewData["Error"] = "Δεν μπορέσαμε να κάνουμε την εγγραφή προσπαθήστε ξανά";
            return(Page());
        }
示例#14
0
        public async Task <AuthenticationResult> GetAccessTokenAsync(ClaimsPrincipal principal, string[] scopes)
        {
            IConfidentialClientApplication app = BuildApp(principal);
            IAccount account = await app.GetAccountAsync(principal.GetMsalAccountId());

            // guest??
            if (null == account)
            {
                System.Collections.Generic.IEnumerable <IAccount> accounts = await app.GetAccountsAsync();

                account = accounts.FirstOrDefault(a => a.Username == principal.GetLoginHint());
            }

            AuthenticationResult token = await app.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);

            return(token);
        }
示例#15
0
        private static string FindFullVoiceName(string voiceArgument)
        {
            string voiceName = null;

            using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
            {
                System.Collections.ObjectModel.ReadOnlyCollection <InstalledVoice> installedVoices = synthesizer.GetInstalledVoices();
                System.Collections.Generic.IEnumerable <InstalledVoice>            enabledVoices   = installedVoices.Where(voice => voice.Enabled);

                InstalledVoice selectedVoice = enabledVoices.FirstOrDefault(voice => voice.VoiceInfo.Name.ToLowerInvariant().Contains(voiceArgument));
                if (selectedVoice != null)
                {
                    voiceName = selectedVoice.VoiceInfo.Name;
                }
            }
            return(voiceName);
        }
        public async Task <bool> ValidateXp(int xpToAchieve, Guid id)
        {
            System.Collections.Generic.IEnumerable <GamificationLevel> all = await repository.GetAll();

            int  maxXp = all.Max(x => x.XpToAchieve);
            Guid?maxId = all.FirstOrDefault(x => x.XpToAchieve == maxXp)?.Id;

            if (id == Guid.Empty)
            {
                return(xpToAchieve > maxXp);
            }
            else if (id == maxId)
            {
                return(xpToAchieve >= maxXp);
            }
            else
            {
                return(true);
            }
        }
示例#17
0
        /// <summary>
        /// Will get the parameter value.
        /// </summary>
        /// <param name="parameters">The collection of parameters.</param>
        /// <param name="paramName">The parameter name to extract.</param>
        /// <param name="value">The output value of the parameter name.</param>
        /// <returns>A boolean value indicating if the value was found or not.</returns>
        public static bool TryGetValue(System.Collections.Generic.IEnumerable <string> parameters, string paramName, out string value)
        {
            parameters = Normalize(parameters);

            value = null;
            string paramValue = parameters.FirstOrDefault(s => s.StartsWith(paramName + "=", System.StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrEmpty(paramValue))
            {
                return(false);
            }

            paramValue = paramValue.Substring(paramName.Length + 1);
            if (string.IsNullOrEmpty(paramValue))
            {
                return(false);
            }

            value = paramValue;
            return(true);
        }
示例#18
0
        T IRepository <T> .SingleRecord(System.Linq.Expressions.Expression <Func <T, bool> > where)
        {
            using (System.Data.IDbConnection connection = Connection)
            {
                string columns      = BuildSelectColumns();
                string whereClause  = BuildWhereClause(where.Body);
                string sqlStatement = string.Format("SELECT {0} FROM [{1}].[{2}] WITH (NOLOCK) WHERE {3} ", columns, _schema, _table, whereClause);

                System.Collections.Generic.IEnumerable <T> entities = connection.Query <T>(sqlStatement);
                T entity = default(T);
                if (entities != null)
                {
                    if (entities.Any())
                    {
                        entity = entities.FirstOrDefault();
                    }
                }

                return(entity);
            }
        }
示例#19
0
        /// <summary>
        /// Gets the opposite room from the origin based on direction
        /// </summary>
        /// <param name="origin">The room we're looking to oppose</param>
        /// <param name="direction">The direction the room would be in (this method will reverse the direction itself)</param>
        /// <returns>The room that is in the direction from our room</returns>
        public static IRoomTemplate GetOpposingRoom(IRoomTemplate origin, MovementDirectionType direction)
        {
            //There is no opposite of none directionals
            if (origin == null || direction == MovementDirectionType.None)
            {
                return(null);
            }

            MovementDirectionType oppositeDirection = ReverseDirection(direction);

            System.Collections.Generic.IEnumerable <IPathwayTemplate> paths = TemplateCache.GetAll <IPathwayTemplate>();

            IPathwayTemplate ourPath = paths.FirstOrDefault(pt => origin.Equals(pt.Destination) &&
                                                            pt.DirectionType == oppositeDirection);

            if (ourPath != null)
            {
                return((IRoomTemplate)ourPath.Destination);
            }

            return(null);
        }
        private static void MontaCabecalho(FiltroRelatorioCompensacaoAusenciaDto filtros, Data.Ue ue, Data.Dre dre, System.Collections.Generic.IEnumerable <RelatorioCompensacaoAusenciaRetornoConsulta> compensacoes, System.Collections.Generic.IEnumerable <Data.ComponenteCurricularPorTurma> componentesCurriculares, RelatorioCompensacaoAusenciaDto result)
        {
            result.Bimestre = filtros.Bimestre > 0 ? filtros.Bimestre.ToString() : "Todos";


            if (filtros.ComponentesCurriculares != null && filtros.ComponentesCurriculares.Any())
            {
                if (filtros.ComponentesCurriculares.Count() == 1)
                {
                    result.ComponenteCurricular = componentesCurriculares.FirstOrDefault(a => a.CodDisciplina == filtros.ComponentesCurriculares.FirstOrDefault())?.Disciplina;
                }
                else
                {
                    result.ComponenteCurricular = "";
                }
            }
            else
            {
                result.ComponenteCurricular = "Todos";
            }

            result.Data       = DateTime.Today.ToString("dd/MM/yyyy");
            result.Modalidade = filtros.Modalidade.Name();
            result.RF         = filtros.UsuarioRf;

            if (filtros.TurmasCodigo != null && filtros.TurmasCodigo.Any())
            {
                result.TurmaNome = $"{filtros.Modalidade.ShortName()} - {compensacoes.FirstOrDefault(a => a.TurmaCodigo == filtros.TurmasCodigo[0])?.TurmaNome}";
            }
            else
            {
                result.TurmaNome = "Todas";
            }

            result.UeNome  = ue.NomeComTipoEscola;
            result.DreNome = dre.Abreviacao;
            result.Usuario = filtros.UsuarioNome;
        }
示例#21
0
        //called by CartController.cs
        //this method is overloaded
        public virtual void AddItem(Product product, int quantity)
        {
            System.Collections.Generic.IEnumerable <CartLine> cartLines = lineCollection.Where(p => p.Product.ProductID == product.ProductID);
            CartLine line = cartLines.FirstOrDefault();

            if (line == null)
            {
                lineCollection.Add(new CartLine
                {
                    Product            = product,
                    ProductName        = product.Name,
                    ProductDescription = product.Description,
                    Quantity           = quantity,
                    UnitPrice          = product.Price,
                    LineTotal          = quantity * product.Price,
                    ProductID          = product.ProductID
                });
            }
            else
            {
                line.Quantity += quantity;
            }
        }
示例#22
0
        private System.Collections.Generic.List <string> addInParametersFrom <T>(DbCommand command, T input, params string[] parametersToAdd)
        {
            if (parametersToAdd == null || parametersToAdd.Length == 0)
            {
                throw new Exception("parametersToAdd is empty");
            }
            System.Collections.Generic.IEnumerable <System.Reflection.PropertyInfo> properties =
                from p in Utilities.GetProperties(input)
                where p.CanRead
                select p;

            System.Collections.Generic.List <string> addedParameters = new System.Collections.Generic.List <string>();
            System.Array.ForEach <string>(parametersToAdd, delegate(string parameter)
            {
                System.Reflection.PropertyInfo property = properties.FirstOrDefault((System.Reflection.PropertyInfo p) => p.Name.Equals(DatabaseUtilities.GetMatchingPropertyName(parameter), System.StringComparison.CurrentCultureIgnoreCase));
                if (property != null)
                {
                    this.addInParameterFrom <T>(command, input, parameter, property);
                    addedParameters.Add(parameter);
                }
            });
            return(addedParameters);
        }
示例#23
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="operation">Operation</param>
        /// <param name="context">OperationFilterContext</param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var pars = context.ApiDescription.ParameterDescriptions;

            foreach (var par in pars)
            {
                var swaggerParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name);

                ControllerParameterDescriptor parameterDescriptor = par.ParameterDescriptor as ControllerParameterDescriptor;
                System.Collections.Generic.IEnumerable <System.Reflection.CustomAttributeData> attributes = null;

                if (parameterDescriptor != null)
                {
                    attributes = parameterDescriptor.ParameterInfo.CustomAttributes;
                }

                if (attributes != null && attributes.Count() > 0 && swaggerParam != null)
                {
                    // Required - [Required]
                    var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute));
                    if (requiredAttr != null)
                    {
                        swaggerParam.Required = true;
                    }

                    // Regex Pattern [RegularExpression]
                    var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute));
                    if (regexAttr != null)
                    {
                        string regex = (string)regexAttr.ConstructorArguments[0].Value;
                        if (swaggerParam is NonBodyParameter)
                        {
                            ((NonBodyParameter)swaggerParam).Pattern = regex;
                        }
                    }

                    // String Length [StringLength]
                    int?minLenght = null, maxLength = null;
                    var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute));
                    if (stringLengthAttr != null)
                    {
                        if (stringLengthAttr.NamedArguments.Count == 1)
                        {
                            minLenght = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value;
                        }
                        maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value;
                    }

                    var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute));
                    if (minLengthAttr != null)
                    {
                        minLenght = (int)minLengthAttr.ConstructorArguments[0].Value;
                    }

                    var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute));
                    if (maxLengthAttr != null)
                    {
                        maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value;
                    }

                    if (swaggerParam is NonBodyParameter)
                    {
                        ((NonBodyParameter)swaggerParam).MinLength = minLenght;
                        ((NonBodyParameter)swaggerParam).MaxLength = maxLength;
                    }

                    // Range [Range]
                    var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute));
                    if (rangeAttr != null)
                    {
                        int rangeMin = (int)rangeAttr.ConstructorArguments[0].Value;
                        int rangeMax = (int)rangeAttr.ConstructorArguments[1].Value;

                        if (swaggerParam is NonBodyParameter)
                        {
                            ((NonBodyParameter)swaggerParam).Minimum = rangeMin;
                            ((NonBodyParameter)swaggerParam).Maximum = rangeMax;
                        }
                    }
                }
            }
        }
 static public T GetObject <T>(
     System.Collections.Generic.IEnumerable <T> sequence, Func <T, bool> match)
 => sequence.FirstOrDefault(match);
        /// <summary>
        /// Authenticate user/application using Credentials.
        /// </summary>
        /// <param name="Credentials">Credentials to use during authentication process.</param>
        public static async System.Threading.Tasks.Task AuthenticateAsync(SoftmakeAll.SDK.Fluent.Authentication.ICredentials Credentials)
        {
            if (Credentials != null)
            {
                SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = Credentials;

                // From AccessKey
                if (Credentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application)
                {
                    SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Basic {System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{Credentials.ClientID}@{Credentials.ContextIdentifier.ToString().ToLower()}:{Credentials.ClientSecret}"))}";
                    SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Store();
                    await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization);

                    return;
                }
            }
            else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials == null)
            {
                try
                {
                    System.Text.Json.JsonElement CacheData = SoftmakeAll.SDK.Fluent.GeneralCacheHelper.ReadString().ToJsonElement();
                    if (!(CacheData.IsValid()))
                    {
                        throw new System.Exception();
                    }

                    // From AccessKey
                    if (CacheData.GetInt32("AuthType") == (int)SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application)
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = new SoftmakeAll.SDK.Fluent.Authentication.Credentials(CacheData.GetGuid("ContextIdentifier"), CacheData.GetString("ClientID"), null, (SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes)CacheData.GetInt32("AuthType"));
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = CacheData.GetString("Authorization");
                        if (System.String.IsNullOrWhiteSpace(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization))
                        {
                            throw new System.Exception();
                        }

                        await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization);

                        return;
                    }
                    else
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = new SoftmakeAll.SDK.Fluent.Authentication.Credentials(CacheData.GetJsonElement("AppMetadata").EnumerateObject().First().Value.GetGuid("client_id"));
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType = SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive;
                    }
                }
                catch { }
            }

            if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials == null)
            {
                SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                throw new System.Exception("Invalid Credentials from cache.");
            }


            // From AccessKey
            if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application)
            {
                return;
            }


            // From Public Client Application
            if ((SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult == null) || (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.ExpiresOn.Subtract(System.DateTimeOffset.UtcNow).TotalMinutes <= 5.0D))
            {
                System.String[] Scopes = new System.String[] { "openid", "https://softmakeb2c.onmicrosoft.com/48512da7-b030-4e62-be61-9e19b2c52d8a/user_impersonation" };
                if (SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication == null)
                {
                    if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive) // From Interactive
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication = SoftmakeAll.SDK.Fluent.SDKContext.CreatePublicClientApplication(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ContextIdentifier, "A_signup_signin", "http://localhost:1435");
                    }
                    else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Credentials) // From Username and Password
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication = SoftmakeAll.SDK.Fluent.SDKContext.CreatePublicClientApplication(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ContextIdentifier, "_ROPC");
                    }
                    else
                    {
                        throw new System.Exception("Invalid authentication type.");
                    }
                }

                // Getting existing Account in cache
                try
                {
                    System.Collections.Generic.IEnumerable <Microsoft.Identity.Client.IAccount> Accounts = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.GetAccountsAsync();

                    if (Accounts.Any())
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenSilent(Scopes, Accounts.FirstOrDefault()).ExecuteAsync();

                        if (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult != null)
                        {
                            SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Bearer {SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken}";
                            await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken);

                            return;
                        }
                    }
                }
                catch
                {
                    SoftmakeAll.SDK.Fluent.GeneralCacheHelper.Clear();
                }


                if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive) // From Interactive
                {
                    try
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenInteractive(Scopes).WithPrompt(Microsoft.Identity.Client.Prompt.ForceLogin).ExecuteAsync();
                    }
                    catch { }
                }
                else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Credentials) // From Username and Password
                {
                    if (System.String.IsNullOrWhiteSpace(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientSecret))
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                        throw new System.Exception("Authentication aborted. Please, re-enter credentials.");
                    }

                    System.Security.SecureString Password = new System.Security.SecureString();
                    foreach (System.Char Char in SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientSecret)
                    {
                        Password.AppendChar(Char);
                    }
                    Password.MakeReadOnly();

                    try
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenByUsernamePassword(Scopes, SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientID, Password).ExecuteAsync();

                        Password.Dispose();
                    }
                    catch
                    {
                        Password.Dispose();
                        SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                        throw new System.Exception("Invalid username or password.");
                    }
                }

                if (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult == null)
                {
                    SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                    throw new System.Exception("Authentication aborted.");
                }


                SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Bearer {SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken}";
                await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken);

                return;
            }
        }
示例#26
0
        public static void Tick(EventArgs args)
        {
            if (!Game.IsInGame || Game.IsPaused || Game.IsWatchingGame)
            {
                return;
            }
            me = ObjectMgr.LocalHero;
            if (me == null)
            {
                return;
            }
            if (me.ClassID != ClassID.CDOTA_Unit_Hero_EarthSpirit)
            {
                return;
            }


            //SKILLS

            if (Qskill == null)
            {
                Qskill = me.Spellbook.SpellQ;
            }
            if (Wskill == null)
            {
                Wskill = me.Spellbook.SpellW;
            }
            if (Eskill == null)
            {
                Eskill = me.Spellbook.SpellE;
            }
            if (DRemnant == null)
            {
                DRemnant = me.Spellbook.SpellD;
            }
            if (Rskill == null)
            {
                Rskill = me.Spellbook.SpellR;
            }
            if (Fskill == null)
            {
                Fskill = me.Spellbook.SpellF;
            }

            // UNIT VARIABLES

            stone_for_combo = ObjectMgr.GetEntities <Unit>().Where(x => x.ClassID == ClassID.CDOTA_Unit_Earth_Spirit_Stone && me.Distance2D(x.NetworkPosition) < 200).FirstOrDefault();
            stone           = ObjectMgr.GetEntities <Unit>().Where(x => x.ClassID == ClassID.CDOTA_Unit_Earth_Spirit_Stone && x.NetworkPosition.Distance2D(me.NetworkPosition) <= 1300).ToList();
            if (boulder_slow == null || stage_combo4 == 0)
            {
                boulder_slow = ObjectMgr.GetEntities <Hero>().Where(x => x.Team != me.Team && x.IsVisible && !x.IsIllusion && x.NetworkPosition.Distance2D(me.NetworkPosition) < 200 && x.Modifiers.Any(y => y.Name == "modifier_earth_spirit_rolling_boulder_slow")).FirstOrDefault();
            }
            if (stage == 2 && stunned == null)
            {
                stunned = ObjectMgr.GetEntities <Hero>().Where(x => x.Modifiers.Any(y => y.Name == "modifier_stunned") && !x.IsIllusion && x.Team != me.Team && x.IsVisible).FirstOrDefault();
            }

            //KEYS TOGGLE

            if ((Game.IsKeyDown(_hotkeys_config.Item("hotkeycombo1").GetValue <KeyBind>().Key)) && !Game.IsChatOpen && stunned == null)
            {
                key_active = true;
            }
            if ((Game.IsKeyDown(_hotkeys_config.Item("hotkeycombo3").GetValue <KeyBind>().Key)) && !Game.IsChatOpen)
            {
                key_active_2 = true;
            }
            if ((Game.IsKeyDown(_hotkeys_config.Item("hotkeycombo5").GetValue <KeyBind>().Key)) && !Game.IsChatOpen)
            {
                key_active_4 = true;
            }

            if (key_active == false)
            {
                stage = 0; key_active = false; stunned = null;
            }

            if (me.CanCast() && !me.IsChanneling() && key_active)
            {
                Mouse_Position = Game.MousePosition;
                if ((!Eskill.CanBeCasted() && !Qskill.CanBeCasted() && !Wskill.CanBeCasted() && (!DRemnant.CanBeCasted() && stone_for_combo == null) || ((!DRemnant.CanBeCasted() && stone_for_combo == null))) || (Game.IsKeyDown(_hotkeys_config.Item("hotkeycombo2").GetValue <KeyBind>().Key)))
                {
                    if (auto_atack_after_spell)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 1");
                        auto_atack_after_spell = false;
                    }
                    if (auto_atack)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack 1");
                        auto_atack = false;
                    }
                    key_active = false;
                    stage      = 0;
                    stunned    = null;
                }
                if (stage == 0 && Utils.SleepCheck("auto_atack_change"))
                {
                    if (Game.GetConsoleVar("dota_player_units_auto_attack_after_spell").GetInt() == 1)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 0");
                        auto_atack_after_spell = true;
                    }
                    else
                    {
                        auto_atack_after_spell = false;
                    }
                    if (Game.GetConsoleVar("dota_player_units_auto_attack").GetInt() == 1)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack 0");
                        auto_atack = true;
                    }
                    else
                    {
                        auto_atack = false;
                    }
                    stage = 1;
                    Utils.Sleep(Game.Ping, "auto_atack_change");
                }
                else if (stage == 1 && Utils.SleepCheck("Qskill") && Utils.SleepCheck("auto_atack_change"))
                {
                    if (DRemnant.CanBeCasted() && Utils.SleepCheck("DRemnant") && stone_for_combo == null && (Qskill.CanBeCasted() && Wskill.CanBeCasted() && Eskill.CanBeCasted()))
                    {
                        DRemnant.UseAbility(me.NetworkPosition);
                        Utils.Sleep(500 - (int)Game.Ping, "DRemnant");
                    }
                    if (Qskill.CanBeCasted())
                    {
                        Qskill.UseAbility((Mouse_Position - me.NetworkPosition) * 200 / Mouse_Position.Distance2D(me) + me.NetworkPosition);
                        Utils.Sleep((int)Game.Ping + 50, "Qskill");
                    }
                    else
                    {
                        stage = 2;
                    }
                }
                else if (stage == 2 && stunned != null && Utils.SleepCheck("Eskill"))
                {
                    stone_nearly = stone.Where(x => stunned.Distance2D(x) < stunned.Distance2D((me.NetworkPosition - stunned.NetworkPosition) * 400 / stunned.NetworkPosition.Distance2D(me.NetworkPosition) + stunned.NetworkPosition)).FirstOrDefault();
                    if (Eskill.CanBeCasted())
                    {
                        if (stone_nearly != null)
                        {
                            if (Game.Ping < 100)
                            {
                                Eskill.UseAbility(stone_nearly.NetworkPosition);
                                Utils.Sleep((int)Game.Ping + 100, "Eskill");
                            }
                            else
                            {
                                Eskill.UseAbility(stunned.Predict(-Game.Ping));
                                Utils.Sleep((int)Game.Ping + 100, "Eskill");
                            }
                        }
                    }
                    else
                    {
                        stage = 3;
                    }
                }
                else if ((Game.IsKeyDown(_hotkeys_config.Item("hotkeycombo1").GetValue <KeyBind>().Key)) && stage == 2 && Utils.SleepCheck("Eskill") && stunned == null)
                {
                    stone_nearly = stone.Where(x => x.NetworkPosition.Distance2D(Mouse_Position) < 200).FirstOrDefault();
                    if (Eskill.CanBeCasted() && stone_nearly != null)
                    {
                        Eskill.UseAbility(Mouse_Position);
                        Utils.Sleep(100, "Eskill");
                    }
                    if (!Eskill.CanBeCasted())
                    {
                        stage = 3;
                    }
                }
                else if (stage == 3 && stunned != null && stunned.Modifiers.Any(x => x.Name == "modifier_earth_spirit_geomagnetic_grip_debuff") && Utils.SleepCheck("Wskill"))
                {
                    if (auto_atack_after_spell)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 1");
                        Utils.Sleep(Game.Ping + 50, "auto_attack_1");
                        auto_atack_after_spell = false;
                    }
                    if (auto_atack)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack 1");
                        Utils.Sleep(Game.Ping + 50, "auto_attack_1");
                        auto_atack = false;
                    }
                    if (Wskill.CanBeCasted() && Utils.SleepCheck("auto_attack_1"))
                    {
                        Wskill.UseAbility(stunned.NetworkPosition);
                        Utils.Sleep(Game.Ping + (Qskill.GetCastDelay(me, stunned, true, true) * 100), "Wskill");
                    }
                }
                else if (stage == 3 && stunned == null && Utils.SleepCheck("Wskill") && (Game.IsKeyDown(_hotkeys_config.Item("hotkeycombo1").GetValue <KeyBind>().Key)))
                {
                    if (auto_atack_after_spell)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 1");
                        Utils.Sleep(Game.Ping + 50, "auto_attack_1");
                        auto_atack_after_spell = false;
                    }
                    if (auto_atack)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack 1");
                        Utils.Sleep(Game.Ping + 50, "auto_attack_1");
                        auto_atack = false;
                    }
                    if (Wskill.CanBeCasted() && Utils.SleepCheck("auto_attack_1"))
                    {
                        Wskill.UseAbility(Mouse_Position);
                        Utils.Sleep((int)Game.Ping + 100, "Wskill");
                    }
                }
                else if (!Wskill.CanBeCasted())
                {
                    stage      = 0;
                    key_active = false;
                    stunned    = null;
                    if (auto_atack_after_spell)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 1");
                        auto_atack_after_spell = false;
                    }
                    if (auto_atack)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack 1");
                        auto_atack = false;
                    }
                }
            }
            if (key_active_2 && !Game.IsChatOpen)
            {
                if ((Game.IsKeyDown(_hotkeys_config.Item("hotkeycombo2").GetValue <KeyBind>().Key) && !Game.IsChatOpen))
                {
                    stage_combo2 = 0;
                    key_active_2 = false;
                    if (auto_atack_after_spell)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 1");
                        auto_atack_after_spell = false;
                    }
                    if (auto_atack)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack 1");
                        auto_atack = false;
                    }
                }
                if (stage_combo2 == 0 || stone_peoples == null)
                {
                    stone_peoples  = ObjectMgr.GetEntities <Hero>().Where(x => !x.IsIllusion && x.Modifiers.Any(xy => xy.Name == "modifier_earthspirit_petrify") && x.Distance2D(me) <= 1600);
                    Mouse_Position = Game.MousePosition;
                }
                if (stone_peoples.FirstOrDefault() != null && me.CanCast() && !me.IsChanneling())
                {
                    if (stage_combo2 == 0)
                    {
                        if (Game.GetConsoleVar("dota_player_units_auto_attack_after_spell").GetInt() == 1)
                        {
                            Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 0");
                            auto_atack_after_spell = true;
                        }
                        else
                        {
                            auto_atack_after_spell = false;
                        }
                        if (Game.GetConsoleVar("dota_player_units_auto_attack").GetInt() == 1)
                        {
                            Game.ExecuteCommand("dota_player_units_auto_attack 0");
                            auto_atack = true;
                        }
                        else
                        {
                            auto_atack = false;
                        }
                        Utils.Sleep(Game.Ping + 50, "auto_atack_change");
                        stage_combo2 = 1;
                    }
                    if (stage_combo2 == 1 && Utils.SleepCheck("EskillSleep") && Utils.SleepCheck("auto_atack_change"))
                    {
                        if (Eskill.CanBeCasted() && stone_peoples.FirstOrDefault().NetworkPosition.Distance2D(me) >= 180)
                        {
                            Eskill.UseAbility(stone_peoples.FirstOrDefault().NetworkPosition);
                            Utils.Sleep(Game.Ping, "EskillSleep");
                        }
                        else
                        {
                            stage_combo2 = 2;
                        }
                    }
                    else if (stage_combo2 == 2)
                    {
                        if (Wskill.CanBeCasted())
                        {
                            int DelayCombo = 0;
                            if (stone_peoples.FirstOrDefault().NetworkPosition.Distance2D(stone_peoples.FirstOrDefault().NetworkPosition / me.NetworkPosition * 100) < 200)
                            {
                                DelayCombo = 150 - (int)Game.Ping;
                            }
                            else
                            {
                                DelayCombo = 400 - (int)Game.Ping;
                            }
                            Wskill.UseAbility(Mouse_Position);
                            Utils.Sleep(Game.Ping + DelayCombo + (me.GetTurnTime(Mouse_Position) * 100), "PerfectDelay");
                        }
                        else
                        {
                            stage_combo2 = 3;
                        }
                    }
                    else if (stage_combo2 == 3 && Utils.SleepCheck("PerfectDelay"))
                    {
                        if (Qskill.CanBeCasted())
                        {
                            Qskill.UseAbility(Mouse_Position);
                        }
                        else
                        {
                            stage_combo2 = 0;
                            key_active_2 = false;
                            if (auto_atack_after_spell)
                            {
                                Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 1");
                                auto_atack_after_spell = false;
                            }
                            if (auto_atack)
                            {
                                auto_atack = false;
                                Game.ExecuteCommand("dota_player_units_auto_attack 1");
                            }
                        }
                    }
                }
                if (stone_peoples.FirstOrDefault() == null || !me.CanCast())
                {
                    stage_combo2 = 0;
                    key_active_2 = false;
                    if (auto_atack_after_spell)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 1");
                        auto_atack_after_spell = false;
                    }
                    if (auto_atack)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack 1");
                        auto_atack = false;
                    }
                }
            }
            if (key_active_4 && !Game.IsChatOpen)
            {
                if ((stage_combo4 == 0 && (!Qskill.CanBeCasted() || !Wskill.CanBeCasted())) || (Game.IsKeyDown(_hotkeys_config.Item("hotkeycombo2").GetValue <KeyBind>().Key) && !Game.IsChatOpen))
                {
                    stage_combo4 = 0;
                    key_active_4 = false;
                    if (auto_atack_after_spell)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 1");
                        auto_atack_after_spell = false;
                    }
                    if (auto_atack)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack 1");
                        auto_atack = false;
                    }
                }
                if (stage_combo4 == 0)
                {
                    if (Game.GetConsoleVar("dota_player_units_auto_attack_after_spell").GetInt() == 1)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 0");
                        auto_atack_after_spell = true;
                    }
                    else
                    {
                        auto_atack_after_spell = false;
                    }
                    if (Game.GetConsoleVar("dota_player_units_auto_attack").GetInt() == 1)
                    {
                        Game.ExecuteCommand("dota_player_units_auto_attack 0");
                        auto_atack = true;
                    }
                    else
                    {
                        auto_atack = false;
                    }
                    Utils.Sleep(Game.Ping + 50, "auto_atack_change");
                    stage_combo4 = 1;
                }
                else if (stage_combo4 == 1 && Utils.SleepCheck("auto_atack_change"))
                {
                    Mouse_Position  = Game.MousePosition;
                    stone_for_combo = ObjectMgr.GetEntities <Unit>().Where(x => x.ClassID == ClassID.CDOTA_Unit_Earth_Spirit_Stone && Mouse_Position.Distance2D(x.NetworkPosition) < 200).FirstOrDefault();
                    Hero geomagnetic_target = ObjectMgr.GetEntities <Hero>().Where(x => x.Team != me.Team && x.IsVisible && !x.IsIllusion && x.NetworkPosition.Distance2D(me.NetworkPosition) <= 1600 && x.Modifiers.Any(y => y.Name == "modifier_earth_spirit_geomagnetic_grip_debuff")).FirstOrDefault();
                    if (DRemnant.CanBeCasted() && Utils.SleepCheck("DRemnant") && stone_for_combo == null && (Qskill.CanBeCasted() && Wskill.CanBeCasted() && Eskill.CanBeCasted()))
                    {
                        DRemnant.UseAbility(Mouse_Position);
                        Utils.Sleep((int)Game.Ping + 2000, "DRemnant");
                    }
                    else if (Eskill.CanBeCasted() && Utils.SleepCheck("Eskill_3combo"))
                    {
                        Eskill.UseAbility(Mouse_Position);
                        Utils.Sleep(500, "Eskill_3combo");
                    }
                    else if ((!Eskill.CanBeCasted() || Eskill.Level == 0) && geomagnetic_target == null)
                    {
                        stone_for_combo = ObjectMgr.GetEntities <Unit>().Where(x => x.ClassID == ClassID.CDOTA_Unit_Earth_Spirit_Stone && me.Distance2D(x.NetworkPosition) < 400).FirstOrDefault();
                        if (DRemnant.CanBeCasted() && Utils.SleepCheck("DRemnant") && stone_for_combo == null && (Qskill.CanBeCasted() && Wskill.CanBeCasted()))
                        {
                            DRemnant.UseAbility(me.NetworkPosition);
                            Utils.Sleep((int)Game.Ping + 2000, "DRemnant");
                        }
                        else
                        {
                            stage_combo4 = 2;
                        }
                    }
                    else if ((!Eskill.CanBeCasted() || Eskill.Level == 0) && stone_for_combo != null)
                    {
                        stage_combo4 = 2;
                    }
                }
                else if (stage_combo4 == 2)
                {
                    if (Wskill.CanBeCasted() && Utils.SleepCheck("Wskill_3combo"))
                    {
                        Wskill.UseAbility(Mouse_Position);
                        Utils.Sleep(500, "Wskill_3combo");
                    }
                    if (!Wskill.CanBeCasted())
                    {
                        stage_combo4 = 3;
                    }
                }
                else if (stage_combo4 == 3)
                {
                    if (boulder_slow != null)
                    {
                        Mouse_Position = Game.MousePosition;
                        Vector3 perfect_position = (boulder_slow.NetworkPosition - Mouse_Position) * 150 / boulder_slow.NetworkPosition.Distance2D(Mouse_Position) + boulder_slow.NetworkPosition;
                        if (Utils.SleepCheck("moving") && me.NetworkPosition.Distance2D(perfect_position) >= 70)
                        {
                            me.Move(perfect_position);
                            Utils.Sleep(500 - Game.Ping, "moving");
                        }
                        if (me.NetworkPosition.ToVector2().FindAngleBetween(Mouse_Position.ToVector2(), true) - me.NetworkPosition.ToVector2().FindAngleBetween(boulder_slow.NetworkPosition.ToVector2(), true) <= 0.1 && me.NetworkPosition.ToVector2().FindAngleBetween(Mouse_Position.ToVector2(), true) - me.NetworkPosition.ToVector2().FindAngleBetween(boulder_slow.NetworkPosition.ToVector2(), true) >= -0.1)
                        {
                            if (Qskill.CanBeCasted() && Utils.SleepCheck("Qskill_combo3"))
                            {
                                Qskill.UseAbility(boulder_slow);
                                Utils.Sleep(500, "Qskill_combo3");
                            }
                            if (!Qskill.CanBeCasted())
                            {
                                stage_combo4 = 0;
                                key_active_4 = false;
                                if (auto_atack_after_spell)
                                {
                                    Game.ExecuteCommand("dota_player_units_auto_attack_after_spell 1");
                                    auto_atack_after_spell = false;
                                }
                                if (auto_atack)
                                {
                                    Game.ExecuteCommand("dota_player_units_auto_attack 1");
                                    auto_atack = false;
                                }
                            }
                        }
                    }
                }
            }
            //if (key_active_3 && !Game.IsChatOpen)
            //{
            //    if (stun_target == null || stage_combo3 == 0)
            //    {
            //        Mouse_Position = Game.MousePosition;
            //        stun_target = ObjectMgr.GetEntities<Hero>().Where(x => x.Team != me.Team && !x.IsIllusion && x.IsAlive && x.Distance2D(me) <= 1600);
            //    }
            //    int distance = 0;
            //    int last_distance = 50000;
            //    Hero most_closer_mouse_position_hero;
            //    foreach (var v in stun_target)
            //    {
            //        distance = (int)v.NetworkPosition.Distance2D(Mouse_Position);
            //        if (distance < last_distance)
            //        {
            //            last_distance = distance;
            //            most_closer_mouse_position_hero = v;
            //        }
            //    }

            //}
        }
示例#27
0
        /// <include file='../../../../../../doc/snippets/Microsoft.Data.SqlClient/ActiveDirectoryAuthenticationProvider.xml' path='docs/members[@name="ActiveDirectoryAuthenticationProvider"]/AcquireTokenAsync/*'/>
        public override Task <SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters) => Task.Run(async() =>
        {
            AuthenticationResult result;
            string scope    = parameters.Resource.EndsWith(s_defaultScopeSuffix) ? parameters.Resource : parameters.Resource + s_defaultScopeSuffix;
            string[] scopes = new string[] { scope };

            if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryServicePrincipal)
            {
                IConfidentialClientApplication ccApp = ConfidentialClientApplicationBuilder.Create(parameters.UserId)
                                                       .WithAuthority(parameters.Authority)
                                                       .WithClientSecret(parameters.Password)
                                                       .WithClientName(Common.DbConnectionStringDefaults.ApplicationName)
                                                       .WithClientVersion(Common.ADP.GetAssemblyVersion().ToString())
                                                       .Build();

                result = ccApp.AcquireTokenForClient(scopes).ExecuteAsync().Result;
                SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token for Active Directory Service Principal auth mode. Expiry Time: {0}", result.ExpiresOn);
                return(new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn));
            }

            /*
             * Today, MSAL.NET uses another redirect URI by default in desktop applications that run on Windows
             * (urn:ietf:wg:oauth:2.0:oob). In the future, we'll want to change this default, so we recommend
             * that you use https://login.microsoftonline.com/common/oauth2/nativeclient.
             *
             * https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-app-registration#redirect-uris
             */
            string redirectURI = "https://login.microsoftonline.com/common/oauth2/nativeclient";

#if NETCOREAPP
            if (parameters.AuthenticationMethod != SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow)
            {
                redirectURI = "http://localhost";
            }
#endif
            IPublicClientApplication app;

#if NETSTANDARD
            if (parentActivityOrWindowFunc != null)
            {
                app = PublicClientApplicationBuilder.Create(_applicationClientId)
                      .WithAuthority(parameters.Authority)
                      .WithClientName(Common.DbConnectionStringDefaults.ApplicationName)
                      .WithClientVersion(Common.ADP.GetAssemblyVersion().ToString())
                      .WithRedirectUri(redirectURI)
                      .WithParentActivityOrWindow(parentActivityOrWindowFunc)
                      .Build();
            }
#endif
#if NETFRAMEWORK
            if (_iWin32WindowFunc != null)
            {
                app = PublicClientApplicationBuilder.Create(_applicationClientId)
                      .WithAuthority(parameters.Authority)
                      .WithClientName(Common.DbConnectionStringDefaults.ApplicationName)
                      .WithClientVersion(Common.ADP.GetAssemblyVersion().ToString())
                      .WithRedirectUri(redirectURI)
                      .WithParentActivityOrWindow(_iWin32WindowFunc)
                      .Build();
            }
#endif
#if !NETCOREAPP
            else
#endif
            {
                app = PublicClientApplicationBuilder.Create(_applicationClientId)
                      .WithAuthority(parameters.Authority)
                      .WithClientName(Common.DbConnectionStringDefaults.ApplicationName)
                      .WithClientVersion(Common.ADP.GetAssemblyVersion().ToString())
                      .WithRedirectUri(redirectURI)
                      .Build();
            }

            if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryIntegrated)
            {
                if (!string.IsNullOrEmpty(parameters.UserId))
                {
                    result = app.AcquireTokenByIntegratedWindowsAuth(scopes)
                             .WithCorrelationId(parameters.ConnectionId)
                             .WithUsername(parameters.UserId)
                             .ExecuteAsync().Result;
                }
                else
                {
                    result = app.AcquireTokenByIntegratedWindowsAuth(scopes)
                             .WithCorrelationId(parameters.ConnectionId)
                             .ExecuteAsync().Result;
                }
                SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token for Active Directory Integrated auth mode. Expiry Time: {0}", result.ExpiresOn);
            }
            else if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryPassword)
            {
                SecureString password = new SecureString();
                foreach (char c in parameters.Password)
                {
                    password.AppendChar(c);
                }
                password.MakeReadOnly();
                result = app.AcquireTokenByUsernamePassword(scopes, parameters.UserId, password)
                         .WithCorrelationId(parameters.ConnectionId)
                         .ExecuteAsync().Result;
                SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token for Active Directory Password auth mode. Expiry Time: {0}", result.ExpiresOn);
            }
            else if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive ||
                     parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow)
            {
                System.Collections.Generic.IEnumerable <IAccount> accounts = await app.GetAccountsAsync();
                IAccount account;
                if (!string.IsNullOrEmpty(parameters.UserId))
                {
                    account = accounts.FirstOrDefault(a => parameters.UserId.Equals(a.Username, System.StringComparison.InvariantCultureIgnoreCase));
                }
                else
                {
                    account = accounts.FirstOrDefault();
                }

                if (null != account)
                {
                    try
                    {
                        result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync();
                        SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (silent) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result.ExpiresOn);
                    }
                    catch (MsalUiRequiredException)
                    {
                        result = await AcquireTokenInteractiveDeviceFlowAsync(app, scopes, parameters.ConnectionId, parameters.UserId, parameters.AuthenticationMethod);
                        SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (interactive) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result.ExpiresOn);
                    }
                }
                else
                {
                    result = await AcquireTokenInteractiveDeviceFlowAsync(app, scopes, parameters.ConnectionId, parameters.UserId, parameters.AuthenticationMethod);
                    SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (interactive) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result.ExpiresOn);
                }
            }
            else
            {
                SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | {0} authentication mode not supported by ActiveDirectoryAuthenticationProvider class.", parameters.AuthenticationMethod);
                throw SQL.UnsupportedAuthenticationSpecified(parameters.AuthenticationMethod);
            }

            return(new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn));
        });
示例#28
0
        public override Character GetTarget(System.Collections.Generic.IEnumerable <Character> targetsList)
        {
            Character target = targetsList.FirstOrDefault(t => t.Team != this.Team && t.IsAlive);

            return(target);
        }
示例#29
0
        /// <include file='../../../../../../doc/snippets/Microsoft.Data.SqlClient/ActiveDirectoryAuthenticationProvider.xml' path='docs/members[@name="ActiveDirectoryAuthenticationProvider"]/AcquireTokenAsync/*'/>
        public override Task <SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters) => Task.Run(async() =>
        {
            AuthenticationResult result;
            string scope    = parameters.Resource.EndsWith(s_defaultScopeSuffix) ? parameters.Resource : parameters.Resource + s_defaultScopeSuffix;
            string[] scopes = new string[] { scope };

            if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryServicePrincipal)
            {
                IConfidentialClientApplication ccApp = ConfidentialClientApplicationBuilder.Create(parameters.UserId)
                                                       .WithAuthority(parameters.Authority)
                                                       .WithClientSecret(parameters.Password)
                                                       .WithClientName(Common.DbConnectionStringDefaults.ApplicationName)
                                                       .WithClientVersion(Common.ADP.GetAssemblyVersion().ToString())
                                                       .Build();

                result = ccApp.AcquireTokenForClient(scopes).ExecuteAsync().Result;
                SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token for Active Directory Service Principal auth mode. Expiry Time: {0}", result.ExpiresOn);
                return(new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn));
            }

            /*
             * Today, MSAL.NET uses another redirect URI by default in desktop applications that run on Windows
             * (urn:ietf:wg:oauth:2.0:oob). In the future, we'll want to change this default, so we recommend
             * that you use https://login.microsoftonline.com/common/oauth2/nativeclient.
             *
             * https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-app-registration#redirect-uris
             */
            string redirectUri = s_nativeClientRedirectUri;

#if NETCOREAPP
            if (parameters.AuthenticationMethod != SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow)
            {
                redirectUri = "http://localhost";
            }
#endif
            PublicClientAppKey pcaKey = new PublicClientAppKey(parameters.Authority, redirectUri, _applicationClientId
#if NETFRAMEWORK
                                                               , _iWin32WindowFunc
#endif
#if NETSTANDARD
                                                               , _parentActivityOrWindowFunc
#endif
                                                               );

            IPublicClientApplication app = GetPublicClientAppInstance(pcaKey);

            if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryIntegrated)
            {
                if (!string.IsNullOrEmpty(parameters.UserId))
                {
                    result = app.AcquireTokenByIntegratedWindowsAuth(scopes)
                             .WithCorrelationId(parameters.ConnectionId)
                             .WithUsername(parameters.UserId)
                             .ExecuteAsync().Result;
                }
                else
                {
                    result = app.AcquireTokenByIntegratedWindowsAuth(scopes)
                             .WithCorrelationId(parameters.ConnectionId)
                             .ExecuteAsync().Result;
                }
                SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token for Active Directory Integrated auth mode. Expiry Time: {0}", result.ExpiresOn);
            }
            else if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryPassword)
            {
                SecureString password = new SecureString();
                foreach (char c in parameters.Password)
                {
                    password.AppendChar(c);
                }
                password.MakeReadOnly();
                result = app.AcquireTokenByUsernamePassword(scopes, parameters.UserId, password)
                         .WithCorrelationId(parameters.ConnectionId)
                         .ExecuteAsync().Result;
                SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token for Active Directory Password auth mode. Expiry Time: {0}", result.ExpiresOn);
            }
            else if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive ||
                     parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow)
            {
                // Fetch available accounts from 'app' instance
                System.Collections.Generic.IEnumerable <IAccount> accounts = await app.GetAccountsAsync();
                IAccount account;
                if (!string.IsNullOrEmpty(parameters.UserId))
                {
                    account = accounts.FirstOrDefault(a => parameters.UserId.Equals(a.Username, System.StringComparison.InvariantCultureIgnoreCase));
                }
                else
                {
                    account = accounts.FirstOrDefault();
                }

                if (null != account)
                {
                    try
                    {
                        // If 'account' is available in 'app', we use the same to acquire token silently.
                        // Read More on API docs: https://docs.microsoft.com/dotnet/api/microsoft.identity.client.clientapplicationbase.acquiretokensilent
                        result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync();
                        SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (silent) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result.ExpiresOn);
                    }
                    catch (MsalUiRequiredException)
                    {
                        // An 'MsalUiRequiredException' is thrown in the case where an interaction is required with the end user of the application,
                        // for instance, if no refresh token was in the cache, or the user needs to consent, or re-sign-in (for instance if the password expired),
                        // or the user needs to perform two factor authentication.
                        result = await AcquireTokenInteractiveDeviceFlowAsync(app, scopes, parameters.ConnectionId, parameters.UserId, parameters.AuthenticationMethod);
                        SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (interactive) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result.ExpiresOn);
                    }
                }
                else
                {
                    // If no existing 'account' is found, we request user to sign in interactively.
                    result = await AcquireTokenInteractiveDeviceFlowAsync(app, scopes, parameters.ConnectionId, parameters.UserId, parameters.AuthenticationMethod);
                    SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (interactive) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result.ExpiresOn);
                }
            }
            else
            {
                SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | {0} authentication mode not supported by ActiveDirectoryAuthenticationProvider class.", parameters.AuthenticationMethod);
                throw SQL.UnsupportedAuthenticationSpecified(parameters.AuthenticationMethod);
            }

            return(new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn));
        });
示例#30
0
        public override async System.Threading.Tasks.Task <System.Collections.Generic.IEnumerable <Lpp.Dns.DTO.DataMartDTO> > Insert(System.Collections.Generic.IEnumerable <Lpp.Dns.DTO.DataMartDTO> values)
        {
            await CheckForDuplicates(values);

            var dmDTO = values.FirstOrDefault();

            if (dmDTO.ID == null || dmDTO.ID == Guid.Empty)
            {
                dmDTO.ID = Lpp.Utilities.DatabaseEx.NewGuid();
            }


            Guid networkID = await CNDSEntityUpdater.GetNetworkID(DataContext);

            if (CNDSEntityUpdater.CanUpdateCNDS)
            {
                try
                {
                    using (var cnds = new CNDSEntityUpdater(networkID))
                    {
                        await CNDSEntityUpdater.RegisterOrUpdateDataSources(dmDTO);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message, ex);
                    throw;
                }
            }

            var clientBasedTypeID = DataContext.DataMartTypes.Where(t => t.Name == "Client based").Select(t => t.ID).FirstOrDefault();
            var dm = new DataMart
            {
                ID              = dmDTO.ID.Value,
                Name            = dmDTO.Name,
                Acronym         = dmDTO.Acronym,
                OrganizationID  = dmDTO.OrganizationID.Value,
                DataMartTypeID  = dmDTO.DataMartTypeID == Guid.Empty ? clientBasedTypeID : dmDTO.DataMartTypeID,
                IsGroupDataMart = dmDTO.IsGroupDataMart,
                UnattendedMode  = dmDTO.UnattendedMode,
                IsLocal         = dmDTO.IsLocal,
                Url             = dmDTO.Url,
            };

            if (dmDTO.AdapterID.HasValue)
            {
                dm.AdapterID = dmDTO.AdapterID;
            }

            if (dmDTO.ProcessorID.HasValue)
            {
                dm.ProcessorID = dmDTO.ProcessorID;
            }

            DataContext.DataMarts.Add(dm);

            DataContext.SaveChanges();


            IList <DataMartDTO> returnDM = new List <DataMartDTO>();

            returnDM.Add(dmDTO);
            return(returnDM);
        }