Example #1
0
 public static void AvoidBumpingThings(EntityCache thisBigObject, string module)
 {
     //if It hasn't been at least 60 seconds since we last session changed do not do anything
     if (Cache.Instance.InStation || !Cache.Instance.InSpace || Cache.Instance.DirectEve.ActiveShip.Entity.IsCloaked || (Cache.Instance.InSpace && Cache.Instance.LastSessionChange.AddSeconds(60) < DateTime.Now))
         return;
     //
     // if we are "too close" to the bigObject move away... (is orbit the best thing to do here?)
     //
     if (Cache.Instance.ClosestStargate.Distance > 9000 || Cache.Instance.ClosestStation.Distance > 5000)
     {
         //EntityCache thisBigObject = Cache.Instance.BigObjects.FirstOrDefault();
         if (thisBigObject != null)
         {
             if (thisBigObject.Distance >= (int)Distance.TooCloseToStructure)
             {
                 //we are no longer "too close" and can proceed.
                 AvoidBumpingThingsTimeStamp = DateTime.Now;
                 SafeDistanceFromStructureMultiplier = 1;
                 AvoidBumpoingThingsWarningSent = false;
             }
             else
             {
                 if (DateTime.Now > Cache.Instance.NextOrbit)
                 {
                     if (DateTime.Now > AvoidBumpingThingsTimeStamp.AddSeconds(30))
                     {
                         if (SafeDistanceFromStructureMultiplier <= 4)
                         {
                             //
                             // for simplicitys sake we reset this timestamp every 30 sec until the multiplier hits 5 then it should stay static until we arent "too close" anymore
                             //
                             AvoidBumpingThingsTimeStamp = DateTime.Now;
                             SafeDistanceFromStructureMultiplier++;
                         }
                         if (DateTime.Now > AvoidBumpingThingsTimeStamp.AddMinutes(5) && !AvoidBumpoingThingsWarningSent)
                         {
                             Logging.Log("NavigateOnGrid","We are stuck on a object and have been trying to orbit away from it for over 5 min", Logging.orange);
                             AvoidBumpoingThingsWarningSent = true;
                         }
                         if (DateTime.Now > AvoidBumpingThingsTimeStamp.AddMinutes(15))
                         {
                             Cache.Instance.CloseQuestorCMDLogoff = false;
                             Cache.Instance.CloseQuestorCMDExitGame = true;
                             Cache.Instance.ReasonToStopQuestor = "navigateOnGrid: We have been stuck on an object for over 15 min";
                             Logging.Log("ReasonToStopQuestor", Cache.Instance.ReasonToStopQuestor, Logging.yellow);
                             Cache.Instance.SessionState = "Quitting";
                         }
                     }
                     thisBigObject.Orbit((int)Distance.SafeDistancefromStructure * SafeDistanceFromStructureMultiplier);
                     Logging.Log(module,
                                ": initiating Orbit of [" + thisBigObject.Name +
                                   "] orbiting at [" + ((int)Distance.SafeDistancefromStructure * SafeDistanceFromStructureMultiplier) + "]", Logging.white);
                 }
                 return;
                 //we are still too close, do not continue through the rest until we are not "too close" anymore
             }
         }
     }
 }
Example #2
0
        static void Main(string[] args)
        {
            string productName = "Lamp";

            using (var cache = new EntityCache<Product, StoreDbContext>(p => p.Name == "Lamp"))
            {
                Console.WriteLine("Press any key to stop listening for changes...");

                while (true)
                {
                    Console.WriteLine(cache.Results.Count());
                    Thread.Sleep(1000);

                    if (Console.KeyAvailable)
                        break;
                }
            }

            return;

            using (var notifer = new EntityChangeNotifier<Product, StoreDbContext>(p => p.Name == productName))
            {
                notifer.Error += (sender, e) =>
                {
                    Console.WriteLine("[{0}, {1}, {2}]:\n{3}", e.Reason.Info, e.Reason.Source, e.Reason.Type, e.Sql);
                };

                notifer.Changed += (sender, e) =>
                {
                    Console.WriteLine(e.Results.Count());
                    foreach (var p in e.Results)
                    {
                        Console.WriteLine("  {0}", p.Name);
                    }
                };

                using (var otherNotifier = new EntityChangeNotifier<Product, StoreDbContext>(x => x.Name == "Desk"))
                {
                    otherNotifier.Changed += (sender, e) =>
                    {
                        Console.WriteLine(e.Results.Count());
                    };

                    Console.WriteLine("Press any key to stop listening for changes...");
                    Console.ReadKey(true);
                }

                Console.WriteLine("Press any key to stop...");
                Console.ReadKey(true);
            }
        }
Example #3
0
        /// <summary>
        ///  设置默认主键排序
        /// </summary>
        private void setPrimarykeyOrderby()
        {
            Field[] primarykeys = EntityCache.GetPrimaryKeyFields <T>();

            OrderByOperation temporderBy;

            if (null != primarykeys && primarykeys.Length > 0)
            {
                temporderBy = new OrderByOperation(primarykeys[0]);
            }
            else
            {
                temporderBy = new OrderByOperation(EntityCache.GetFirstField <T>());
            }

            OrderBy(temporderBy);
        }
Example #4
0
        private JsonSerializer GetSerializer(EntityCache cache)
        {
            var settings = new JsonSerializerSettings
            {
                ContractResolver    = fluentContext,
                SerializationBinder = fluentContext,
                TypeNameHandling    = TypeNameHandling.All,
                Converters          =
                {
                    new GqlMaterializer(cache)
                }
            };

            FluentContextExtensions.Apply(fluentContext, settings);

            return(JsonSerializer.Create(settings));
        }
        public override SqlProvider FormatUpdateSelect <T>(Expression <Func <T, T> > updator)
        {
            var update = ResolveExpression.ResolveUpdate(updator);

            var fromTableSql = FormatTableName(false, false);
            var selectSql    = ResolveExpression.ResolveSelectOfUpdate(EntityCache.QueryEntity(typeof(T)), Context.Set.SelectExpression);

            ProviderOption.IsAsName = false;

            var whereSql = ResolveExpression.ResolveWhereList();

            Params.AddDynamicParams(update.Param);

            SqlString = $"UPDATE {fromTableSql} {update.SqlCmd} {selectSql} {whereSql}";

            return(this);
        }
