public FreeGameRule(ServerRoom room)
        {
            this.args   = (FreeRuleEventArgs)room.RoomContexts.session.commonSession.FreeArgs;
            this.mapId  = room.RoomContexts.session.commonSession.RoomInfo.MapId;
            this.ruleId = room.RoomContexts.session.commonSession.RoomInfo.ModeId;

            this.Room = room;

            RandomUtil.SetSeed(RandomUtil.Random(1, 10000000));

            SendMessageAction.sender = new FreeMessageSender();

            try
            {
                string         rule   = RuleMap.GetRuleName(ruleId);
                FreeRuleConfig config = FreeRuleConfig.GetRule(rule, SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.Mysql);
                args.Triggers.Merge(config.Triggers);
                args.ComponentMap = config.GameComponentMap;
                args.AddDefault(this);
                args.Functions.Merge(config.Functions);
                args.rule = this;
                args.FreeContext.TestCase.Merge(config.Triggers);
            }
            catch (Exception e)
            {
                Debug.LogError("加载模式" + RuleMap.GetRuleName(ruleId) + "失败.\n" + e.Message);
                _logger.Error("加载模式" + RuleMap.GetRuleName(ruleId) + "失败.\n", e);
            }

            this.paras = new SimpleParaList();
            paras.AddFields(new ObjectFields(this));

            this.paras.AddPara(new IntPara(StatePara, 0));
            this.paras.AddPara(new IntPara(EnterPara, 0));
        }
Exemple #2
0
    public ContextsServerWrapper(Contexts contexts, IUnityAssetManager assetManager, ICoRoutineManager coRoutineManager)
    {
        var ruleId = RuleMap.GetRuleId(SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.Rule);

        this.contexts = contexts;
#if (!ENTITASDISABLEVISUALDEBUGGING && UNITYEDITOR)
        this.contexts.InitializeContexObservers();
#endif

        SingletonManager.Get <MyProfilerManager>().Contexts = contexts;
        IBin2DManager bin2DManager = CreateBin2DManager();
        IniCurrentTimeSession();

        var entityIdGenerator          = new EntityIdGenerator(EntityIdGenerator.GlobalBaseId);
        var equipmentEntityIdGenerator = new EntityIdGenerator(EntityIdGenerator.EquipmentBaseId);
        InitEntityFactorySession(entityIdGenerator, equipmentEntityIdGenerator);


        InitCommonSession(bin2DManager, entityIdGenerator, equipmentEntityIdGenerator, ruleId, assetManager,
                          coRoutineManager);

        InitServerSession(bin2DManager, ruleId);

        contexts.vehicle.SetSimulationTime(0);



        InitialWeaponSkill();
    }
Exemple #3
0
        internal Formatter(ParseTreeCache parseTreeProvider)
        {
            Requires.NotNull(parseTreeProvider, nameof(parseTreeProvider));

            this.parseTreeProvider = parseTreeProvider;
            this.formattingOptions = new FormattingOptions();
            this.ruleMap           = RuleMap.Create();
        }
Exemple #4
0
        protected MemberBinding BuildSelfPermissionBinding(
            Expression subject,
            object permissionResolverContext
            )
        {
            var selfPermissionExpression = RuleMap.GetInstanceCustomResolverExpression(permissionResolverContext, subject, State.ToPermission());

            return(selfPermissionExpression == null ? null : Expression.Bind(SelfPermissionProperty, Expression.Convert(selfPermissionExpression, typeof(bool?))));
        }
