public void ShouldRestoreFromSnapshot() { var snapshot = Fake <FakeState>(); var entity = Factory.Create("test", "test", snapshot: snapshot); entity.State.SnapshotWasRestored.Should().BeTrue(); }
public IList <Attendance> GetEmployees(Schedule schedule) { var reloadSchedule = _scheduleRepository.Get(schedule.Id); var employees = _employeeRepository.GetEmployeeByOrganizations(reloadSchedule.Organizations.ToArray(), schedule.Start); var involved = _attendanceRepository.GetAttendanceFrom(reloadSchedule).ToDictionary(o => o.Agent); var results = new List <Attendance>(involved.Values); foreach (var o in employees) { if (involved.ContainsKey(o)) { continue; } var entity = _entityFactory.Create <Attendance>() .SetProperties <Attendance>(o, reloadSchedule.Campaign, reloadSchedule.Start, reloadSchedule.End) .CopyRule(o); entity.Joined = false; results.Add(entity); } return(results); }
private void HandleSelectCharacterRequest(string username, PacketBase p) { CharacterSelectedPacket packet = (CharacterSelectedPacket)p; // If player is already added to the game world, we don't want to add another. Ignore this request. if (_pcs.ContainsKey(username)) { _logger.Info($"Player {username} is already added to the game world. Ignoring request."); return; } string path = _pathService.ServerVaultDirectory + username + "/" + packet.PCGlobalID + ".pcf"; if (!File.Exists(path)) { _logger.Error($"PC file '{packet.PCGlobalID}.pcf' does not exist for username {username}. Cannot select character. Ignoring request."); return; } PCData pcData = _dataService.Load <PCData>(path); Entity player = _entityFactory.Create <Player, PCData>(pcData); _pcs.Add(username, player); ScriptGroup scripts = _gameModule.GetComponent <ScriptGroup>(); string script = scripts[ScriptEvent.OnModulePlayerEnter]; _scriptService.QueueScript(script, _gameModule); CharacterAddedToWorldPacket response = new CharacterAddedToWorldPacket(); _networkService.SendMessage(PacketDeliveryMethod.ReliableUnordered, response, username); }
public async Task <T> Create <T>() where T : IEntity, new() { var entity = await _entityFactory.Create <T>(); Entities.TryAdd($"{nameof(entity)}|{Guid.NewGuid().ToString()}", entity); return(entity); }
public void Create(IntPtr entityPointer, ushort id) { if (entities.ContainsKey(entityPointer)) { return; } Add(entityFactory.Create(entityPointer, id)); }
public IEnumerable <CommandDefinition> GetCommands(IEnumerable <string> context) { context = context.ToArray(); if (!context.Any()) { newCommand = CommandDefinitionBuilder.Create() .SetName("new") .SetHelp("Creates new files / projects.") .Build(); deployCommand = templateCommandBuilder.GenerateDeployCommandDefinition(null, null, null, repository.Templates.ToArray()); return(new[] { newCommand, deployCommand }); } if (context.SequenceEqual(new[] { "new" })) { List <CommandDefinition> commandDefinitions = new List <CommandDefinition>(); foreach (TemplateDescription template in repository.Templates) { if (template.isHidden || commandDefinitions.Any(d => d.Name == template.name)) { continue; } Entity templateEntity = entityFactory.Create(template.name); templateEntity.SetMetaData(true, EntityKeys.IsTemplateOnly); commandDefinitions.Add(templateCommandBuilder.GenerateNewCommandDefinition(templateEntity, template, newCommand, repository.Templates)); } return(commandDefinitions); } if (context.SequenceEqual(new[] { "deploy" })) { List <CommandDefinition> commandDefinitions = new List <CommandDefinition>(); foreach (TemplateDescription template in repository.Templates) { if (template.isHidden || commandDefinitions.Any(d => d.Name == template.name) || !template.isRoot) { continue; } Entity templateEntity = entityFactory.Create(template.name); templateEntity.SetMetaData(true, EntityKeys.IsTemplateOnly); commandDefinitions.Add(templateCommandBuilder.GenerateDeployCommandDefinition(templateEntity, template, deployCommand, repository.Templates.ToArray())); } return(commandDefinitions); } if (context.SequenceEqual(new[] { "generate" })) { return(templateCommandBuilder.CreateGenerateCommandDefinitions(generateCommands, repository.Templates)); } return(Enumerable.Empty <CommandDefinition>()); }
public void Load(string mapName) { Entity level = _entityFactory.Create <Level>(mapName); _entityFactory.Create <Player>(CharacterType.X, 16, -30); Script script = level.GetComponent <Script>(); _scriptManager.QueueScript(script.FilePath, level, "OnLoad"); }
public BasicAssignmentType SaveAsNew(string newName, Type type, ref BasicAssignmentType source) { var newEntity = _entityFactory.Create <BasicAssignmentType>(type); newEntity.GapGuaranteed = source.GapGuaranteed; newEntity.Occupied = source.Occupied; newEntity.IgnoreAdherence = source.IgnoreAdherence; newEntity.AsAWork = source.AsAWork; newEntity.AsARest = source.AsARest; newEntity.Name = newName; newEntity.Type = source.Type; newEntity.Background = source.Background; newEntity.SetNewTime(source.Start, source.End); foreach (var o in source.GetSubEventInsertRules()) { var copy = o; _entityFactory.Create <SubEventInsertRule>().Self( n => { n.TimeRange = copy.TimeRange; n.SubEvent = copy.SubEvent; n.SubEventLength = copy.SubEventLength; newEntity.AddSubEventInsertRule(n); }); } if (type == typeof(AssignmentType)) { var copy = source.As <AssignmentType>(); newEntity.Self <AssignmentType>(n => { n.ServiceQueue = copy == null ? null: copy.ServiceQueue; n.EstimationPriority = copy == null ? 1 : copy.EstimationPriority; n.Template1 = copy == null ? null : copy.Template1; n.Template2 = copy == null ? null : copy.Template2; n.Template3 = copy == null ? null : copy.Template3; n.TimeZoneInfoId = copy == null ? "Taipei Standard Time" : copy.TimeZone.Id; n.Country = copy == null ? "Taiwan" : copy.Country; if (copy != null) { n.WorkingDayMask.Weekdays = copy.WorkingDayMask.Weekdays; n.WorkingDayMask.Weekdays2 = copy.WorkingDayMask.Weekdays2; n.WorkingDayMask.Monthdays = copy.WorkingDayMask.Monthdays; } }); } //_termStyleRepository.MakePersistent(newEntity); //Reload(ref source); return(newEntity); }
public TEntity GetEntity(TextSlice slice) { TEntity entity = _factory.Create(); for (int i = 0; i < _properties.Length; i++) { _properties[i].Map(entity, slice); } return(entity); }
/// <summary> /// Creates an enemy entity at a specified position. /// </summary> /// <param name="name">Name of the enemy file in the Enemies folder.</param> /// <param name="x">The X position of the newly created entity.</param> /// <param name="y">The Y position of the newly created entity.</param> /// <param name="direction">The direction the enemy starts facing.</param> /// <returns>The newly created entity, or nil if no file could be found.</returns> public Entity CreateEnemy(string name, int x, int y, Direction direction) { try { Entity enemy = _entityFactory.Create <Enemy>(name, x, y); enemy.GetComponent <Position>().Facing = direction; return(enemy); } catch (Exception) { return(null); } }
protected void InitialDetailPresenters(IEnumerable <TEntity> exists, Dictionary <string, object> args, Func <TEntity, TEntity> looping) { var @params = args ?? new Dictionary <string, object>(); Presenters.SupendOnCollectionChangedEvent(true); foreach (var item in exists) { @params["Entity"] = looping(item); LoadPresenters(_entityFactory.Create <TIDetailPresenter>(@params).Self(p => p.Initialize())); } Presenters.SupendOnCollectionChangedEvent(false); @params.Remove("Entity"); }
private void AreaOpened(AreaDataObservable area) { CameraReset(); _loadedAreaData = _objectMapper.Map <AreaData>(area); _loadedArea = _entityFactory.Create <Area, AreaData>(_loadedAreaData); Texture2D texture = _loadedArea.GetComponent <Renderable>().Texture; _objectPainter = _entityFactory.Create <ObjectPainter, Texture2D>(texture); Paintable paintable = _objectPainter.GetComponent <Paintable>(); paintable.AreaHeight = _loadedAreaData.Height; paintable.AreaWidth = _loadedAreaData.Width; }
public void AddInsertRule(DragEventArgs e) { var start = e.Data.GetData("DropedPlacement").SaftyGetProperty <DateTime, ITerm>(o => o.Start); var subevent = e.Data.GetData("PointOutBlock").SaftyGetProperty <TermStyle, VisibleSubEventTerm>(o => o.Source); if (subevent == null || subevent.Type == typeof(Shrink)) { return; } var startValue = (int)start.Subtract(Entity.Start).TotalMinutes; var endValue = startValue + (subevent.TimeRange.Length * 1); var rule = _entityFactory.Create <SubEventInsertRule>(); //var timeRange = new TimeValueRange(startValue, endValue); //if (timeRange.IsValid) return null; rule.MAssign(new { TimeRange = new TimeValueRange(startValue, endValue), SubEvent = subevent, SubEventLength = subevent.TimeRange.Length }); if (Entity.AddSubEventInsertRule(rule)) { SelectedBlock = rule; } }
public Area ReloadWithSeat(Area area, out IEnumerable <IArrangeSeatRule> availableOrganizations) { var result = _areaRepository.Get(area.Id); var exists = _areaRepository.GetOrganizationSeatingArea(area.Id).ToDictionary(o => o.Object); var all = new List <IArrangeSeatRule>(); var defaultTargetSeat = result.Seats.FirstOrDefault(); foreach (var item in ((Campaign)result.Campaign).Organizations) { if (exists.ContainsKey(item)) { all.Add(exists[item]); } else { var o = defaultTargetSeat == null ? null : _entityFactory.Create <OrganizationSeatingArea>(new Dictionary <string, object> { { "Area", result }, { "Object", item }, { "TargetSeat", defaultTargetSeat } }); if (o != null) { _areaRepository.MakePersistent(o); all.Add(o); } } } availableOrganizations = all.ToRebuildPriorityList <IArrangeSeatRule, IArrangeSeatRule>(true, null); return(result); }
public static IEntity Create(this IEntityFactory entityFactory, IEntityDefinition definition) { entityFactory.NotNull(nameof(entityFactory)); definition.NotNull(nameof(definition)); return(entityFactory.Create(definition, CancellationToken.None).GetAwaiter().GetResult()); }
TEntity BuildEntity <TEntity>(Guid id, int version) where TEntity : IEntity { var minVersion = 0; var entity = _entityFactory.Create <TEntity>(); entity.Id = id; if (typeof(TEntity).IsAssignableToGenericType(typeof(ISnapshotable <>))) { var snapshot = _eventStore.Advanced.GetSnapshot(id, version); if (snapshot != null) { dynamic snapshotable = entity; snapshotable.Hydrate(snapshot.Payload); minVersion = snapshot.StreamRevision; } } using (var stream = _eventStore.OpenStream(id, minVersion, version)) { foreach (var @event in stream.CommittedEvents) { entity.ApplyEvent(@event.Body); } } return(entity); }
protected override CommandResult ExecuteDetailed(GetProjectInformationCommandArgs args, ChangeObservable observable) { Entity root = entityFactory.Create(Guid.NewGuid().ToByteString(), args).Root; propertiesProvider.Initialize(root); return(new CommandResult(0, new ProjectInformationCommandResult(propertiesProvider.ProjectName, propertiesProvider.ProjectNamespace, propertiesProvider.ProjectType, propertiesProvider.ProjectTargets.Select(t => new TargetResult(t.Target.Name, t.Target.Version, t.Target.LongVersion, t.Target.ShortVersion, t.IsAvailable)), propertiesProvider.ProjectCodeEntities.Select(kvp => new EntityResult(kvp.Key.Name, kvp.Key.Namespace, kvp.Key.Type, kvp.Value.Select(en => en.Name))), propertiesProvider.IncludePaths.Select(p => new CommandResults.IncludePath(p.PathValue, (p.Exists != null ? (bool)p.Exists : false), p.Targets .Select(t => new TargetResult(t.Name, t.Version, t.LongVersion, t.ShortVersion) ) ) ) ), propertiesProvider.Exceptions)); }
private void OnLevelOpened(LevelData levelData) { CloseLevel(); _activeLevel = _entityFactory.Create <EditorLevel>( levelData.Width, levelData.Height, levelData.Name, levelData.Spritesheet, levelData.Tiles); _activeLevel.GetComponent <Map>().ShowEmptyTiles = true; _highlightedTile = _entityFactory.Create <HighlightedTile>( 0, 0, TilesetConstants.TileWidth, TilesetConstants.TileHeight, Color.Yellow); }
TEntity Convert(TextSlice slice) { var entity = _factory.Create(); for (var i = 0; i < _properties.Length; i++) { _properties[i].Convert(entity, slice); } return(entity); }
protected override int Execute(GenerateLibraryCommandArgs args, ChangeObservable observable) { if (!string.IsNullOrEmpty(args.LibraryGuid) && !Guid.TryParse(args.LibraryGuid, out Guid realGuid)) { throw new LibraryIdMalformattedException(args.LibraryGuid); } Entity project = entityFactory.Create(Guid.NewGuid().ToByteString(), args).Root; return(builder.BuildLibraryForProject(project, observable, args.MetaFilesDirectory, args.LibraryLocation, args.OutputDirectory, realGuid, args.Target, args.ExternalLibraries, null)); }
public FilmEntity Map(FilmDetailModel detailModel, IEntityFactory entityFactory) { var newEntity = (entityFactory ??= new CreateNewEntityFactory()).Create <FilmEntity>(detailModel.Id); newEntity.Id = detailModel.Id; newEntity.OriginalName = detailModel.OriginalName; newEntity.CzechName = detailModel.CzechName; newEntity.CountryOfOrigin = detailModel.CountryOfOrigin; newEntity.Description = detailModel.Description; newEntity.ImageFilePath = detailModel.ImageFilePath; newEntity.GenreOfFilm = detailModel.GenreOfFilm; newEntity.LengthInMinutes = detailModel.LengthInMinutes; newEntity.Directors = detailModel.Directors.Select(model => { var newFilmDirectorEntity = entityFactory.Create <FilmDirectorEntity>(model.Id); newFilmDirectorEntity.FilmId = detailModel.Id; newFilmDirectorEntity.DirectorId = model.DirectorId; return(newFilmDirectorEntity); }).ToList(); newEntity.Actors = detailModel.Actors.Select(model => { var newFilmActorEntity = entityFactory.Create <FilmActorEntity>(model.Id); newFilmActorEntity.FilmId = detailModel.Id; newFilmActorEntity.ActorId = model.ActorId; return(newFilmActorEntity); }).ToList(); newEntity.Ratings = detailModel.Ratings.Select(model => { var newRatingEntity = entityFactory.Create <RatingEntity>(model.Id); newRatingEntity.FilmId = detailModel.Id; newRatingEntity.RatingInPercents = model.RatingInPercents; newRatingEntity.TextRating = model.TextRating; return(newRatingEntity); }).ToList(); return(newEntity); }
private Session CreateSession(IEntityFactory factory, User user, string ip) { var now = _systemDateService.Now(); var session = factory.Create <Session>(); session.Guid = Guid.NewGuid(); session.User = user; session.IP = ip; session.CreationTime = now; session.LastAction = now; return(session); }
public CourseEntity Map(CourseDetailModel detailModel, IEntityFactory entityFactory) { var entity = (entityFactory ??= new CreateNewEntityFactory()).Create <CourseEntity>(detailModel.Id); entity.Id = detailModel.Id; entity.Name = detailModel.Name; entity.Description = detailModel.Description; entity.StudentCourses = detailModel.Students.Select(model => { var studentCourseEntity = entityFactory.Create <StudentCourseEntity>(model.CourseId); studentCourseEntity.CourseId = detailModel.Id; studentCourseEntity.StudentId = model.StudentId; return(studentCourseEntity); }).ToList(); return(entity); }
protected override int Execute(BuildCommandArgs args, ChangeObservable observable) { string buildProperties = string.Join(" ", args.BuildProperties.Select(Unescape)); Entity rootEntity = entityFactory.Create(Guid.NewGuid().ToByteString(), args).Root; BuildInformation buildInfo = new BuildInformation(rootEntity, args.BuildType, args.Configure, args.NoConfigure, buildProperties, args.Output); builder.Build(buildInfo, observable, args.Target); return(0); string Unescape(string arg) { return(arg.Replace("%22", "\"")); } }
private IVisibleLinerData ConvertTo(double[] values, int category, string resourceKey, object queue) { var entity = _entityFactory.Create <IVisibleLinerData>(); entity.Color = resourceKey + "LineColor"; entity.Values = values; entity.Text = resourceKey; entity.Source = queue; entity.Category = category; entity.Format = category == 1 ? "{0:0.#%}" : "{0:0.#}"; if (category == 1) { entity.MaxValue = 1.1; } entity.SaftyInvoke <ISelectable>(o => o.IsSelected = true); return(entity); }
protected override CommandResult ExecuteDetailed(GetProgramsCommandArgs args, ChangeObservable observable) { ExecutionContext.WriteWarning("This command is deprecated. Use 'get project-information' instead.", false); TemplateEntity project = TemplateEntity.Decorate(entityFactory.Create(Guid.NewGuid().ToByteString(), args).Root); IEnumerable <Entity> programs = project.EntityHierarchy.Where(e => e.Type.Equals("program", StringComparison.OrdinalIgnoreCase)) .ToArray(); if (!string.IsNullOrEmpty(args.Component)) { Entity component = project.EntityHierarchy.FirstOrDefault(e => e.HasName && e.Name == args.Component && e.Type.Equals("component", StringComparison.OrdinalIgnoreCase)); if (component != null) { programs = programs.Where(p => TemplateEntity.Decorate(p).RelatedEntites.Contains(component)); } else { ExecutionContext.WriteError($"A component with name {args.Component} does not exist in project {project.Name}."); return(new CommandResult(-1, ProgramsCommandResult.Empty)); } } if (!programs.Any()) { ExecutionContext.WriteInformation($"No programs found."); return(new CommandResult(0, ProgramsCommandResult.Empty)); } return(new CommandResult(0, new ProgramsCommandResult(programs.Select(p => { CodeEntity codeEntity = CodeEntity.Decorate(p); TemplateEntity templateEntity = TemplateEntity.Decorate(p); Entity componentEntity = templateEntity.RelatedEntites.FirstOrDefault(e => e.Type == "component"); if (componentEntity == null) { throw new InvalidOperationException($"Program {p.Name} has no related component. This should not be possible."); } CodeEntity componentCodeEntity = CodeEntity.Decorate(componentEntity); return new ProgramResult(p.Name, codeEntity.Namespace, componentEntity.Name, componentCodeEntity.Namespace); })))); }
public Dictionary <string, AgentStatus> Search(Entity area, DateTime time, Dictionary <string, AgentStatusType> agentStatusTypes) { var sqlStatement = string.Format( @"select AgentStatus.[TimeStamp], AgentStatus.ExtNo, AgentStatus.AgentACDId ,AgentStatus.AgentStatusTypeCode from AgentStatus INNER JOIN Seat ON AgentStatus.ExtNo = Seat.ExtNo INNER JOIN AgentStatusType ON AgentStatus.AgentStatusTypeCode = AgentStatusType.AgentStatusTypeCode and Seat.AreaId = '{0}' and AgentStatus.AgentStatusId in ( SELECT AgentStatusId FROM AgentStatus a,(SELECT MAX(TimeStamp) as TimeStamp, AgentACDId FROM AgentStatus WHERE TimeStamp >= '{1:yyyy/MM/dd HH:mm:ss}' and TimeStamp <= '{2:yyyy/MM/dd HH:mm:ss}' GROUP BY AgentACDId) b WHERE a.TimeStamp = b.TimeStamp and a.AgentACDId = b.AgentACDId) order by AgentStatus.TimeStamp desc", area.Id, time.AddHours(-12), time); var agentLastActivity = new Dictionary <string, IAgentStatus>(); var seatLastActivity = new Dictionary <string, AgentStatus>(); ToLightweightAgentStatus(sqlStatement, o => { agentLastActivity[o.AgentAcdid] = o; }, () => _entityFactory.Create <AgentStatus>()); var removeLogoutStatus = new Action(() => { }); foreach (var item in agentLastActivity) { var agentStatus = ((AgentStatus)item.Value).SetAgentStatusType(agentStatusTypes); if (agentStatus.IsLogout()) { var key = item.Key; removeLogoutStatus += () => { agentLastActivity[key] = default(IAgentStatus); }; continue; } seatLastActivity[item.Value.ExtNo] = agentStatus; } removeLogoutStatus(); return(seatLastActivity); }
public DirectorEntity Map(DirectorDetailModel detailModel, IEntityFactory entityFactory) { var newEntity = (entityFactory ??= new CreateNewEntityFactory()).Create <DirectorEntity>(detailModel.Id); newEntity.Id = detailModel.Id; newEntity.FirstName = detailModel.FirstName; newEntity.SecondName = detailModel.SecondName; newEntity.Age = detailModel.Age; newEntity.WikiUrl = detailModel.WikiUrl; newEntity.PhotoFilePath = detailModel.PhotoFilePath; newEntity.DirectedMovies = detailModel.DirectedMovies.Select(transsitionTable => { var newFilmDirectorEntity = entityFactory.Create <FilmDirectorEntity>(transsitionTable.Id); newFilmDirectorEntity.FilmId = transsitionTable.FilmId; newFilmDirectorEntity.DirectorId = detailModel.Id; return(newFilmDirectorEntity); }).ToArray(); return(newEntity); }
public IEnumerable <TEntity> FindEntities(string html) { HtmlNode documentNode = new HtmlToHtmlNode( new CleanHtmlLite( html, () => _options.CleanHtml)); HtmlXPathTemplate template = _template.Value; HtmlNodeCollection nodes = documentNode.SelectNodes(template.RootNodeXPath); foreach (HtmlNode node in nodes) { JsonObject json = new JsonObject(); FillJsonProperties <TEntity>(template.Patterns, node, json); if (!_options.SkipEmptyEntities || !json.IsEmpty) { yield return(_entityFactory.Create(json.ToString())); } } }
public async Task <TranslateResult <TSchema> > Translate(TranslateContext <TInput, TSchema> context) { var entity = _entityFactory.Create(); if (_observers.Count > 0) { await _observers.PreTranslateEntity(entity, context).ConfigureAwait(false); } await Task.WhenAll(_propertyTranslaters.Select(x => x.Apply(entity, context))).ConfigureAwait(false); var translateResult = context.Result(entity); if (_observers.Count > 0) { await _observers.PostTranslateEntity(translateResult, context).ConfigureAwait(false); } return(translateResult); }