Example #6
0
        protected override void OnFirstRun(TickEventArgs args)
        {
            base.OnFirstRun(args);

            Players    = new EntityCache <CSPlayer>();
            PlayersOld = new EntityCache <CSPlayer>();
            PlayersOld.RequestMissingEntities = false;
            Weapons          = new EntityCache <BaseCombatWeapon>();
            BaseEntitites    = new EntityCache <BaseEntity>();
            pEntityList      = Program.Hack.ClientDll.BaseAddress.ToInt32() + Program.Offsets.EntityList;
            pClientState     = Program.Hack.EngineDll.BaseAddress.ToInt32() + Program.Offsets.ClientState;
            pLocalPlayer     = Program.Hack.ClientDll.BaseAddress.ToInt32() + Program.Offsets.LocalPlayer;
            pViewMatrix      = Program.Hack.ClientDll.BaseAddress.ToInt32() + Program.Offsets.m_mViewMatrix;
            pGameRules       = Program.Hack.ClientDll.BaseAddress.ToInt32() + Program.Offsets.GameRulesProxy;
            pPlayerResources = Program.Hack.ClientDll.BaseAddress.ToInt32() + Program.Offsets.PlayerResources;
            pRadarAddress    = Program.Hack.ClientDll.BaseAddress.ToInt32() + Program.Offsets.RadarBase;
        }
        public void UpdateClosingPrices()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var id    = Guid.NewGuid();
            var stock = new Stock(id);

            stock.List("XYZ", "Existing Stock", new Date(1990, 01, 01), true, AssetCategory.AustralianFixedInterest);

            var stockPriceHistory = new StockPriceHistory(id);

            stock.SetPriceHistory(stockPriceHistory);

            var stockCache = new EntityCache <Stock>();

            stockCache.Add(stock);
            var stockQuery             = new StockQuery(stockCache);
            var stockRepository        = mockRepository.Create <IRepository <Stock> >();
            var stockPriceHistoryCache = new EntityCache <StockPriceHistory>();

            stockPriceHistoryCache.Add(stockPriceHistory);
            var stockPriceHistoryRepository = mockRepository.Create <IRepository <StockPriceHistory> >();

            stockPriceHistoryRepository.Setup(x => x.Update(stockPriceHistory)).Verifiable();

            var service = new StockService(stockQuery, stockCache, stockRepository.Object, stockPriceHistoryCache, stockPriceHistoryRepository.Object);

            var prices = new StockPrice[]
            {
                new StockPrice(new Date(2000, 01, 01), 0.10m),
                new StockPrice(new Date(2000, 01, 02), 0.20m),
                new StockPrice(new Date(2000, 01, 03), 0.30m)
            };
            var result = service.UpdateClosingPrices(id, prices);

            using (new AssertionScope())
            {
                result.Should().HaveOkStatus();

                stock.GetPrice(new Date(2000, 01, 01)).Should().Be(0.10m);
                stock.GetPrice(new Date(2000, 01, 02)).Should().Be(0.20m);
                stock.GetPrice(new Date(2000, 01, 03)).Should().Be(0.30m);
            }

            mockRepository.Verify();
        }
        public int Delete(T model)
        {
            SqlProvider.FormatDelete();
            var entityObject = EntityCache.QueryEntity(model.GetType());
            var identity     = entityObject.EntityFieldList.FirstOrDefault(x => x.IsIdentity);

            if (identity == null)
            {
                throw new System.Exception("主键不存在!");
            }
            //设置参数
            DynamicParameters param = new DynamicParameters();

            param.Add(entityObject.Identitys, identity.PropertyInfo.GetValue(model));
            return(DbCon.Execute($@"{SqlProvider.SqlString} AND {entityObject.Identitys}={SqlProvider.ProviderOption.ParameterPrefix}{entityObject.Identitys}
			"            , param, isExcludeUnitOfWork: SqlProvider.IsExcludeUnitOfWork));
        }
        public override SqlProvider FormatUpdateSelect <T>(Expression <Func <T, T> > updator)
        {
            var update = ResolveExpression.ResolveUpdate(updator);

            var selectSql = ResolveExpression.ResolveSelectOfUpdate(EntityCache.QueryEntity(typeof(T)), Context.Set.SelectExpression);

            var whereSql = string.Empty;

            //表查询条件
            var whereParamsList = ResolveExpression.ResolveWhereList(Context.Set, ref whereSql, Params);

            Params.AddDynamicParams(update.Param);

            SqlString = $"UPDATE {FormatTableName(false, false)} {update.SqlCmd} {selectSql} {whereSql}";

            return(this);
        }
Example #10
0
        /// <summary>
        /// 连表
        /// </summary>
        /// <typeparam name="TWhere">条件表</typeparam>
        /// <typeparam name="TInner">连接表</typeparam>
        /// <param name="rightField">主表关联键</param>
        /// <param name="leftField">外表关联键</param>
        /// <param name="joinMode">连接方式</param>
        /// <returns></returns>
        public IQuerySet <T> Join <TWhere, TInner>(Expression <Func <TWhere, object> > rightField, Expression <Func <TInner, object> > leftField, JoinMode joinMode = JoinMode.LEFT)
        {
            var tWhere = EntityCache.QueryEntity(typeof(TWhere));
            var tInner = EntityCache.QueryEntity(typeof(TInner));

            SqlProvider.JoinList.Add(new JoinAssTable()
            {
                Action       = JoinAction.Default,
                JoinMode     = joinMode,
                RightTabName = tWhere.AsName,
                RightAssName = tWhere.FieldPairs[rightField.GetCorrectPropertyName()],
                LeftTabName  = tInner.AsName,
                LeftAssName  = tInner.FieldPairs[leftField.GetCorrectPropertyName()],
                TableType    = typeof(TInner)
            });
            return(this);
        }
Example #11
0
        public static string GetTableName <TEntity>() where TEntity : class
        {
            var type   = typeof(TEntity);
            var entity = EntityCache.GetEntity(type);

            if (entity == default)
            {
                entity = AnalyzeType(type);
            }

            if (entity.TableName.IsNullOrEmpty())
            {
                throw new InvalidOperationException($"Table name is no set for {type.Name}. Considers using {nameof(TypeAnalyzer)}.{nameof(TypeAnalyzer.AddType)} before using {nameof(TypeAnalyzer)}.{nameof(TypeAnalyzer.GetTableName)}");
            }

            return(entity.TableName);
        }
        static void UpdateCaches(Object entity)
        {
            if (entity.GetType() != typeof(Models.ProfileModels.LearningOpportunityProfile))
            {
                return;
            }
            var         document = (entity as Models.ProfileModels.LearningOpportunityProfile);
            EntityCache ec       = new EntityCache()
            {
                EntityTypeId   = 7,
                EntityType     = "LearningOpportunity",
                EntityStateId  = document.EntityStateId,
                EntityUid      = document.RowId,
                BaseId         = document.Id,
                Description    = document.Description,
                SubjectWebpage = document.SubjectWebpage,
                CTID           = document.CTID,
                Created        = document.Created,
                LastUpdated    = document.LastUpdated,
                //ImageUrl = document.ImageUrl,
                Name           = document.Name,
                OwningAgentUID = document.OwningAgentUid,
                OwningOrgId    = document.OrganizationId
            };

            var statusMessage = "";

            new EntityManager().EntityCacheSave(ec, ref statusMessage);


            new CacheManager().PopulateEntityRelatedCaches(document.RowId);
            //update Elastic
            List <string> messages = new List <string>();

            if (Utilities.UtilityManager.GetAppKeyValue("updatingElasticIndexImmediately", false))
            {
                ElasticHelper.LearningOpp_UpdateIndex(document.Id);
            }
            else
            {
                new SearchPendingReindexManager().Add(7, document.Id, 1, ref messages);
            }

            new SearchPendingReindexManager().Add(CodesManager.ENTITY_TYPE_ORGANIZATION, document.OwningOrganizationId, 1, ref messages);
        }
Example #13
0
        public void TestUpdateCacheSync()
        {
            var cache = new EntityCache <Role>
            {
                Expire = 2
            };

            // 尝试访问
            var list = cache.Entities;

            Assert.Equal(1, cache.Times);

            // 2倍超时后,再次访问走同步更新
            Thread.Sleep(cache.Expire * 1000 * 2 + 100);
            var list3 = cache.Entities;

            Assert.Equal(2, cache.Times);
        }
        public override SqlProvider FormatToList <T>()
        {
            var topNum = DataBaseContext <T>().QuerySet.TopNum;

            var selectSql = ResolveExpression.ResolveSelect(EntityCache.QueryEntity(typeof(T)), Context.Set.SelectExpression, null, Params);

            var fromTableSql = FormatTableName();

            var joinSql = ResolveExpression.ResolveJoinSql(JoinList, ref selectSql, Context.Set.SelectExpression);

            var whereSql = ResolveExpression.ResolveWhereList(Context.Set, Params);

            var orderbySql = ResolveExpression.ResolveOrderBy(Context.Set);

            SqlString = $"{selectSql} {fromTableSql} {joinSql} {whereSql} {orderbySql}";

            return(this);
        }
Example #15
0
        public bool Activate(EntityCache target)
        {
            if (InLimboState || IsActive || ActivateCountThisFrame > 0)
            {
                return(false);
            }

            ActivateCountThisFrame++;

            if (Cache.Instance.LastReloadedTimeStamp != null && Cache.Instance.LastReloadedTimeStamp.ContainsKey(ItemId))
            {
                if (DateTime.UtcNow < Cache.Instance.LastReloadedTimeStamp[ItemId].AddSeconds(Time.Instance.ReloadWeaponDelayBeforeUsable_seconds))
                {
                    if (Settings.Instance.DebugActivateWeapons)
                    {
                        Logging.Log("ModuleCache", "TypeName: [" + _module.TypeName + "] This module is likely still reloading! aborting activating this module.", Logging.Debug);
                    }
                    return(false);
                }
            }

            if (Cache.Instance.LastChangedAmmoTimeStamp != null && Cache.Instance.LastChangedAmmoTimeStamp.ContainsKey(ItemId))
            {
                if (DateTime.UtcNow < Cache.Instance.LastChangedAmmoTimeStamp[ItemId].AddSeconds(Time.Instance.ReloadWeaponDelayBeforeUsable_seconds))
                {
                    if (Settings.Instance.DebugActivateWeapons)
                    {
                        Logging.Log("ModuleCache", "TypeName: [" + _module.TypeName + "] This module is likely still changing ammo! aborting activating this module.", Logging.Debug);
                    }
                    return(false);
                }
            }

            if (!target.IsTarget)
            {
                Logging.Log("Combat", "Target [" + target.Name + "][" + Math.Round(target.Distance / 1000, 2) + "]IsTargeting[" + target.IsTargeting + "] was not locked, aborting activating module as we cant activate a module on something that is not locked!", Logging.Debug);
                return(false);
            }

            _module.Activate(target.Id);
            Cache.Instance.LastActivatedTimeStamp[ItemId] = DateTime.UtcNow;
            Cache.Instance.LastModuleTargetIDs[ItemId]    = target.Id;
            return(true);
        }
Example #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="variable"></param>
        public virtual void RecordVariableUpdate(IVariableInstanceEntity variable)
        {
            if (variable != null && IsHistoryLevelAtLeast(HistoryLevel.ACTIVITY))
            {
                if (!(EntityCache.FindInCache(variable.GetType(), variable.Id) is IHistoricVariableInstanceEntity historicProcessVariable))
                {
                    historicProcessVariable = HistoricVariableInstanceEntityManager.FindHistoricVariableInstanceByVariableInstanceId(variable.Id);
                }

                if (historicProcessVariable != null)
                {
                    HistoricVariableInstanceEntityManager.CopyVariableValue(historicProcessVariable, variable);
                }
                else
                {
                    HistoricVariableInstanceEntityManager.CopyAndInsert(variable);
                }
            }
        }
        /// <summary>
        /// 解析更新语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="Param"></param>
        /// <param name="excludeFields"></param>
        /// <returns></returns>
        public virtual string ResolveUpdates <T>(T t, DynamicParameters Param, string[] excludeFields)
        {
            var           entity     = EntityCache.QueryEntity(t.GetType());
            var           properties = entity.Properties;
            StringBuilder builder    = new StringBuilder();

            foreach (var propertiy in properties)
            {
                //是否是排除字段
                if (excludeFields != null && excludeFields.Contains(propertiy.Name))
                {
                    continue;
                }
                var customAttributes = propertiy.GetCustomAttributess(true);
                //导航属性排除
                if (customAttributes.Any(x => x.GetType().Equals(typeof(ForeignKey))))
                {
                    continue;
                }
                //主键标识
                var typeAttribute = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(Identity)));
                if (typeAttribute != null)
                {
                    var identity = typeAttribute as Identity;
                    //是否自增
                    if (identity.IsIncrease)
                    {
                        continue;
                    }
                }
                object value = propertiy.GetValue(t);
                string name  = entity.FieldPairs[propertiy.Name];
                if (builder.Length != 0)
                {
                    builder.Append(",");
                }
                string paramName = $"{providerOption.ParameterPrefix}Update_{Param.ParameterNames.Count()}";
                builder.Append($"{providerOption.CombineFieldName(name)}={paramName}");
                Param.Add($"{paramName}", value);
            }
            builder.Insert(0, " SET ");
            return(builder.ToString());
        }
Example #18
0
        public void Save(DataObject_Base data, OnConflictOption option, bool cache = true)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (data.IsChanged == false)
            {
                Logger.Log("save skipped because data has no changes", LogCategory.CRUD, LogLevel.Verbose);
                return;
            }

            if (!data.IsPersisted)
            {
                object primaryKey = Insert(data, option: option);

                var dal = data.DAL;
                if (dal != this)
                {
                    data.InternalSetDAL(this);
                }

                if (cache && primaryKey != null)
                {
                    EntityCache cacheStore = GetEntityCache(data.GetType());

                    Debug.Assert(cacheStore.ContainsKey(primaryKey) == false, "Cache already contains entity, existing entity will be replaced");
                    if (cacheStore.ContainsKey(primaryKey))
                    {
                        cacheStore[primaryKey] = data;
                    }
                    else
                    {
                        cacheStore.Add(primaryKey, data);
                    }
                }
            }
            else
            {
                Update(data, option: option);
            }
        }
Example #19
0
        /// <summary>
        /// 执行对象并写入值到对象中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="T1"></typeparam>
        /// <param name="data"></param>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="memberName"></param>
        public static void SetValue <T, T1>(T data, IDbConnection dbCon, string sql, DynamicParameters param, string memberName)
        {
            //执行sql
            var          navigationData = dbCon.Query <T1>(sql, param);
            PropertyInfo property       = EntityCache.QueryEntity(typeof(T)).Properties.FirstOrDefault(x => x.Name.Equals(memberName));

            if (property.PropertyType.FullName.Contains("System.Collections.Generic"))
            {
                property.SetValue(data, navigationData);
            }
            else
            {
                var firstData = navigationData.FirstOrDefault();
                if (firstData != null)
                {
                    property.SetValue(data, firstData);
                }
            }
        }