Exemple #5
0
        public ServerRoom Create(RequestCreateRoomMessage message)
        {
            _logger.InfoFormat("Handle CreateRoom Message");
            var serverRoom = new ServerRoom(new RoomId(1), _contexts, _dispatcher, _coRouitneManager, _assetMananger, _tokenGenerator);

            ResetEventDispacther();

            if (message != null)
            {
                HallRoom hallRoom = new HallRoom(_dispatcher, _contexts);
                hallRoom.HallRoomId       = message.HallRoomId;
                hallRoom.ModeId           = message.ModeId;
                hallRoom.TeamCapacity     = message.TeamCapacity;
                hallRoom.MapId            = message.MapId;
                hallRoom.RevivalTime      = message.RevivalTime;
                hallRoom.MultiAngleStatus = message.MultiAngleStatus;
                hallRoom.WatchStatus      = message.WatchStatus;
                hallRoom.HelpStatus       = message.HelpStatus;
                hallRoom.HasFriendHarm    = message.HasFriendHarm;
                hallRoom.WaitTimeNum      = message.WaitTimeNum;
                hallRoom.OverTime         = message.OverTime;
                hallRoom.ConditionValue   = message.ConditionValue;
                hallRoom.ConditionType    = message.ConditionType;
                hallRoom.ChannelName      = message.ChannelName;
                hallRoom.RoomName         = message.CustomRoomName;
                hallRoom.RoomCapacity     = message.CustomRoomCapacity;
                hallRoom.RoomDisplayId    = (int)message.CustomRoomDisplayId;

                hallRoom.Init();

                serverRoom.SetHallRoom(hallRoom);
                serverRoom.SetRoomInfo(hallRoom);
                serverRoom.SetGameMode(message.ModeId);

                _logger.InfoFormat("Create Room {0}", message.MapId);
            }
            else
            {
                //serverRoom.SetHallRoom(new DummyHallRoom(_dispatcher, _contexts));
                HallRoom hallRoom = new DummyHallRoom(_dispatcher, _contexts);
                hallRoom.Init();
                serverRoom.SetHallRoom(hallRoom);
                serverRoom.SetGameMode(RuleMap.GetRuleId(SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.Rule));
            }

            //serverRoom.Reset();

            return(serverRoom);
        }
Exemple #6
0
        public ServerRoom(IRoomId roomId, Contexts contexts, IRoomEventDispatchter eventDispatcher,
                          ICoRoutineManager coRoutineManager, IUnityAssetManager assetManager, IPlayerTokenGenerator tokenGenerator)
        {
            //SingletonManager.Get<ServerFileSystemConfigManager>().Reload();
            _state = RoomState.Initialized;

            _tokenGenerator   = tokenGenerator;
            _coRoutineManager = coRoutineManager;

            var entityIdGenerator          = new EntityIdGenerator(EntityIdGenerator.GlobalBaseId);
            var equipmentEntityIdGenerator = new EntityIdGenerator(EntityIdGenerator.EquipmentBaseId);
            var ruleId = RuleMap.GetRuleId(SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.Rule);

            RoomId    = roomId;
            _contexts = contexts;
#if (!ENTITAS_DISABLE_VISUAL_DEBUGGING && UNITY_EDITOR)
            _contexts.InitializeContexObservers();
#endif
            SingletonManager.Get <MyProfilerManager>().Contexts = _contexts;
            _eventDispatcher = eventDispatcher;
            _bin2DManager    = CreateBin2DManager();
            IniCurrentTimeSession();


            InitEntityFactorySession(entityIdGenerator, equipmentEntityIdGenerator);
            _assetManager = assetManager;


            InitCommonSession(entityIdGenerator,
                              equipmentEntityIdGenerator, ruleId);

            InitServerSession(_bin2DManager, ruleId);


            _contexts.vehicle.SetSimulationTime(0);
            MessageDispatcher    = CreateNetworMessageHandlers();
            _snapshotFactory     = new SnapshotFactory(_contexts.session.commonSession.GameContexts);
            _sessionStateMachine = new ServerSessionStateMachine(_contexts, this);

            _damager = new SimplePlayerDamager(this);
            VehicleDamageUtility._damager = _damager;
            _sendSnapshotManager          = new SendSnapshotManager(_contexts);

            InitialWeaponSkill();
        }
Exemple #7
0
        public async Task PostPersistAction(EntityEntry entry, ISet <EntityMutationInfo> cache)
        {
            var actionResult = new ActionResult();

            if (!(IsReference || cache.Contains(this)))
            {
                cache.Add(this);
                if (RuleMap != null)
                {
                    switch (State)
                    {
                    case (EntityState.Added): { await RuleMap.OnAfterCreation(MutationContext.SecurityContext, Entity, entry, this); break; }

                    case (EntityState.Modified): { await RuleMap.OnAfterEdition(MutationContext.SecurityContext, Entity, entry); break; }

                    case (EntityState.Deleted): { await RuleMap.OnAfterDeletion(MutationContext.SecurityContext, Entity, entry); break; }
                    }
                }
                foreach (var reference in References.Values.Where(reference => reference.TargetEntityMutationInfo != null))
                {
                    var targetEntry = entry.Reference(reference.Navigation.Name).TargetEntry;
                    if (targetEntry != null)
                    {
                        await reference.TargetEntityMutationInfo.PostPersistAction(targetEntry, cache);
                    }
                }
                foreach (var collectionMutationInfo in Collections.Values)
                {
                    var index      = 0;
                    var collection = (IEnumerable <object>)collectionMutationInfo.Navigation.GetGetter().GetClrValue(Entity);
                    foreach (var targetEntityMutationInfo in collectionMutationInfo.TargetEntityMutationInfos)
                    {
                        if (targetEntityMutationInfo.State != EntityState.Deleted)
                        {
                            await targetEntityMutationInfo.PostPersistAction(entry.Collection(collectionMutationInfo.Navigation.Name).FindEntry(collection.ElementAt(index)), cache);

                            index++;
                        }
                    }
                }
            }
        }