Example #20
0
        /// <summary>
        /// 查询返回匿名类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="conn"></param>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        private static List <T> QueryRowImpl <T>(IDbConnection conn, SqlProvider provider, IDbTransaction transaction = null)
        {
            List <T> data = default(List <T>);
            Type     type = typeof(T);

            if (type.FullName.Contains("AnonymousType"))//匿名类型
            {
                ConstructorInfo[] constructorInfoArray       = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                ConstructorInfo   noParameterConstructorInfo = constructorInfoArray.FirstOrDefault(x => x.GetParameters().Length == 0);
                data = new List <T>();
                T t = default(T);
                noParameterConstructorInfo = constructorInfoArray.FirstOrDefault();
                using (var reader = conn.ExecuteReader(provider.SqlString, provider.Params, transaction))
                {
                    var properties = EntityCache.QueryEntity(type).Properties;
                    while (reader.Read())
                    {
                        object[] array = new object[properties.Length];
                        for (var i = 0; i < properties.Length; i++)
                        {
                            var item  = properties[i];
                            var value = reader[item.Name];
                            if (value != DBNull.Value)
                            {
                                value = Convert.ChangeType(value, item.PropertyType);
                            }
                            else
                            {
                                value = default;
                            }
                            array[i] = value;
                        }
                        t = (T)noParameterConstructorInfo.Invoke(array);
                        data.Add(t);
                    }
                }
            }
            else
            {
                data = conn.Querys <T>(provider, transaction).ToList();
            }
            return(data);
        }
Example #21
0
        private void HandleTasks()
        {
            //for test
            //Thread.Sleep(10000);

            try
            {
                using (var cache = new EntityCache <AutoTask, CHCContext>(p => p.AutoTaskStatus.Name == "开始" || p.AutoTaskStatus.Name == "停止"))
                {
                    LogManager.Instance.Write("Start ---------------------------------------------------------------------------------------------");

                    while (true)
                    {
                        var count = cache.Results.Count();
                        LogManager.Instance.Write(count.ToString());

                        var startList = cache.Results.Where(e => e.AutoTaskStatus.Name == "开始").ToList();
                        if (startList.Count > 0)
                        {
                            foreach (var task in startList)
                            {
                                AutoTaskHandlerManager.Instance.StartAutoTask(task);
                            }
                        }

                        var stopList = cache.Results.Where(e => e.AutoTaskStatus.Name == "停止").ToList();
                        if (stopList.Count > 0)
                        {
                            foreach (var task in stopList)
                            {
                                AutoTaskHandlerManager.Instance.StartAutoTask(task);
                            }
                        }

                        Thread.Sleep(5000);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance.Write(ex.ToString());
            }
        }
        private bool CalExpressionValue(SysTransition tran)
        {
            SysExpression expr;
            bool          flag = true;

            if ((tran.Expressions != null) && (tran.Expressions.Count != 0))
            {
                if (!tran.ExpressionId.HasValue)
                {
                    return(flag);
                }
                expr = tran.Expressions.FirstOrDefault <SysExpression>(e => e.ExpressionId == tran.ExpressionId.Value);
                if (expr == null)
                {
                    throw new ApplicationException("指定的入口表达式不在连接线的表达式中");
                }
                Queue <SysExpression> calOrder = ExpressionHelper.GetCalOrder(tran.Expressions.ToList <SysExpression>());
                if (calOrder.Count <SysExpression>(p => (p.ExpressionId == expr.ExpressionId)) <= 0)
                {
                    throw new ApplicationException("无法计算表达式的值");
                }
                EntityCache     cache  = new EntityCache(base.Manager);
                ExpressionCache cache2 = new ExpressionCache();
                while (calOrder.Count > 0)
                {
                    SysExpression expression = calOrder.Dequeue();
                    object        obj2       = ExpressionHelper.GetHelper(expression).GetValue(expression, cache, cache2, base.PI, this.AI);
                    if (expression.ExpressionId == expr.ExpressionId)
                    {
                        if (obj2 == null)
                        {
                            throw new ApplicationException("表达式的值返回null");
                        }
                        if (obj2.GetType() != typeof(bool))
                        {
                            throw new ApplicationException("入口条件表达式的值不是布尔类型");
                        }
                        return((bool)obj2);
                    }
                }
            }
            return(flag);
        }
        public List <EntityCache> PrepareEntityCacheModel(EntityCollection entityCacheCollection)
        {
            if (entityCacheCollection == null)
            {
                return(null);
            }
            var entityCacheModelList = new List <EntityCache>();

            for (int i = 0; i < entityCacheCollection.Entities.Count; i++)
            {
                var entityCache      = entityCacheCollection.Entities[i];
                var entityCacheModel = new EntityCache();

                entityCacheModel.Id = entityCache.Id;
                if (EntityHelper.HasAttributeNotNull(entityCache, Attributes.EntityCache.Name))
                {
                    entityCacheModel.Name = entityCache.Attributes[Attributes.EntityCache.Name].ToString();
                }

                if (EntityHelper.HasAttributeNotNull(entityCache, Attributes.EntityCache.SourceMarket))
                {
                    entityCacheModel.SourceMarket = entityCache.Attributes[Attributes.EntityCache.SourceMarket].ToString();
                }

                if (EntityHelper.HasAttributeNotNull(entityCache, Attributes.EntityCache.Type))
                {
                    entityCacheModel.Type = entityCache.Attributes[Attributes.EntityCache.Type].ToString();
                }

                if (EntityHelper.HasAttributeNotNull(entityCache, Attributes.EntityCache.RecordId))
                {
                    entityCacheModel.RecordId = entityCache.Attributes[Attributes.EntityCache.RecordId].ToString();
                }

                if (EntityHelper.HasAttributeNotNull(entityCache, Attributes.EntityCache.Operation))
                {
                    entityCacheModel.Operation = ((int?)entityCache.Attributes[Attributes.EntityCache.Operation]).Value;
                }

                entityCacheModelList.Add(entityCacheModel);
            }
            return(entityCacheModelList);
        }
Example #24
0
        /// <summary>
        ///   Activate salvagers on targeted wreck
        /// </summary>
        private void ActivateSalvagers()
        {
            // We are not in space yet, wait...
            if (!Cache.Instance.InSpace)
            {
                return;
            }

            List <ModuleCache> salvagers = Cache.Instance.Modules.Where(m => Salvagers.Contains(m.TypeId)).ToList();

            if (salvagers.Count == 0)
            {
                return;
            }

            double salvagerRange = salvagers.Min(s => s.OptimalRange);

            List <EntityCache> wrecks = Cache.Instance.Targets.Where(t => t.GroupId == (int)Group.Wreck && t.Distance < salvagerRange).ToList();

            if (wrecks.Count == 0)
            {
                return;
            }

            foreach (ModuleCache salvager in salvagers)
            {
                if (salvager.IsActive || salvager.IsDeactivating)
                {
                    continue;
                }

                // Spread the salvagers around
                EntityCache wreck = wrecks.OrderBy(w => salvagers.Count(s => s.LastTargetId == w.Id)).FirstOrDefault();
                if (wreck == null)
                {
                    return;
                }

                Logging.Log("Salvage", "Activating salvager [" + salvager.ItemId + "] on [" + wreck.Name + "][ID: " + Cache.Instance.MaskedID(wreck.Id) + "]", Logging.White);
                salvager.Activate(wreck);
            }
        }
        /// <summary>
        /// 解析连表查询
        /// </summary>
        /// <param name="joinAssTables"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public virtual string ResolveJoinSql(List <JoinAssTable> joinAssTables, ref string sql)
        {
            StringBuilder builder = new StringBuilder(Environment.NewLine);

            if (joinAssTables.Count != 0)
            {
                sql = sql.TrimEnd();
                //循环拼接连表对象
                for (int i = 0; i < joinAssTables.Count; i++)
                {
                    //当前连表对象
                    var item = joinAssTables[i];
                    if (item.IsMapperField == false)
                    {
                        continue;
                    }
                    item.MapperList.Clear();
                    //连表实体
                    var leftEntity = EntityCache.QueryEntity(item.TableType);
                    //默认连表
                    if (item.Action == JoinAction.Default || item.Action == JoinAction.Navigation)
                    {
                        string leftTable = providerOption.CombineFieldName(item.LeftTabName);
                        builder.Append($@" {item.JoinMode.ToString()} JOIN 
                                       {leftTable} {leftEntity.AsName} ON {leftEntity.AsName}
                                      .{providerOption.CombineFieldName(item.LeftAssName)} = {providerOption.CombineFieldName(item.RightTabName)}
                                      .{providerOption.CombineFieldName(item.RightAssName)} " + Environment.NewLine);
                    }
                    else                    //sql连表
                    {
                        builder.Append(" " + item.JoinSql);
                        //判断是否需要显示连表的字段
                        if (!item.IsMapperField)
                        {
                            continue;
                        }
                    }
                    FieldDetailWith(ref sql, item, leftEntity);
                }
            }
            return(builder.ToString());
        }
        public void ChangeStockInvalidId()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var id = Guid.NewGuid();

            var stockCache                  = new EntityCache <Stock>();
            var stockQuery                  = new StockQuery(stockCache);
            var stockRepository             = mockRepository.Create <IRepository <Stock> >();
            var stockPriceHistoryCache      = mockRepository.Create <IEntityCache <StockPriceHistory> >();
            var stockPriceHistoryRepository = mockRepository.Create <IRepository <StockPriceHistory> >();

            var service = new StockService(stockQuery, stockCache, stockRepository.Object, stockPriceHistoryCache.Object, stockPriceHistoryRepository.Object);

            var result = service.ChangeStock(id, new Date(2000, 01, 01), "ABC", "ABC Pty Ltd", AssetCategory.AustralianFixedInterest);

            result.Should().HaveNotFoundStatus();

            mockRepository.Verify();
        }
        public override SqlProvider FormatGet <T>()
        {
            var selectSql = ResolveExpression.ResolveSelect(EntityCache.QueryEntity(typeof(T)), Context.Set.SelectExpression, 1, Params);

            var fromTableSql = FormatTableName();

            var nolockSql = ResolveExpression.ResolveWithNoLock(Context.Set.NoLock);

            var joinSql = ResolveExpression.ResolveJoinSql(JoinList, ref selectSql, Context.Set.SelectExpression);

            var whereSql = ResolveExpression.ResolveWhereList(Context.Set, Params);

            var groupSql = ResolveExpression.ResolveGroupBy(Context.Set, "Group");

            var orderbySql = ResolveExpression.ResolveOrderBy(Context.Set);

            SqlString = $"{selectSql} {fromTableSql} {nolockSql} {joinSql} {whereSql} {groupSql} {orderbySql}";

            return(this);
        }
        public void UpdateClosingPricesInvalidId()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var id = Guid.NewGuid();

            var stockCache                  = new EntityCache <Stock>();
            var stockQuery                  = new StockQuery(stockCache);
            var stockRepository             = mockRepository.Create <IRepository <Stock> >();
            var stockPriceHistoryCache      = mockRepository.Create <IEntityCache <StockPriceHistory> >();
            var stockPriceHistoryRepository = mockRepository.Create <IRepository <StockPriceHistory> >();

            var service = new StockService(stockQuery, stockCache, stockRepository.Object, stockPriceHistoryCache.Object, stockPriceHistoryRepository.Object);

            var result = service.UpdateClosingPrices(id, new StockPrice[] { });

            result.Should().HaveNotFoundStatus();

            mockRepository.Verify();
        }
        public void ChangeDividendRulesInvalidId()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var id = Guid.NewGuid();

            var stockCache                  = new EntityCache <Stock>();
            var stockQuery                  = new StockQuery(stockCache);
            var stockRepository             = mockRepository.Create <IRepository <Stock> >();
            var stockPriceHistoryCache      = mockRepository.Create <IEntityCache <StockPriceHistory> >();
            var stockPriceHistoryRepository = mockRepository.Create <IRepository <StockPriceHistory> >();

            var service = new StockService(stockQuery, stockCache, stockRepository.Object, stockPriceHistoryCache.Object, stockPriceHistoryRepository.Object);

            var result = service.ChangeDividendRules(id, new Date(2000, 01, 01), 0.30m, RoundingRule.Round, true, DrpMethod.Round);

            result.Should().HaveNotFoundStatus();

            mockRepository.Verify();
        }
Example #30
0
        /// <summary>
        /// 获取用户对实体的权限
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public EntityPrivilegeResponse GetPrivilege()
        {
            var sql       = @"
SELECT * FROM sys_role_privilege
WHERE sys_roleid = @id and object_type = 'sys_entity'
and objectid = @entityid";
            var user      = Broker.Retrieve <user_info>(UserIdentityUtil.GetCurrentUserId());
            var paramList = new Dictionary <string, object>()
            {
                { "@id", user.roleid }, { "@entityid", EntityCache.GetEntity(new T().EntityName)?.Id }
            };
            var data = Broker.Retrieve <sys_role_privilege>(sql, paramList);

            return(new EntityPrivilegeResponse()
            {
                read = data.privilege >= 1,
                create = data.privilege >= 3,
                delete = data.privilege >= 7
            });
        }
Example #31
0
        public void Test1()
        {
            try
            {
                using (var cache = new EntityCache <CompanyOrder, CHCContext>(p => p.Locked == true))
                {
                    logHelper.WriteLogFile(logFilePath, string.Format("{0}:{1}", DateTime.Now.ToString(), "Start---------------------------------------------------------------------------------------------"));

                    while (true)
                    {
                        logHelper.WriteLogFile(logFilePath, string.Format("{0}:{1}", DateTime.Now.ToString(), cache.Results.Count().ToString()));
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception ex)
            {
                logHelper.WriteLogFile(logFilePath, string.Format("{0}:{1}", DateTime.Now.ToString(), ex.ToString()));
            }
        }
Example #32
0
        public void TestAddRemove()
        {
            var cache = new EntityCache <Role>
            {
                Expire = 2
            };

            var list = cache.Entities;

            var role = new Role {
                Name = "test"
            };

            // 添加实体对象
            cache.Add(role);
            var list2 = cache.Entities;

            Assert.NotEqual(list, list2);
            Assert.Equal(list.Count + 1, list2.Count);

            // 删除实体对象,来自内部
            cache.Remove(role);
            var list3 = cache.Entities;

            Assert.True(list != list3);
            Assert.True(list2 != list3);
            Assert.Equal(list.Count, list3.Count);

            // 删除实体对象,来自外部
            cache.Add(role);
            var role2 = new Role {
                Name = "test"
            };

            cache.Remove(role2);
            var list4 = cache.Entities;

            Assert.True(list != list4);
            Assert.True(list2 != list4);
            Assert.Equal(list.Count, list4.Count);
        }
        internal static bool PerformFinalDestinationTask(EveCom.Bookmark bookmark, int warpDistance)
        {
            // The bookmark no longer exists, assume we are not there
            if (bookmark == null)
                return false;

            // Is this a station bookmark?
            if ((int)bookmark.GroupID == (int)Group.Station)
            {
                if (QuestorCache.Instance.InSpace && !QuestorCache.Instance.InStation)
                {
                    if (Logging.DebugTraveler) Logging.Log("TravelerDestination.BookmarkDestination", "bookmark info title: [" + Logging.Yellow + bookmark.Title + Logging.Green + "]", Logging.Green);
                    if (Logging.DebugTraveler) Logging.Log("TravelerDestination.BookmarkDestination", "bookmark info locationID: [" + Logging.Yellow + bookmark.LocationID + Logging.Green + "]", Logging.Green);
                    if (Logging.DebugTraveler) Logging.Log("TravelerDestination.BookmarkDestination", "bookmark info id: [" + Logging.Yellow + bookmark.ID + Logging.Green + "]", Logging.Green);
                    if (Logging.DebugTraveler) Logging.Log("TravelerDestination.BookmarkDestination", "bookmark info distance: [" + Logging.Yellow + bookmark.Distance + Logging.Green + "]", Logging.Green);
                    int stationNum = 0;
                    if (Logging.DebugTraveler) Logging.Log("TravelerDestination.BookmarkDestination", "---------------------------------", Logging.Green);

                    foreach (EntityCache station in QuestorCache.Instance.Stations)
                    {
                        stationNum++;
                        if (Logging.DebugTraveler) Logging.Log("TravelerDestination.BookmarkDestination", "[" + stationNum + "] Station Name [" + Logging.Yellow + station.Name + Logging.Green + "]", Logging.Green);
                        if (Logging.DebugTraveler) Logging.Log("TravelerDestination.BookmarkDestination", "[" + stationNum + "] Station Distance [" + Logging.Yellow + station.Distance + Logging.Green + "]", Logging.Green);
                        if (Logging.DebugTraveler) Logging.Log("TravelerDestination.BookmarkDestination", "[" + stationNum + "] Station ID [" + Logging.Yellow + station.EveComEntity.ID + Logging.Green + "]", Logging.Green);
                        if (station.Distance == bookmark.Distance)
                        {
                            ThisStation = station;
                        }
                    }

                    if (Logging.DebugTraveler) Logging.Log("TravelerDestination.BookmarkDestination", "---------------------------------", Logging.Green);
                }

                if (ThisStation == null)
                {
                    Logging.DebugTraveler = true;
                    Logging.Log("TravelerDestination.BookmarkDestination", "Station missing... bookmark distance doesnt match any of the stations in local", Logging.Debug);
                    return false;
                }

                bool arrived = StationDestination.PerformFinalDestinationTask(ThisStation.Id);
                if (arrived)
                {
                    Logging.Log("TravelerDestination.BookmarkDestination", "Arrived at bookmark [" + Logging.Yellow + bookmark.Title + Logging.Green + "]", Logging.Green);
                }

                return arrived;
            }

            if (QuestorCache.Instance.InStation)
            {
                // We have arrived
                if (bookmark.ItemID == EveCom.Session.StationID)
                    return true;

                // We are in a station, but not the correct station!
                if (DateTime.UtcNow > Time.Instance.NextUndockAction)
                {
                    TravelerDestination.Undock();
                    return false;
                }

                return false;
            }

            if (!QuestorCache.Instance.InSpace)
            {
                // We are not in space and not in a station, wait a bit
                return false;
            }

            if (_nextTravelerDestinationAction > DateTime.UtcNow)
                return false;

            _undockAttempts = 0;

            if (!UseInstaBookmark()) return false;

            // This bookmark has no x / y / z, assume we are there.
            //if (bookmark.X = -1 || bookmark.Y == -1 || bookmark.Z == -1)
            //{
            //    Logging.Log("TravelerDestination.BookmarkDestination", "Arrived at the bookmark [" + Logging.Yellow + bookmark.Title + Logging.Green + "][No XYZ]", Logging.Green);
            //    return true;
            //}

            if (bookmark.Distance < warpDistance)
            {
                Logging.Log("TravelerDestination.BookmarkDestination", "Arrived at the bookmark [" + Logging.Yellow + bookmark.Title + Logging.Green + "]", Logging.Green);
                return true;
            }

            if (_nextTravelerDestinationAction > DateTime.UtcNow)
                return false;

            if (Math.Round((bookmark.Distance / 1000)) < (int)Distances.MaxPocketsDistanceKm && QuestorCache.Instance.AccelerationGates.Count() != 0)
            {
                Logging.Log("TravelerDestination.BookmarkDestination", "Warp to bookmark in same pocket requested but acceleration gate found delaying.", Logging.White);
                return true;
            }

            Defense.DoNotBreakInvul = false;
            string nameOfBookmark = "";
            if (QuestorSettings.Instance.EveServerName == "Tranquility") nameOfBookmark = "Encounter";
            if (QuestorSettings.Instance.EveServerName == "Serenity") nameOfBookmark = "遭遇战";
            if (nameOfBookmark == "") nameOfBookmark = "Encounter";
            //if (!Combat.ReloadAll(Cache.Instance.EntitiesNotSelf.OrderBy(t => t.Distance).FirstOrDefault(t => t.Distance < (double)Distance.OnGridWithMe))) return false;
            if (MissionSettings.MissionWarpAtDistanceRange != 0 && bookmark.Title.Contains(nameOfBookmark))
            {
                if (DateTime.UtcNow > Time.Instance.NextWarpAction && EveCom.MyShip.Mode != EveCom.EntityMode.Warping)
                {
                    bookmark.WarpTo(MissionSettings.MissionWarpAtDistanceRange * 1000);
                }

                if (EveCom.MyShip.Mode == EveCom.EntityMode.Warping)
                {
                    Logging.Log("TravelerDestination.BookmarkDestination", "Warping to bookmark [" + Logging.Yellow + bookmark.Title + Logging.Green + "][" + Logging.Yellow + " At " + MissionSettings.MissionWarpAtDistanceRange + Logging.Green + " km]", Logging.Green);
                    Time.Instance.NextWarpAction = DateTime.UtcNow.AddSeconds(5);
                    return true;
                }
            }
            else
            {
                if (DateTime.UtcNow > Time.Instance.NextWarpAction && EveCom.MyShip.Mode != EveCom.EntityMode.Warping)
                {
                    bookmark.WarpTo();
                }

                if (EveCom.MyShip.Mode == EveCom.EntityMode.Warping)
                {
                    Logging.Log("TravelerDestination.BookmarkDestination", "Warping to bookmark [" + Logging.Yellow + bookmark.Title + Logging.Green + "][" + Logging.Yellow + Math.Round((bookmark.Distance / 1000) / 149598000, 2) + Logging.Green + " AU away]", Logging.Green);
                    Time.Instance.NextWarpAction = DateTime.UtcNow.AddSeconds(5);
                    return true;
                }
            }

            return false;
        }
Example #34
0
        //this needs to accept a distance parameter....
        public static void NavigateToObject(EntityCache target, string module)
        {
            if (Settings.Instance.SpeedTank)
            {   //this should be only executed when no specific actions
                if (DateTime.Now > Cache.Instance.NextOrbit)
                {
                    if (target.Distance + (int)Cache.Instance.OrbitDistance < Cache.Instance.MaxRange)
                    {
                        Logging.Log(module, "StartOrbiting: Target in range", Logging.teal);
                        if (!Cache.Instance.IsApproachingOrOrbiting)
                        {
                            Logging.Log("CombatMissionCtrl.NavigateToObject", "We are not approaching nor orbiting", Logging.teal);
                            const bool orbitStructure = true;
                            var structure = Cache.Instance.Entities.Where(i => i.GroupId == (int)Group.LargeCollidableStructure || i.Name.Contains("Gate") || i.Name.Contains("Beacon")).OrderBy(t => t.Distance).OrderBy(t => t.Distance).FirstOrDefault();

                            if (orbitStructure && structure != null)
                            {
                                structure.Orbit((int)Cache.Instance.OrbitDistance);
                                Logging.Log(module, "Initiating Orbit [" + structure.Name + "][ID: " + structure.Id + "]", Logging.teal);
                            }
                            else
                            {
                                target.Orbit(Cache.Instance.OrbitDistance);
                                Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + target.Id + "]", Logging.teal);
                            }
                            return;
                        }
                    }
                    else
                    {
                        Logging.Log(module, "Possible out of range. ignoring orbit around structure", Logging.teal);
                        target.Orbit(Cache.Instance.OrbitDistance);
                        Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + target.Id + "]", Logging.teal);
                        return;
                    }
                }
            }
            else //if we aren't speed tanking then check optimalrange setting, if that isn't set use the less of targeting range and weapons range to dictate engagement range
            {
                if (DateTime.Now > Cache.Instance.NextApproachAction)
                {
                    //if optimalrange is set - use it to determine engagement range
                    //
                    // this assumes that both optimal range and missile boats both want to be within 5k of the object they asked us to navigate to
                    //
                    if (target.Distance > Cache.Instance.MaxRange && (Cache.Instance.Approaching == null || Cache.Instance.Approaching.Id != target.Id))
                    {
                        target.Approach((int)(Distance.SafeDistancefromStructure));
                        Logging.Log(module, "Using SafeDistanceFromStructure: Approaching target [" + target.Name + "][ID: " + target.Id + "][" + Math.Round(target.Distance / 1000, 0) + "k away]", Logging.teal);
                    }
                    return;
                }
            }
        }