Exemple #8
0
            public Pattern ApplyRules(RuleMap rules)
            {
                (int tileSize, int tileCount) = GetTileSizeAndCount();
                int nextTileSize = GetNextTileSize(tileSize);
                int nextSize     = nextTileSize * tileCount;

                Pattern nextPattern = new Pattern(nextSize);

                foreach ((Tile currentTile, Tile nextTile) in GetTiles(tileSize).Zip(nextPattern.GetTiles(nextTileSize)))
                {
                    if (!rules.TryGetMatchedTile(currentTile.Size, currentTile.GetPrimaryId(), out Tile matchedTile))
                    {
                        throw new InvalidOperationException();
                    }

                    matchedTile.CopyTo(nextTile);
                }

                return(nextPattern);
            }
Exemple #9
0
        /// <summary>
        /// This is main entry point for the VS side of things. For now, the implementation
        /// of the function is not final and it just used as a way seeing results in VS.
        /// Ideally, Format will also take in a "formatting option" object that dictates
        /// the rules that should be enabled, spacing and tabs.
        /// </summary>
        /// <param name="sourceText">The SourceText that represents the text to be formatted</param>
        /// <param name="range">The range of indicies to be formatted</param>
        /// <param name="formattingOptions">The options to format with, null leaves the options as they were</param>
        /// <returns>
        /// A list of TextEditInfo objects are returned for the spacing between tokens (starting from the
        /// first token in the document to the last token. After the spacing text edits, the indentation
        /// text edits follow (starting again from the beginning of the document). I might separate the
        /// indentation text edits from the spacing text edits in the future but for now they are in
        /// the same list.
        /// </returns>
        public List <TextEditInfo> Format(SourceText sourceText, Range range, FormattingOptions formattingOptions)
        {
            Requires.NotNull(formattingOptions, nameof(formattingOptions));
            Requires.NotNull(sourceText, nameof(sourceText));

            this.formattingOptions = formattingOptions;
            this.ruleMap           = RuleMap.Create(this.formattingOptions.OptionalRuleMap);

            List <TextEditInfo> textEdits = new List <TextEditInfo>();

            SyntaxTree syntaxTree = this.parseTreeProvider.Get(sourceText);

            List <ParsedToken> parsedTokens = new List <ParsedToken>(ParsedToken.GetParsedTokens(syntaxTree, range));

            if (syntaxTree.ErrorList.Count == 0)
            {
                for (int i = 0; i < parsedTokens.Count - 1; ++i)
                {
                    FormattingContext formattingContext =
                        new FormattingContext(parsedTokens[i], parsedTokens[i + 1], sourceText);

                    Rule rule = this.ruleMap.Get(formattingContext);

                    if (rule != null)
                    {
                        textEdits.AddRange(rule.Apply(formattingContext));
                    }
                }
            }

            textEdits.AddRange(Indenter.GetIndentations(parsedTokens, this.formattingOptions));

            textEdits.Sort((x, y) => x.Start < y.Start ? 1 : x.Start == y.Start ? 0 : -1);

            return(textEdits);
        }