Example #35
0
        public static void OrbitGateorTarget(EntityCache target, string module)
        {
            if (DateTime.Now > Cache.Instance.NextOrbit)
            {
                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "OrbitGateorTarget Started", Logging.white);
                if (Cache.Instance.OrbitDistance == 0)
                {
                    Cache.Instance.OrbitDistance = 2000;
                }

                if (target.Distance + (int)Cache.Instance.OrbitDistance < Cache.Instance.MaxRange)
                {
                    if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "OrbitGateorTarget Started", Logging.white);
                    //Logging.Log("CombatMissionCtrl." + _pocketActions[_currentAction] ,"StartOrbiting: Target in range");
                    if (!Cache.Instance.IsApproachingOrOrbiting)
                    {
                        Logging.Log("CombatMissionCtrl.NavigateIntoRange", "We are not approaching nor orbiting", Logging.teal);

                        EntityCache structure = Cache.Instance.Entities.Where(i => i.Name.Contains("Gate")).OrderBy(t => t.Distance).OrderBy(t => t.Distance).FirstOrDefault();

                        if (Settings.Instance.OrbitStructure && structure != null)
                        {
                            structure.Orbit((int)Cache.Instance.OrbitDistance);
                            Logging.Log(module, "Initiating Orbit [" + structure.Name + "][ID: " + structure.Id + "]", Logging.teal);
                        }
                        else
                        {
                            target.Orbit(Cache.Instance.OrbitDistance);
                            Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + target.Id + "]", Logging.teal);
                        }
                        return;
                    }
                }
                else
                {
                    Logging.Log(module, "Possible out of range. ignoring orbit around structure", Logging.teal);
                    target.Orbit(Cache.Instance.OrbitDistance);
                    Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + target.Id + "]", Logging.teal);
                    Cache.Instance.NextOrbit = DateTime.Now.AddSeconds(Time.Instance.OrbitDelay_seconds);
                    return;
                }
                return;
            }
        }
Example #36
0
 public void ClearCache()
 {
     _entity = null;
 }
Example #37
0
        //this needs to accept a distance parameter....
        public static void NavigateToObject(EntityCache target, string module)
        {
            if (Settings.Instance.SpeedTank)
            {   //this should be only executed when no specific actions
                if (DateTime.UtcNow > Cache.Instance.NextOrbit)
                {
                    if (target.Distance + Cache.Instance.OrbitDistance < Cache.Instance.MaxRange)
                    {
                        //we cant move in bastion mode, do not try
                        List<ModuleCache> bastionModules = null;
                        bastionModules = Cache.Instance.Modules.Where(m => m.GroupId == (int)Group.Bastion && m.IsOnline).ToList();
                        if (bastionModules.Any(i => i.IsActive)) return;

                        Logging.Log(module, "StartOrbiting: Target in range", Logging.Teal);
                        if (!Cache.Instance.IsApproachingOrOrbiting(target.Id))
                        {
                            Logging.Log("CombatMissionCtrl.NavigateToObject", "We are not approaching nor orbiting", Logging.Teal);
                            bool orbitStructure = Settings.Instance.OrbitStructure;
                            EntityCache structure = Cache.Instance.EntitiesOnGrid.Where(i => i.IsLargeCollidable || i.Name.Contains("Gate") || i.Name.Contains("Beacon")).OrderBy(t => t.Distance).ThenBy(t => t.Distance).FirstOrDefault();

                            if (orbitStructure && structure != null)
                            {
                                structure.Orbit(Cache.Instance.OrbitDistance);
                                Logging.Log(module, "Initiating Orbit [" + structure.Name + "][ID: " + Cache.Instance.MaskedID(structure.Id) + "]", Logging.Teal);
                            }
                            else
                            {
                                target.Orbit(Cache.Instance.OrbitDistance);
                                Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "]", Logging.Teal);
                            }
                            return;
                        }
                    }
                    else
                    {
                        Logging.Log(module, "Possible out of range. ignoring orbit around structure", Logging.Teal);
                        target.Orbit(Cache.Instance.OrbitDistance);
                        Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "]", Logging.Teal);
                        return;
                    }
                }
            }
            else //if we are not speed tanking then check optimalrange setting, if that is not set use the less of targeting range and weapons range to dictate engagement range
            {
                if (DateTime.UtcNow > Cache.Instance.NextApproachAction)
                {
                    //if optimalrange is set - use it to determine engagement range
                    //
                    // this assumes that both optimal range and missile boats both want to be within 5k of the object they asked us to navigate to
                    //
                    if (target.Distance > Cache.Instance.MaxRange)
                    {
                        if (Cache.Instance.Approaching == null || Cache.Instance.Approaching.Id != target.Id || Cache.Instance.MyShipEntity.Velocity < 50)
                        {
                            if (target.KeepAtRange((int) (Distances.SafeDistancefromStructure)))
                            {
                                Logging.Log(module, "Using SafeDistanceFromStructure: Approaching target [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "][" + Math.Round(target.Distance / 1000, 0) + "k away]", Logging.Teal);
                            }
                        }
                    }

                    return;
                }
            }
        }
Example #38
0
        public static void OrbitGateorTarget(EntityCache target, string module)
        {
            if (DateTime.UtcNow > Cache.Instance.NextOrbit)
            {
                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "OrbitGateorTarget Started", Logging.White);
                if (Cache.Instance.OrbitDistance == 0)
                {
                    Cache.Instance.OrbitDistance = 2000;
                }

                if (target.Distance + Cache.Instance.OrbitDistance < Cache.Instance.MaxRange - 5000)
                {
                    if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "if (target.Distance + Cache.Instance.OrbitDistance < Cache.Instance.MaxRange - 5000)", Logging.White);
                    //Logging.Log("CombatMissionCtrl." + _pocketActions[_currentAction] ,"StartOrbiting: Target in range");
                    if (!Cache.Instance.IsApproachingOrOrbiting)
                    {
                        if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("CombatMissionCtrl.NavigateIntoRange", "We are not approaching nor orbiting", Logging.Teal);

                        //
                        // Prefer to orbit the last structure defined in
                        // Cache.Instance.OrbitEntityNamed
                        //
                        EntityCache structure = null;
                        if (!string.IsNullOrEmpty(Cache.Instance.OrbitEntityNamed))
                        {
                            structure = Cache.Instance.Entities.Where(i => i.Name.Contains(Cache.Instance.OrbitEntityNamed)).OrderBy(t => t.Distance).FirstOrDefault();
                        }

                        if (structure == null)
                        {
                            structure = Cache.Instance.Entities.Where(i => i.Name.Contains("Gate")).OrderBy(t => t.Distance).FirstOrDefault();
                        }

                        if (Settings.Instance.OrbitStructure && structure != null)
                        {
                            structure.Orbit(Cache.Instance.OrbitDistance);
                            Logging.Log(module, "Initiating Orbit [" + structure.Name + "][ID: " + Cache.Instance.MaskedID(structure.Id) + "]", Logging.Teal);
                            return;
                        }

                        //
                        // OrbitStructure is false
                        //
                        if (Settings.Instance.SpeedTank)
                        {
                            target.Orbit(Cache.Instance.OrbitDistance);
                            Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "]", Logging.Teal);
                            return;
                        }

                        //
                        // OrbitStructure is false
                        // Speedtank is false
                        //
                        if (Cache.Instance.MyShip.Velocity < 300) //this will spam a bit until we know what "mode" our activeship is when aligning
                        {
                            if (Settings.Instance.WeaponGroupId == (int)Group.HybridWeapon ||
                                Settings.Instance.WeaponGroupId == (int)Group.ProjectileWeapon)
                            {
                                if (DateTime.UtcNow > Cache.Instance.NextAlign)
                                {
                                    Cache.Instance.Star.AlignTo();
                                    Logging.Log(module, "Aligning to the Star so we might possibly hit [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "][ActiveShip.Entity.Mode:[" + Cache.Instance.DirectEve.ActiveShip.Entity.Mode + "]", Logging.Teal);
                                    return;
                                }
                            }

                            target.Orbit(Cache.Instance.OrbitDistance);
                            Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "]", Logging.Teal);
                            return;
                        }

                        target.Orbit(Cache.Instance.OrbitDistance);
                        Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "]", Logging.Teal);
                        return;
                    }
                }
                else
                {
                    Logging.Log(module, "Out of range. ignoring orbit around structure.", Logging.Teal);
                    target.Orbit(Cache.Instance.OrbitDistance);
                    Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "]", Logging.Teal);
                    Cache.Instance.NextOrbit = DateTime.UtcNow.AddSeconds(90);
                    return;
                }
                return;
            }
        }
Example #39
0
 public LanguagesValues(EntityCache<Language> languages)
 {
     _languages = languages;
 }
Example #40
0
        internal MultithreadedSystem(MultithreadedSystemSharedContext sharedData, ISystem system) {
            System = system;
            _shared = sharedData;

            PerformanceData = new PerformanceInformation(system);

            ITriggerFilterProvider trigger = system as ITriggerFilterProvider;
            if (trigger != null) {
                _filter = new Filter(DataAccessorFactory.MapTypesToDataAccessors(trigger.RequiredDataTypes));
                _entityCache = new EntityCache(_filter);

                // all of these triggers require a filter
                _triggerAdded = trigger as Trigger.Added;
                _triggerRemoved = trigger as Trigger.Removed;
                _triggerModified = trigger as Trigger.Modified;
                _triggerUpdate = trigger as Trigger.Update;
                _triggerInput = trigger as Trigger.Input;
            }

            // these triggers don't require a filter
            _triggerGlobalPreUpdate = system as Trigger.GlobalPreUpdate;
            _triggerGlobalPostUpdate = system as Trigger.GlobalPostUpdate;
            _triggerGlobalInput = system as Trigger.GlobalInput;
        }
Example #41
0
 public void Initialize(string userLocal, string userRegion, MundoMvc4BaseEntities entitiesSource)
 {
     _entitiesSource = entitiesSource;
     _regionsCache = DataProviderFactory.GetRegions(userLocal);
     _languagesCache = DataProviderFactory.GetLanguages(userLocal);
 }
Example #42
0
        public static EntityCache FindDronePriorityTarget(EntityCache currentTarget, DronePriority priorityType, bool AddECMTypeToDronePriorityTargetList, double Distance, bool FindAUnTargetedEntity = true)
        {
            if (AddECMTypeToDronePriorityTargetList)
            {
                //if (Logging.DebugGetBestTarget) Logging.Log(callingroutine + " Debug: GetBestTarget", "Checking for Neutralizing priority targets (currentTarget first)", Logging.Teal);
                // Choose any Neutralizing primary weapon priority targets
                try
                {
                    EntityCache target = null;
                    try
                    {
                        if (DronePriorityEntities.Any(pt => pt.DronePriorityLevel == priorityType))
                        {
                            target = DronePriorityEntities.Where(pt => ((FindAUnTargetedEntity || pt.IsReadyToShoot) && currentTarget != null && pt.Id == currentTarget.Id && (pt.Distance < Distance) && pt.IsActiveDroneEwarType == priorityType)
                                                                                                || ((FindAUnTargetedEntity || pt.IsReadyToShoot) && pt.Distance < Distance && pt.IsActiveDroneEwarType == priorityType))
                                                                                                       .OrderByDescending(pt => pt.IsNpcFrigate)
                                                                                                       .ThenByDescending(pt => pt.IsLastTargetDronesWereShooting)
                                                                                                       .ThenByDescending(pt => pt.IsInDroneRange)
                                                                                                       .ThenBy(pt => pt.IsEntityIShouldKeepShootingWithDrones)
                                                                                                       .ThenBy(pt => (pt.ShieldPct + pt.ArmorPct + pt.StructurePct))
                                                                                                       .ThenBy(pt => pt.Nearest5KDistance)
                                                                                                       .FirstOrDefault();
                        }
                    }
                    catch (NullReferenceException) { }  // Not sure why this happens, but seems to be no problem

                    if (target != null)
                    {
                        //if (Logging.DebugGetBestTarget) Logging.Log(callingroutine + " Debug: GetBestTarget", "NeutralizingPrimaryWeaponPriorityTarget [" + NeutralizingPriorityTarget.Name + "][" + Math.Round(NeutralizingPriorityTarget.Distance / 1000, 2) + "k][" + Cache.Instance.MaskedID(NeutralizingPriorityTarget.Id) + "] GroupID [" + NeutralizingPriorityTarget.GroupId + "]", Logging.Debug);

                        if (!FindAUnTargetedEntity)
                        {
                            Drones.PreferredDroneTarget = target;
                            Time.Instance.LastPreferredDroneTargetDateTime = DateTime.UtcNow;
                            return target;
                        }

                        return target;
                    }

                    return null;
                }
                catch (NullReferenceException) { }

                return null;
            }

            return null;
        }
Example #43
0
        public static void NavigateIntoRange(EntityCache target, string module)
        {
            if (Cache.Instance.InWarp || Cache.Instance.InStation)
                return;

            if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange Started", Logging.white);

            if (Cache.Instance.OrbitDistance != Settings.Instance.OrbitDistance)
            {
                if (Cache.Instance.OrbitDistance == 0)
                {
                    Cache.Instance.OrbitDistance = Settings.Instance.OrbitDistance;
                    Logging.Log("CombatMissionCtrl", "Using default orbit distance: " + Cache.Instance.OrbitDistance + " (as the custom one was 0)", Logging.teal);
                }
                //else
                //    Logging.Log("CombatMissionCtrl", "Using custom orbit distance: " + Cache.Instance.OrbitDistance, Logging.teal);
            }
            //if (Cache.Instance.OrbitDistance != 0)
            //    Logging.Log("CombatMissionCtrl", "Orbit Distance is set to: " + (Cache.Instance.OrbitDistance / 1000).ToString(CultureInfo.InvariantCulture) + "k", Logging.teal);

            NavigateOnGrid.AvoidBumpingThings(Cache.Instance.BigObjectsandGates.FirstOrDefault(), "NavigateOnGrid: NavigateIntoRange");

            if (Settings.Instance.SpeedTank)
            {
                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: speedtank: orbitdistance is [" + Cache.Instance.OrbitDistance + "]", Logging.white);
                OrbitGateorTarget(target, module);
            }
            else //if we aren't speed tanking then check optimalrange setting, if that isn't set use the less of targeting range and weapons range to dictate engagement range
            {
                if (DateTime.Now > Cache.Instance.NextApproachAction)
                {
                    //if optimalrange is set - use it to determine engagement range
                    if (Settings.Instance.OptimalRange != 0)
                    {
                        if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: OptimalRange [ " + Settings.Instance.OptimalRange + "] Current Distance to [" + target.Name + "] is [" + target.Distance + "]", Logging.white);

                        if (target.Distance > Settings.Instance.OptimalRange + (int)Distance.OptimalRangeCushion && (Cache.Instance.Approaching == null || Cache.Instance.Approaching.Id != target.Id))
                        {
                            if (target.IsNPCFrigate)
                            {
                                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: target is NPC Frigate [" + target.Name + "][" + target.Distance + "]", Logging.white);
                                OrbitGateorTarget(target, module);
                                return;
                            }
                            target.Approach(Settings.Instance.OptimalRange);
                            Logging.Log(module, "Using Optimal Range: Approaching target [" + target.Name + "][ID: " + target.Id + "][" + Math.Round(target.Distance / 1000, 0) + "k away]", Logging.teal);
                        }
                        //I think when approach distance will be reached ship will be stopped so this is not needed
                        if (target.Distance <= Settings.Instance.OptimalRange && Cache.Instance.Approaching != null)
                        {
                            Cache.Instance.DirectEve.ExecuteCommand(DirectCmd.CmdStopShip);
                            Cache.Instance.Approaching = null;
                            Logging.Log(module, "Using Optimal Range: Stop ship, target at [" + Math.Round(target.Distance / 1000, 0) + "k away] is inside optimal", Logging.teal);
                        }
                    }
                    //if optimalrange is not set use MaxRange (shorter of weapons range and targeting range)
                    else
                    {
                        if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: using MaxRange [" + Cache.Instance.MaxRange + "] target is [" + target.Name + "][" + target.Distance + "]", Logging.white);

                        if (target.Distance > Cache.Instance.MaxRange && (Cache.Instance.Approaching == null || Cache.Instance.Approaching.Id != target.Id))
                        {
                            if (target.IsNPCFrigate)
                            {
                                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: target is NPC Frigate [" + target.Name + "][" + target.Distance + "]", Logging.white);
                                OrbitGateorTarget(target, module);
                                return;
                            }
                            target.Approach((int)(Cache.Instance.WeaponRange * 0.8d));
                            Logging.Log(module, "Using Weapons Range * 0.8d [" + Math.Round(Cache.Instance.WeaponRange * 0.8d/1000,0) + " k]: Approaching target [" + target.Name + "][ID: " + target.Id + "][" + Math.Round(target.Distance / 1000, 0) + "k away]", Logging.teal);
                        }
                        //I think when approach distance will be reached ship will be stopped so this is not needed
                        if (target.Distance <= Cache.Instance.MaxRange && Cache.Instance.Approaching != null)
                        {
                            if (target.IsNPCFrigate)
                            {
                                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: target is NPC Frigate [" + target.Name + "][" + target.Distance + "]", Logging.white);
                                OrbitGateorTarget(target, module);
                                return;
                            }
                            Cache.Instance.DirectEve.ExecuteCommand(DirectCmd.CmdStopShip);
                            Cache.Instance.Approaching = null;
                            Logging.Log(module, "Using Weapons Range: Stop ship, target is in orbit range", Logging.teal);
                        }
                    }
                    return;
                }
            }
        }
Example #44
0
        //this needs to accept a distance parameter....
        public static bool NavigateToTarget(EntityCache target, string module, bool orbit, int DistanceFromTarget)
        {
            // if we are inside warpto range you need to approach (you cant warp from here)
            if (target.Distance < (int) Distances.WarptoDistance)
            {
                if (orbit)
                {
                    if (target.Distance < DistanceFromTarget)
                    {
                        return true;
                    }

                    if (DateTime.UtcNow > Time.Instance.NextOrbit)
                    {
                        //we cant move in bastion mode, do not try
                        List<ModuleCache> bastionModules = null;
                        if (QuestorCache.Instance.Modules == null) return false;
                        bastionModules = QuestorCache.Instance.Modules.Where(m => m.GroupId == (int)Group.Bastion && m.IsOnline).ToList();
                        if (bastionModules.Any(i => i.IsActive)) return false;

                        Logging.Log(module, "StartOrbiting: Target in range", Logging.Teal);
                        if (!QuestorCache.Instance.IsApproachingOrOrbiting(target.Id))
                        {
                            Logging.Log("CombatMissionCtrl.NavigateToObject", "We are not approaching nor orbiting", Logging.Teal);
                            if (target.Orbit(DistanceFromTarget - 1500))
                            {
                                Logging.Log(module, "Initiating Orbit [" + target.Name + "][ID: " + target.MaskedId + "]", Logging.Teal);
                                return false;
                            }

                            return false;
                        }
                    }
                }
                else //if we are not speed tanking then check optimalrange setting, if that is not set use the less of targeting range and weapons range to dictate engagement range
                {
                    if (DateTime.UtcNow > Time.Instance.NextApproachAction)
                    {
                        if (target.Distance < DistanceFromTarget)
                        {
                            return true;
                        }

                        if (QuestorCache.Instance.Approaching == null || QuestorCache.Instance.Approaching.Id != target.Id || QuestorCache.Instance.MyShipEntity.Velocity < 50)
                        {
                            if (target.KeepAtRange(DistanceFromTarget - 1500))
                            {
                                Logging.Log(module, "Using SafeDistanceFromStructure: Approaching target [" + target.Name + "][ID: " + target.MaskedId + "][" + Math.Round(target.Distance / 1000, 0) + "k away]", Logging.Teal);
                            }

                            return false;
                        }

                        return false;
                    }

                    return false;
                }

            }
            // Probably never happens
            if (target.AlignTo())
            {
                return false;
            }

            return false;
        }