Exemple #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RuleTypeInfo" /> class.
        /// </summary>
        /// <param name="data">The data type.</param>
        /// <param name="rule">The rule.</param>
        /// <exception cref="NotSupportedException"></exception>
        public RuleTypeInfo(DataType data, RuleMap rule)
        {
            switch (rule.RuleType)
            {
            case RuleType.None:
                Description = "Group";
                break;

            case RuleType.Silent:
                Description = "Silent";
                break;

            case RuleType.Equals:
                Description = "Equals";
                break;

            case RuleType.NotEqual:
                Description = "Not Equals";
                break;

            case RuleType.GreaterThan:
                Description = data == DataType.Date ? "After" : "Greater Than";
                break;

            case RuleType.LessThan:
                Description = data == DataType.Date ? "Before" : "Less Than";
                break;

            case RuleType.LessThanOrEqualTo:
                Description = data == DataType.Date ? "Not After" : "Not Greater Than";
                break;

            case RuleType.GreaterThanOrEqualTo:
                Description = data == DataType.Date ? "Not Before" : "Not Less Than";
                break;

            case RuleType.Contains:
                Description = "Contains";
                break;

            case RuleType.DoesNotContain:
                Description = "Does Not Contain";
                break;

            case RuleType.Year:
                Description = "Is in the year";
                break;

            case RuleType.Length:
                Description = "Length";
                break;

            case RuleType.Between:
                Description = "Between";
                break;

            case RuleType.Match:
                Description = data == DataType.Text ? "Pattern Match" : "Pattern Match Replace";
                break;

            case RuleType.NotMatch:
                Description = "Pattern Does Not Match";
                break;

            case RuleType.InList:
                Description = "In List";
                break;

            case RuleType.NotInList:
                Description = "Not In List";
                break;

            case RuleType.InExternalList:
                Description = "In External List";
                break;

            case RuleType.NotInExternalList:
                Description = "Not In External List";
                break;

            case RuleType.Window:
                Description = "In Window";
                break;

            case RuleType.SetText:
                Description = "Set Text Value";
                break;

            case RuleType.SetNumber:
                Description = "Set Number Value";
                break;

            case RuleType.SetDate:
                Description = "Set Date Value";
                break;

            case RuleType.IsOfType:
                Description = data == DataType.Date ? "Is Date" : "Is Number";
                break;

            case RuleType.AppendValue:
                Description = "Append Text";
                break;

            case RuleType.SetDateFormat:
                Description = "Set Date Format";
                break;

            case RuleType.SetDateWindow:
                Description = "Set Date From Today";
                break;

            case RuleType.CopyFromCellToCell:
                Description = "Copy Value";
                break;

            case RuleType.UpdateDate:
                Description = "Change Date Value";
                break;

            case RuleType.SetRandomCharacters:
                Description = "Set Random Characters";
                break;

            case RuleType.LookupList:
                Description = "Look-up";
                break;

            case RuleType.Substring:
                Description = "Copy Selected Length";
                break;

            case RuleType.CalCulateValue:
                Description = "Calculate";
                break;

            case RuleType.SplitString:
                Description = "Copy Split Selection";
                break;

            default:
                //this stops any undefined (but valid) rule type being added
                throw new NotSupportedException();
            }
            RuleType            = rule.RuleType;
            EditTemplate        = rule.EditTemplate;
            LayoutTemplate      = rule.LayoutTemplate;
            EditController      = rule.EditController;
            OptionsList         = rule.OptionsList;
            ComparatorTypesList = rule.ComparatorTypesList;
        }
Exemple #11
0
 public Day21()
 {
     string[] rules = File.ReadAllLines("Inputs/Day21.txt");
     _ruleMap = new RuleMap(rules);
 }
 public static RuleMap <TContext, TEntity> HasInstancePermissionCustomResolverExpression <TContext, TEntity>(this RuleMap <TContext, TEntity> rulemap, Permission permission, Expression <Func <TContext, TEntity, bool> > resolver) where TEntity : class
 {
     rulemap.HasInstanceCustomResolverExpression(permission, resolver);
     return(rulemap);
 }
Exemple #13
0
 public XmlRule(RuleMap map)
     : base(map)
 {
 }