Example #45
0
        public static bool AvoidBumpingThings(EntityCache thisBigObject, string module)
        {
            if (AvoidBumpingThingsBool)
            {
                //if It has not been at least 60 seconds since we last session changed do not do anything
                if (QuestorCache.Instance.InStation || !QuestorCache.Instance.InSpace || QuestorCache.Instance.ActiveShip.Cloaked || (QuestorCache.Instance.InSpace && Time.Instance.LastSessionChange.AddSeconds(60) < DateTime.UtcNow))
                    return false;

                //we cant move in bastion mode, do not try
                List<ModuleCache> bastionModules = null;
                if (QuestorCache.Instance.Modules == null) return false;
                bastionModules = QuestorCache.Instance.Modules.Where(m => m.GroupId == (int)Group.Bastion && m.IsOnline).ToList();
                if (bastionModules.Any(i => i.IsActive)) return false;

                if (QuestorCache.Instance.ClosestStargate != null && QuestorCache.Instance.ClosestStargate.Distance < 9000)
                {
                    //
                    // if we are 'close' to a stargate or a station do not attempt to do any collision avoidance, as its unnecessary that close to a station or gate!
                    //
                    return false;
                }

                if (QuestorCache.Instance.ClosestStation != null && QuestorCache.Instance.ClosestStation.Distance < 11000)
                {
                    //
                    // if we are 'close' to a stargate or a station do not attempt to do any collision avoidance, as its unnecessary that close to a station or gate!
                    //
                    return false;
                }

                //EntityCache thisBigObject = Cache.Instance.BigObjects.FirstOrDefault();
                if (thisBigObject != null)
                {
                    //
                    // if we are "too close" to the bigObject move away... (is orbit the best thing to do here?)
                    //
                    if (thisBigObject.Distance >= (int)Distances.TooCloseToStructure)
                    {
                        //we are no longer "too close" and can proceed.
                        AvoidBumpingThingsTimeStamp = DateTime.UtcNow;
                        SafeDistanceFromStructureMultiplier = 1;
                        AvoidBumpingThingsWarningSent = false;
                    }
                    else
                    {
                        if (DateTime.UtcNow > Time.Instance.NextOrbit)
                        {
                            if (DateTime.UtcNow > AvoidBumpingThingsTimeStamp.AddSeconds(30))
                            {
                                if (SafeDistanceFromStructureMultiplier <= 4)
                                {
                                    //
                                    // for simplicities sake we reset this timestamp every 30 sec until the multiplier hits 5 then it should stay static until we are not "too close" anymore
                                    //
                                    AvoidBumpingThingsTimeStamp = DateTime.UtcNow;
                                    SafeDistanceFromStructureMultiplier++;
                                }

                                if (DateTime.UtcNow > AvoidBumpingThingsTimeStamp.AddMinutes(5) && !AvoidBumpingThingsWarningSent)
                                {
                                    Logging.Log("NavigateOnGrid", "We are stuck on a object and have been trying to orbit away from it for over 5 min", Logging.Orange);
                                    AvoidBumpingThingsWarningSent = true;
                                }

                                if (DateTime.UtcNow > AvoidBumpingThingsTimeStamp.AddMinutes(15))
                                {
                                    QuestorCache.Instance.CloseQuestorCMDLogoff = false;
                                    QuestorCache.Instance.CloseQuestorCMDExitGame = true;
                                    Cleanup.ReasonToStopQuestor = "navigateOnGrid: We have been stuck on an object for over 15 min";
                                    Logging.Log("ReasonToStopQuestor", Cleanup.ReasonToStopQuestor, Logging.Yellow);
                                    Cleanup.SignalToQuitQuestorAndEveAndRestartInAMoment = true;
                                }
                            }

                            if (thisBigObject.Orbit((int) Distances.SafeDistancefromStructure * SafeDistanceFromStructureMultiplier))
                            {
                                Logging.Log(module, ": initiating Orbit of [" + thisBigObject.Name + "] orbiting at [" + ((int)Distances.SafeDistancefromStructure * SafeDistanceFromStructureMultiplier) + "]", Logging.White);
                                return true;
                            }

                            return false;
                        }

                        return false;
                        //we are still too close, do not continue through the rest until we are not "too close" anymore
                    }

                    return false;
                }

                return false;
            }

            return false;
        }
Example #46
0
        public static void OrbitGateorTarget(EntityCache target, string module)
        {
            if (DateTime.UtcNow > Cache.Instance.NextOrbit)
            {
                //we cant move in bastion mode, do not try
                List<ModuleCache> bastionModules = null;
                bastionModules = Cache.Instance.Modules.Where(m => m.GroupId == (int)Group.Bastion && m.IsOnline).ToList();
                if (bastionModules.Any(i => i.IsActive)) return;

                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "OrbitGateorTarget Started", Logging.White);
                if (Cache.Instance.OrbitDistance == 0)
                {
                    Cache.Instance.OrbitDistance = 2000;
                }

                if (target.Distance + Cache.Instance.OrbitDistance < Cache.Instance.MaxRange - 5000)
                {
                    if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "if (target.Distance + Cache.Instance.OrbitDistance < Cache.Instance.MaxRange - 5000)", Logging.White);

                    //Logging.Log("CombatMissionCtrl." + _pocketActions[_currentAction] ,"StartOrbiting: Target in range");
                    if (!Cache.Instance.IsApproachingOrOrbiting(target.Id))
                    {
                        if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("CombatMissionCtrl.NavigateIntoRange", "We are not approaching nor orbiting", Logging.Teal);

                        //
                        // Prefer to orbit the last structure defined in
                        // Cache.Instance.OrbitEntityNamed
                        //
                        EntityCache structure = null;
                        if (!string.IsNullOrEmpty(Cache.Instance.OrbitEntityNamed))
                        {
                            structure = Cache.Instance.EntitiesOnGrid.Where(i => i.Name.Contains(Cache.Instance.OrbitEntityNamed)).OrderBy(t => t.Distance).FirstOrDefault();
                        }

                        if (structure == null)
                        {
                            structure = Cache.Instance.EntitiesOnGrid.Where(i => i.Name.Contains("Gate")).OrderBy(t => t.Distance).FirstOrDefault();
                        }

                        if (Settings.Instance.OrbitStructure && structure != null)
                        {
                            structure.Orbit(Cache.Instance.OrbitDistance);
                            Logging.Log(module, "Initiating Orbit [" + structure.Name + "][at " + Math.Round((double)Cache.Instance.OrbitDistance / 1000, 0) + "k][" + Cache.Instance.MaskedID(structure.Id) + "]", Logging.Teal);
                            return;
                        }

                        //
                        // OrbitStructure is false
                        //
                        if (Settings.Instance.SpeedTank)
                        {
                            target.Orbit(Cache.Instance.OrbitDistance);
                            Logging.Log(module, "Initiating Orbit [" + target.Name + "][at " + Math.Round((double)Cache.Instance.OrbitDistance / 1000, 0) + "k][ID: " + Cache.Instance.MaskedID(target.Id) + "]", Logging.Teal);
                            return;
                        }

                        //
                        // OrbitStructure is false
                        // Speedtank is false
                        //
                        if (Cache.Instance.MyShipEntity.Velocity < 300) //this will spam a bit until we know what "mode" our activeship is when aligning
                        {
                            if (Cache.Instance.DoWeCurrentlyHaveTurretsMounted())
                            {
                                if (DateTime.UtcNow > Cache.Instance.NextAlign)
                                {
                                    Cache.Instance.Star.AlignTo();
                                    Logging.Log(module, "Aligning to the Star so we might possibly hit [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "][ActiveShip.Entity.Mode:[" + Cache.Instance.ActiveShip.Entity.Mode + "]", Logging.Teal);
                                    return;
                                }
                            }
                        }
                    }
                }
                else
                {
                    Logging.Log(module, "Out of range. ignoring orbit around structure.", Logging.Teal);
                    target.Orbit(Cache.Instance.OrbitDistance);

                    return;
                }
                return;
            }
        }
Example #47
0
        public static void NavigateIntoRange(EntityCache target, string module, bool moveMyShip)
        {
            if (!Cache.Instance.InSpace || (Cache.Instance.InSpace && Cache.Instance.InWarp) || !moveMyShip)
                return;

            if (DateTime.UtcNow < NextNavigateIntoRange || Settings.Instance.DebugDisableNavigateIntoRange)
                return;

            NextNavigateIntoRange = DateTime.UtcNow.AddSeconds(5);

            //we cant move in bastion mode, do not try
            List<ModuleCache> bastionModules = null;
            bastionModules = Cache.Instance.Modules.Where(m => m.GroupId == (int)Group.Bastion && m.IsOnline).ToList();
            if (bastionModules.Any(i => i.IsActive)) return;

            if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange Started", Logging.White);

            if (Cache.Instance.OrbitDistance != Settings.Instance.OrbitDistance)
            {
                if (Cache.Instance.OrbitDistance == 0)
                {
                    Cache.Instance.OrbitDistance = Settings.Instance.OrbitDistance;
                    Logging.Log("CombatMissionCtrl", "Using default orbit distance: " + Cache.Instance.OrbitDistance + " (as the custom one was 0)", Logging.Teal);
                }

                //else
                //    Logging.Log("CombatMissionCtrl", "Using custom orbit distance: " + Cache.Instance.OrbitDistance, Logging.teal);
            }

            //if (Cache.Instance.OrbitDistance != 0)
            //    Logging.Log("CombatMissionCtrl", "Orbit Distance is set to: " + (Cache.Instance.OrbitDistance / 1000).ToString(CultureInfo.InvariantCulture) + "k", Logging.teal);

            NavigateOnGrid.AvoidBumpingThings(Cache.Instance.BigObjectsandGates.FirstOrDefault(), "NavigateOnGrid: NavigateIntoRange");

            if (Settings.Instance.SpeedTank)
            {
                if (target.Distance > Cache.Instance.MaxRange && !Cache.Instance.IsApproaching(target.Id))
                {
                    target.Approach((int)(Cache.Instance.MaxRange * 0.8d));
                    if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: speedtank: Moving into weapons range before initiating orbit", Logging.Teal);
                    return;
                }
                if (target.Distance < Cache.Instance.MaxRange && !Cache.Instance.IsOrbiting(target.Id))
                {
                    if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: speedtank: orbitdistance is [" + Cache.Instance.OrbitDistance + "]", Logging.White);
                    OrbitGateorTarget(target, module);
                    return;
                }
                return;
            }
            else //if we are not speed tanking then check optimalrange setting, if that is not set use the less of targeting range and weapons range to dictate engagement range
            {
                if (DateTime.UtcNow > Cache.Instance.NextApproachAction)
                {
                    //if optimalrange is set - use it to determine engagement range
                    if (Cache.Instance.OptimalRange != 0)
                    {
                        if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: OptimalRange [ " + Cache.Instance.OptimalRange + "] Current Distance to [" + target.Name + "] is [" + Math.Round(target.Distance / 1000, 0) + "]", Logging.White);

                        if (target.Distance > Cache.Instance.OptimalRange + (int)Distances.OptimalRangeCushion && (Cache.Instance.Approaching == null || Cache.Instance.Approaching.Id != target.Id))
                        {
                            if (target.IsNPCFrigate && Cache.Instance.DoWeCurrentlyHaveTurretsMounted())
                            {
                                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: target is NPC Frigate [" + target.Name + "][" + Math.Round(target.Distance / 1000, 0) + "]", Logging.White);
                                OrbitGateorTarget(target, module);
                                return;
                            }

                            target.Approach(Cache.Instance.OptimalRange);
                            Logging.Log(module, "Using Optimal Range: Approaching target [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "][" + Math.Round(target.Distance / 1000, 0) + "k away]", Logging.Teal);
                            return;
                        }

                        if (target.Distance <= Cache.Instance.OptimalRange)
                        {
                            if (target.IsNPCFrigate && ((Cache.Instance.Approaching != null && Cache.Instance.Approaching.Id != target.Id) || Cache.Instance.Approaching == null) && Cache.Instance.DoWeCurrentlyHaveTurretsMounted())
                            {
                                Logging.Log(module, "Target is NPC Frigate and we got Turrets. Keeping target at Range to hit it.", Logging.Teal);
                                target.Approach(Settings.Instance.OptimalRange);
                                Logging.Log(module, "Initiating KeepAtRange [" + target.Name + "][at " + Math.Round((double)Settings.Instance.OptimalRange / 1000, 0) + "k][ID: " + Cache.Instance.MaskedID(target.Id) + "]", Logging.Teal);
                                return;
                            }
                            else if (Cache.Instance.Approaching != null && Cache.Instance.MyShipEntity.Velocity != 0)
                            {
                                if (target.IsNPCFrigate && Cache.Instance.DoWeCurrentlyHaveTurretsMounted()) return;

                                StopMyShip();
                                Logging.Log(module, "Using Optimal Range: Stop ship, target at [" + Math.Round(target.Distance / 1000, 0) + "k away] is inside optimal", Logging.Teal);
                                return;
                            }
                        }
                    }
                    else if (!Cache.Instance.InMission && Cache.Instance.OptimalRange != Settings.Instance.OptimalRange)
                    {
                        Cache.Instance.OptimalRange = Settings.Instance.OptimalRange;
                        return;
                    }
                    else //if optimalrange is not set use MaxRange (shorter of weapons range and targeting range)
                    {
                        if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: using MaxRange [" + Cache.Instance.MaxRange + "] target is [" + target.Name + "][" + target.Distance + "]", Logging.White);

                        if (target.Distance > Cache.Instance.MaxRange && (Cache.Instance.Approaching == null || Cache.Instance.Approaching.Id != target.Id))
                        {
                            if (target.IsNPCFrigate && Cache.Instance.DoWeCurrentlyHaveTurretsMounted())
                            {
                                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: target is NPC Frigate [" + target.Name + "][" + target.Distance + "]", Logging.White);
                                OrbitGateorTarget(target, module);
                                return;
                            }
                            target.Approach((int)(Cache.Instance.MaxRange * 0.8d));
                            Logging.Log(module, "Using Weapons Range * 0.8d [" + Math.Round(Cache.Instance.MaxRange * 0.8d / 1000, 0) + " k]: Approaching target [" + target.Name + "][ID: " + Cache.Instance.MaskedID(target.Id) + "][" + Math.Round(target.Distance / 1000, 0) + "k away]", Logging.Teal);
                            return;
                        }

                        //I think when approach distance will be reached ship will be stopped so this is not needed
                        if (target.Distance <= Cache.Instance.MaxRange - 5000 && Cache.Instance.Approaching != null)
                        {
                            if (target.IsNPCFrigate && Cache.Instance.DoWeCurrentlyHaveTurretsMounted())
                            {
                                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: target is NPC Frigate [" + target.Name + "][" + target.Distance + "]", Logging.White);
                                OrbitGateorTarget(target, module);
                                return;
                            }
                            if (Cache.Instance.MyShipEntity.Velocity != 0) StopMyShip();
                            Logging.Log(module, "Using Weapons Range: Stop ship, target is more than 5k inside weapons range", Logging.Teal);
                            return;
                        }

                        if (target.Distance <= Cache.Instance.MaxRange && Cache.Instance.Approaching == null)
                        {
                            if (target.IsNPCFrigate && Cache.Instance.DoWeCurrentlyHaveTurretsMounted())
                            {
                                if (Settings.Instance.DebugNavigateOnGrid) Logging.Log("NavigateOnGrid", "NavigateIntoRange: target is NPC Frigate [" + target.Name + "][" + target.Distance + "]", Logging.White);
                                OrbitGateorTarget(target, module);
                                return;
                            }
                        }
                    }
                    return;
                }
            }
        }
Example #48
0
 public RegionsValues(EntityCache<RegionInfo> regions)
 {
     _regions = regions;
 }
Example #49
0
        public static void AddDronePriorityTarget(EntityCache ewarEntity, DronePriority priority, string module, bool AddEwarTypeToPriorityTargetList = true)
        {
            try
            {
                if (AddEwarTypeToPriorityTargetList && Drones.UseDrones)
                {
                    if ((ewarEntity.IsIgnored) || DronePriorityTargets.Any(p => p.EntityID == ewarEntity.Id))
                    {
                        if (Logging.DebugAddDronePriorityTarget) Logging.Log("AddDronePriorityTargets", "if ((target.IsIgnored) || DronePriorityTargets.Any(p => p.Id == target.Id))", Logging.Debug);
                        return;
                    }

                    if (DronePriorityTargets.All(i => i.EntityID != ewarEntity.Id))
                    {
                        int DronePriorityTargetCount = 0;
                        if (DronePriorityTargets.Any())
                        {
                            DronePriorityTargetCount = DronePriorityTargets.Count();
                        }
                        Logging.Log(module, "Adding [" + ewarEntity.Name + "] Speed [" + Math.Round(ewarEntity.Velocity, 2) + " m/s] Distance [" + Math.Round(ewarEntity.Distance / 1000, 2) + "] [ID: " + ewarEntity.MaskedId + "] as a drone priority target [" + priority.ToString() + "] we have [" + DronePriorityTargetCount + "] other DronePriorityTargets", Logging.Teal);
                        _dronePriorityTargets.Add(new PriorityTarget { Name = ewarEntity.Name, EntityID = ewarEntity.Id, DronePriority = priority });
                    }

                    return;
                }

                if (Logging.DebugAddDronePriorityTarget) Logging.Log(module, "UseDrones is [" + Drones.UseDrones.ToString() + "] AddWarpScramblersToDronePriorityTargetList is [" + Drones.AddWarpScramblersToDronePriorityTargetList + "] [" + ewarEntity.Name + "] was not added as a Drone PriorityTarget (why did we even try?)", Logging.Teal);
                return;
            }
            catch (Exception ex)
            {
                Logging.Log("AddDronePriorityTarget", "Exception [" + ex + "]", Logging.Debug);
            }
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            using (EntityCache ec = new EntityCache())
            {
                reader.Assert(JsonToken.StartObject);

                bool markedAsModified;
                ModifiableEntity mod = GetEntity(reader, objectType, existingValue, serializer, out markedAsModified);
                
                var pr = JsonSerializerExtensions.CurrentPropertyRoute;
                if (pr == null || mod is IRootEntity)
                    pr = PropertyRoute.Root(mod.GetType());
                else if (pr.Type.ElementType() == objectType)
                    pr = pr.Add("Item"); //Because we have a custom MListJsonConverter but not for other simpler collections

                var dic = PropertyConverter.GetPropertyConverters(mod.GetType());

                while (reader.TokenType == JsonToken.PropertyName)
                {
                    if ((string)reader.Value == "mixins")
                    {
                        var entity = (Entity)mod;
                        reader.Read();
                        reader.Assert(JsonToken.StartObject);

                        reader.Read();
                        while (reader.TokenType == JsonToken.PropertyName)
                        {
                            var mixin = entity[(string)reader.Value];

                            reader.Read();

                            using (JsonSerializerExtensions.SetCurrentPropertyRoute(pr.Add(mixin.GetType())))
                                serializer.DeserializeValue(reader, mixin.GetType(), mixin);

                            reader.Read();
                        }

                        reader.Assert(JsonToken.EndObject);
                        reader.Read();
                    }
                    else
                    {
                        PropertyConverter pc = dic.GetOrThrow((string)reader.Value);

                        reader.Read();
                        ReadJsonProperty(reader, serializer, mod, pc, pr, markedAsModified);

                        reader.Read();
                    }
                }

                reader.Assert(JsonToken.EndObject);

                AfterDeserilization.Invoke(mod);

                return mod;
            }
        }
Example #51
0
        /// <summary>
        ///   Invalidate the cached items every pulse (called from cache.invalidatecache, which itself is called every frame in questor.cs)
        /// </summary>
        public static void InvalidateCache()
        {
            try
            {
                //
                // this list of variables is cleared every pulse.
                //
                _activeDrones = null;
                //_droneBay = null;
                _dronePriorityEntities = null;
                _maxDroneRange = null;
                _preferredDroneTarget = null;

                if (_dronePriorityTargets != null && _dronePriorityTargets.Any())
                {
                    _dronePriorityTargets.ForEach(pt => pt.ClearCache());
                }
            }
            catch (Exception exception)
            {
                Logging.Log("Drones.InvalidateCache", "Exception [" + exception + "]", Logging.Debug);
            }
        }
Example #52
0
 public FindByIdCommand(Type entityType, int id, IEntityCache entityCache)
 {
     this.entityType = entityType;
     this.id = id;
     this.entityCache = (EntityCache) entityCache;
 }