Exemple #14
0
        public void CheckPermissions(object context, object permissionEntity, ISet <EntityMutationInfo> cache)
        {
            if (!(IsReference || cache.Contains(this)))
            {
                cache.Add(this);
                var permissionEntityType = permissionEntity?.GetType();
                var primaryKeyPairs      = PropertyTuples.Where(pt => PrimaryKey.Properties.Any(pk => pk == pt.Property));
                var primaryKeyTuples     = PrimaryKey.Properties.Join(PropertyTuples, pk => pk, pt => pt.Property, (pk, pt) => pt);

                var requiredPermission = State.ToPermission();
                var typePermission     = (bool?)RuleMap.ResolveTypeCustom(requiredPermission, context);
                var instancePermission = (bool?)permissionEntityType?.GetProperty("SelfPermission")?.GetValue(permissionEntity)
                                         ?? (bool?)RuleMap.ResolveInstanceCustom(context, Entity, requiredPermission);

                if (instancePermission != null && !instancePermission.Value)
                {
                    throw new UnauthorizedAccessException($"You do not have permission to {Enum.GetName(typeof(Permission), requiredPermission)} on entity type {EntityType.Name} with id with key ({string.Join(", ", primaryKeyPairs.Select(kp => $"{kp.Property.Name}={kp.JProperty.Value}"))}).");
                }

                if (instancePermission == null && (typePermission == null || !typePermission.Value))
                {
                    throw new UnauthorizedAccessException($"You do not have permission to {Enum.GetName(typeof(Permission), requiredPermission)} on entity type {EntityType.Name}.");
                }

                var globalPermission = instancePermission ?? typePermission;

                foreach (var primaryKeyPropertyTuple in primaryKeyTuples)
                {
                    var propertyPermission         = (bool?)RuleMap.ResolvePropertyCustom(requiredPermission, primaryKeyPropertyTuple.Property.PropertyInfo, context);
                    var instancePropertyPermission = (bool?)permissionEntityType?.GetProperty($"{primaryKeyPropertyTuple.Property.Name}Permission")?.GetValue(permissionEntity)
                                                     ?? (bool?)RuleMap.ResolveInstancePropertyCustom(primaryKeyPropertyTuple.Property.PropertyInfo, Permission.Read, context, Entity);
                    if (instancePropertyPermission != null && !instancePropertyPermission.Value)
                    {
                    }
                    if (instancePropertyPermission == null && (globalPermission == null || !globalPermission.Value) && (propertyPermission == null || !propertyPermission.Value))
                    {
                        throw new UnauthorizedAccessException($"You do not have permission to {Enum.GetName(typeof(Permission), Permission.Read)} on property {primaryKeyPropertyTuple.Property.Name} on entity type {EntityType.Name}.");
                    }
                }

                foreach (var property in PropertyTuples.Select(pt => pt.Property.AsPropertyBase()).Union(ReferenceTuples.Union(CollectionTuples).Select(nt => nt.Navigation.AsPropertyBase())))
                {
                    var propertyPermission         = (bool?)RuleMap.ResolvePropertyCustom(requiredPermission, property.PropertyInfo, context);
                    var instancePropertyPermission = (bool?)permissionEntityType?.GetProperty($"{property.Name}Permission")?.GetValue(permissionEntity)
                                                     ?? (bool?)RuleMap.ResolveInstancePropertyCustom(property.PropertyInfo, requiredPermission, context, Entity);
                    if (instancePropertyPermission != null && !instancePropertyPermission.Value)
                    {
                        throw new UnauthorizedAccessException($"You do not have permission to {Enum.GetName(typeof(Permission), requiredPermission)} on property {property.Name} on entity type {EntityType.Name} with key ({string.Join(", ", primaryKeyPairs.Select(kp => $"{kp.Property.Name}={kp.JProperty.Value}"))}).");
                    }
                    if (instancePropertyPermission == null && (globalPermission == null || !globalPermission.Value) && (propertyPermission == null || !propertyPermission.Value))
                    {
                        throw new UnauthorizedAccessException($"You do not have permission to {Enum.GetName(typeof(Permission), requiredPermission)} on property {property.Name} on entity type {EntityType.Name}.");
                    }
                }

                foreach (var reference in References.Values.Where(reference => reference.TargetEntityMutationInfo != null))
                {
                    reference.TargetEntityMutationInfo.CheckPermissions(context, permissionEntityType?.GetProperty(reference.Navigation.Name)?.GetValue(permissionEntity), cache);
                }

                foreach (var collectionMutationInfo in Collections.Values)
                {
                    if (permissionEntity != null)
                    {
                        var collection = (object[])MutationContext.PermissionEntityTypeBuilder.PropertyMap[collectionMutationInfo.Navigation].GetValue(permissionEntity);
                        if (collection != null)
                        {
                            var index = 0;
                            foreach (var itemMutationInfo in collectionMutationInfo.TargetEntityMutationInfos)
                            {
                                if (itemMutationInfo.State != EntityState.Added)
                                {
                                    itemMutationInfo.CheckPermissions(context, collection[index], cache);
                                    index++;
                                }
                            }
                        }
                    }
                }
            }
        }
 protected override RuleBase MakeRule(RuleMap map)
 {
     return new XmlRule(map);
 }