public void GetContentWithNoParametersReturnsDefaultContent()
        {
            var factory = new ContentFactory();

            IContent content = factory.GetContent();

            Assert.AreEqual(!default(bool), content is EmptyContent);
        }
        public void SetContentAssignsSpecifiedContentToContext()
        {
            var cell = new Cell();
            var contentFactory = new ContentFactory();
            cell.SetContent(contentFactory.GetContent(ContentType.Bomb));
            ICell context = cell.GetContext();

            Assert.AreEqual(!default(bool), context.Content is Bomb);
            Assert.AreEqual((CellState)default(int), context.State);
        }
        public void CalculateSurroundingBombsOnCellWithBombShouldReturnZero()
        {
            var contentFactory = new ContentFactory();
            var settings = new EasyBoardSettings();
            var subscribers = new List<IBoardObserver>()
            {
            };

            var board = new Board(settings, subscribers);
            this.FillBoard(board);

            board.Cells[default(int), default(int)].Content = contentFactory.GetContent(ContentType.Bomb);

            int result = board.CalculateNumberOfSurroundingBombs(default(int), default(int));

            Assert.AreEqual(default(int), result);
        }
Ejemplo n.º 4
0
        protected override void PersistUpdatedItem(IContent entity)
        {
            var publishedState = ((Content)entity).PublishedState;

            //check if we need to make any database changes at all
            if (entity.RequiresSaving(publishedState) == false)
            {
                entity.ResetDirtyProperties();
                return;
            }

            //check if we need to create a new version
            bool shouldCreateNewVersion = entity.ShouldCreateNewVersion(publishedState);

            if (shouldCreateNewVersion)
            {
                //Updates Modified date and Version Guid
                ((Content)entity).UpdatingEntity();
            }
            else
            {
                entity.UpdateDate = DateTime.Now;
            }

            //Ensure unique name on the same level
            entity.Name = EnsureUniqueNodeName(entity.ParentId, entity.Name, entity.Id);

            //Ensure that strings don't contain characters that are invalid in XML
            entity.SanitizeEntityPropertiesForXmlStorage();

            //Look up parent to get and set the correct Path and update SortOrder if ParentId has changed
            if (entity.IsPropertyDirty("ParentId"))
            {
                var parent = Database.First <NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
                entity.Path  = string.Concat(parent.Path, ",", entity.Id);
                entity.Level = parent.Level + 1;
                var maxSortOrder =
                    Database.ExecuteScalar <int>(
                        "SELECT coalesce(max(sortOrder),0) FROM umbracoNode WHERE parentid = @ParentId AND nodeObjectType = @NodeObjectType",
                        new { ParentId = entity.ParentId, NodeObjectType = NodeObjectTypeId });
                entity.SortOrder = maxSortOrder + 1;

                //Question: If we move a node, should we update permissions to inherit from the new parent if the parent has permissions assigned?
                // if we do that, then we'd need to propogate permissions all the way downward which might not be ideal for many people.
                // Gonna just leave it as is for now, and not re-propogate permissions.
            }

            var factory = new ContentFactory(NodeObjectTypeId, entity.Id);
            //Look up Content entry to get Primary for updating the DTO
            var contentDto = Database.SingleOrDefault <ContentDto>("WHERE nodeId = @Id", new { Id = entity.Id });

            factory.SetPrimaryKey(contentDto.PrimaryKey);
            var dto = factory.BuildDto(entity);

            //Updates the (base) node data - umbracoNode
            var nodeDto = dto.ContentVersionDto.ContentDto.NodeDto;
            var o       = Database.Update(nodeDto);

            //Only update this DTO if the contentType has actually changed
            if (contentDto.ContentTypeId != entity.ContentTypeId)
            {
                //Create the Content specific data - cmsContent
                var newContentDto = dto.ContentVersionDto.ContentDto;
                Database.Update(newContentDto);
            }

            //a flag that we'll use later to create the tags in the tag db table
            var publishedStateChanged = false;

            //If Published state has changed then previous versions should have their publish state reset.
            //If state has been changed to unpublished the previous versions publish state should also be reset.
            //if (((ICanBeDirty)entity).IsPropertyDirty("Published") && (entity.Published || publishedState == PublishedState.Unpublished))
            if (entity.ShouldClearPublishedFlagForPreviousVersions(publishedState, shouldCreateNewVersion))
            {
                var publishedDocs = Database.Fetch <DocumentDto>("WHERE nodeId = @Id AND published = @IsPublished", new { Id = entity.Id, IsPublished = true });
                foreach (var doc in publishedDocs)
                {
                    var docDto = doc;
                    docDto.Published = false;
                    Database.Update(docDto);
                }

                //this is a newly published version so we'll update the tags table too (end of this method)
                publishedStateChanged = true;
            }

            //Look up (newest) entries by id in cmsDocument table to set newest = false
            var documentDtos = Database.Fetch <DocumentDto>("WHERE nodeId = @Id AND newest = @IsNewest", new { Id = entity.Id, IsNewest = true });

            foreach (var documentDto in documentDtos)
            {
                var docDto = documentDto;
                docDto.Newest = false;
                Database.Update(docDto);
            }

            var contentVersionDto = dto.ContentVersionDto;

            if (shouldCreateNewVersion)
            {
                //Create a new version - cmsContentVersion
                //Assumes a new Version guid and Version date (modified date) has been set
                Database.Insert(contentVersionDto);
                //Create the Document specific data for this version - cmsDocument
                //Assumes a new Version guid has been generated
                Database.Insert(dto);
            }
            else
            {
                //In order to update the ContentVersion we need to retrieve its primary key id
                var contentVerDto = Database.SingleOrDefault <ContentVersionDto>("WHERE VersionId = @Version", new { Version = entity.Version });
                contentVersionDto.Id = contentVerDto.Id;

                Database.Update(contentVersionDto);
                Database.Update(dto);
            }

            //Create the PropertyData for this version - cmsPropertyData
            var propertyFactory  = new PropertyFactory(entity.ContentType.CompositionPropertyTypes.ToArray(), entity.Version, entity.Id);
            var propertyDataDtos = propertyFactory.BuildDto(entity.Properties);
            var keyDictionary    = new Dictionary <int, int>();

            //Add Properties
            foreach (var propertyDataDto in propertyDataDtos)
            {
                if (shouldCreateNewVersion == false && propertyDataDto.Id > 0)
                {
                    Database.Update(propertyDataDto);
                }
                else
                {
                    int primaryKey = Convert.ToInt32(Database.Insert(propertyDataDto));
                    keyDictionary.Add(propertyDataDto.PropertyTypeId, primaryKey);
                }
            }

            //Update Properties with its newly set Id
            if (keyDictionary.Any())
            {
                foreach (var property in entity.Properties)
                {
                    if (keyDictionary.ContainsKey(property.PropertyTypeId) == false)
                    {
                        continue;
                    }

                    property.Id = keyDictionary[property.PropertyTypeId];
                }
            }

            //lastly, check if we are a newly published version and then update the tags table
            if (publishedStateChanged && entity.Published)
            {
                UpdatePropertyTags(entity, _tagRepository);
            }
            else if (publishedStateChanged && (entity.Trashed || entity.Published == false))
            {
                //it's in the trash or not published remove all entity tags
                ClearEntityTags(entity, _tagRepository);
            }

            // published => update published version infos,
            // else if unpublished then clear published version infos
            if (entity.Published)
            {
                dto.DocumentPublishedReadOnlyDto = new DocumentPublishedReadOnlyDto
                {
                    VersionId = dto.VersionId,
                    Newest    = true,
                    NodeId    = dto.NodeId,
                    Published = true
                };
                ((Content)entity).PublishedVersionGuid = dto.VersionId;
            }
            else if (publishedStateChanged)
            {
                dto.DocumentPublishedReadOnlyDto = new DocumentPublishedReadOnlyDto
                {
                    VersionId = default(Guid),
                    Newest    = false,
                    NodeId    = dto.NodeId,
                    Published = false
                };
                ((Content)entity).PublishedVersionGuid = default(Guid);
            }

            entity.ResetDirtyProperties();
        }
Ejemplo n.º 5
0
        protected override void PersistNewItem(IContent entity)
        {
            ((Content)entity).AddingEntity();

            //ensure the default template is assigned
            if (entity.Template == null)
            {
                entity.Template = entity.ContentType.DefaultTemplate;
            }

            //Ensure unique name on the same level
            entity.Name = EnsureUniqueNodeName(entity.ParentId, entity.Name);

            //Ensure that strings don't contain characters that are invalid in XML
            entity.SanitizeEntityPropertiesForXmlStorage();

            var factory = new ContentFactory(NodeObjectTypeId, entity.Id);
            var dto     = factory.BuildDto(entity);

            //NOTE Should the logic below have some kind of fallback for empty parent ids ?
            //Logic for setting Path, Level and SortOrder
            var parent       = Database.First <NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
            var level        = parent.Level + 1;
            var maxSortOrder = Database.ExecuteScalar <int>(
                "SELECT coalesce(max(sortOrder),-1) FROM umbracoNode WHERE parentid = @ParentId AND nodeObjectType = @NodeObjectType",
                new { /*ParentId =*/ entity.ParentId, NodeObjectType = NodeObjectTypeId });
            var sortOrder = maxSortOrder + 1;

            //Create the (base) node data - umbracoNode
            var nodeDto = dto.ContentVersionDto.ContentDto.NodeDto;

            nodeDto.Path      = parent.Path;
            nodeDto.Level     = short.Parse(level.ToString(CultureInfo.InvariantCulture));
            nodeDto.SortOrder = sortOrder;
            var o = Database.IsNew(nodeDto) ? Convert.ToInt32(Database.Insert(nodeDto)) : Database.Update(nodeDto);

            //Update with new correct path
            nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
            Database.Update(nodeDto);

            //Update entity with correct values
            entity.Id        = nodeDto.NodeId; //Set Id on entity to ensure an Id is set
            entity.Path      = nodeDto.Path;
            entity.SortOrder = sortOrder;
            entity.Level     = level;

            //Assign the same permissions to it as the parent node
            // http://issues.umbraco.org/issue/U4-2161
            var permissionsRepo   = new PermissionRepository <IContent>(UnitOfWork, _cacheHelper, SqlSyntax);
            var parentPermissions = permissionsRepo.GetPermissionsForEntity(entity.ParentId).ToArray();

            //if there are parent permissions then assign them, otherwise leave null and permissions will become the
            // user's default permissions.
            if (parentPermissions.Any())
            {
                var userPermissions = (
                    from perm in parentPermissions
                    from p in perm.AssignedPermissions
                    select new EntityPermissionSet.UserPermission(perm.UserId, p)).ToList();

                permissionsRepo.ReplaceEntityPermissions(new EntityPermissionSet(entity.Id, userPermissions));
                //flag the entity's permissions changed flag so we can track those changes.
                //Currently only used for the cache refreshers to detect if we should refresh all user permissions cache.
                ((Content)entity).PermissionsChanged = true;
            }

            //Create the Content specific data - cmsContent
            var contentDto = dto.ContentVersionDto.ContentDto;

            contentDto.NodeId = nodeDto.NodeId;
            Database.Insert(contentDto);

            //Create the first version - cmsContentVersion
            //Assumes a new Version guid and Version date (modified date) has been set
            var contentVersionDto = dto.ContentVersionDto;

            contentVersionDto.NodeId = nodeDto.NodeId;
            Database.Insert(contentVersionDto);

            //Create the Document specific data for this version - cmsDocument
            //Assumes a new Version guid has been generated
            dto.NodeId = nodeDto.NodeId;
            Database.Insert(dto);

            //Create the PropertyData for this version - cmsPropertyData
            var propertyFactory  = new PropertyFactory(entity.ContentType.CompositionPropertyTypes.ToArray(), entity.Version, entity.Id);
            var propertyDataDtos = propertyFactory.BuildDto(entity.Properties);
            var keyDictionary    = new Dictionary <int, int>();

            //Add Properties
            foreach (var propertyDataDto in propertyDataDtos)
            {
                var primaryKey = Convert.ToInt32(Database.Insert(propertyDataDto));
                keyDictionary.Add(propertyDataDto.PropertyTypeId, primaryKey);
            }

            //Update Properties with its newly set Id
            foreach (var property in entity.Properties)
            {
                property.Id = keyDictionary[property.PropertyTypeId];
            }

            //lastly, check if we are a creating a published version , then update the tags table
            if (entity.Published)
            {
                UpdatePropertyTags(entity, _tagRepository);
            }

            // published => update published version infos, else leave it blank
            if (entity.Published)
            {
                dto.DocumentPublishedReadOnlyDto = new DocumentPublishedReadOnlyDto
                {
                    VersionId = dto.VersionId,
                    Newest    = true,
                    NodeId    = dto.NodeId,
                    Published = true
                };
                ((Content)entity).PublishedVersionGuid = dto.VersionId;
            }

            entity.ResetDirtyProperties();
        }
Ejemplo n.º 6
0
        public byte[] ReadData(PageType mode, int maxLength)
        {
            if (maxLength < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxLength));
            }

            if (cache.CacheType <= CacheType.Halo3Beta)
            {
                return(ReadDataHalo3Beta(mode, maxLength));
            }

            var resourceGestalt     = cache.TagIndex.GetGlobalTag("zone").ReadMetadata <cache_file_resource_gestalt>();
            var resourceLayoutTable = cache.TagIndex.GetGlobalTag("play").ReadMetadata <cache_file_resource_layout_table>();
            var entry = resourceGestalt.ResourceEntries[ResourceIndex];

            if (entry.SegmentIndex < 0)
            {
                throw new InvalidOperationException("Data not found");
            }

            var segment      = resourceLayoutTable.Segments[entry.SegmentIndex];
            var useSecondary = mode == PageType.Secondary || (mode == PageType.Auto && segment.SecondaryPageIndex >= 0);

            var pageIndex     = useSecondary ? segment.SecondaryPageIndex : segment.PrimaryPageIndex;
            var segmentOffset = useSecondary ? segment.SecondaryPageOffset : segment.PrimaryPageOffset;

            if (pageIndex < 0 || segmentOffset < 0)
            {
                throw new InvalidOperationException("Data not found");
            }

            var page = resourceLayoutTable.Pages[pageIndex];

            if (mode == PageType.Auto && (page.DataOffset < 0 || page.CompressedSize == 0))
            {
                pageIndex     = segment.PrimaryPageIndex;
                segmentOffset = segment.PrimaryPageOffset;
                page          = resourceLayoutTable.Pages[pageIndex];
            }

            var targetFile = cache.FileName;

            if (page.CacheIndex >= 0)
            {
                var directory = Directory.GetParent(cache.FileName).FullName;
                var mapName   = Utils.GetFileName(resourceLayoutTable.SharedCaches[page.CacheIndex].FileName);
                targetFile = Path.Combine(directory, mapName);
            }

            using (var fs = new FileStream(targetFile, FileMode.Open, FileAccess.Read))
                using (var reader = new EndianReader(fs, cache.ByteOrder))
                {
                    int dataTableAddress;
                    switch (cache.CacheType)
                    {
                    case CacheType.MccHalo3:
                    case CacheType.MccHalo3U4:
                    case CacheType.MccHalo3ODST:
                        if (page.CacheIndex >= 0)
                        {
                            dataTableAddress = 12288; //header size
                        }
                        else
                        {
                            reader.Seek(1208, SeekOrigin.Begin);
                            dataTableAddress = reader.ReadInt32();
                        }
                        break;

                    default:
                        reader.Seek(1136, SeekOrigin.Begin); //xbox
                        dataTableAddress = reader.ReadInt32();
                        break;
                    }

                    reader.Seek(dataTableAddress + page.DataOffset, SeekOrigin.Begin);
                    return(ContentFactory.GetResourceData(reader, cache.Metadata.ResourceCodec, maxLength, segmentOffset, page.CompressedSize, page.DecompressedSize));
                }
        }
Ejemplo n.º 7
0
        protected override void PersistUpdatedItem(IContent entity)
        {
            var publishedState = ((Content)entity).PublishedState;
            //A new version should only be created if published state (or language) has changed
            bool shouldCreateNewVersion = (((ICanBeDirty)entity).IsPropertyDirty("Published") && publishedState != PublishedState.Unpublished) || ((ICanBeDirty)entity).IsPropertyDirty("Language");

            if (shouldCreateNewVersion)
            {
                //Updates Modified date and Version Guid
                ((Content)entity).UpdatingEntity();
            }
            else
            {
                entity.UpdateDate = DateTime.Now;
            }

            //Look up parent to get and set the correct Path and update SortOrder if ParentId has changed
            if (((ICanBeDirty)entity).IsPropertyDirty("ParentId"))
            {
                var parent = Database.First <NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
                entity.Path  = string.Concat(parent.Path, ",", entity.Id);
                entity.Level = parent.Level + 1;
                var maxSortOrder =
                    Database.ExecuteScalar <int>(
                        "SELECT coalesce(max(sortOrder),0) FROM umbracoNode WHERE parentid = @ParentId AND nodeObjectType = @NodeObjectType",
                        new { ParentId = entity.ParentId, NodeObjectType = NodeObjectTypeId });
                entity.SortOrder = maxSortOrder + 1;
            }

            var factory = new ContentFactory(NodeObjectTypeId, entity.Id);
            //Look up Content entry to get Primary for updating the DTO
            var contentDto = Database.SingleOrDefault <ContentDto>("WHERE nodeId = @Id", new { Id = entity.Id });

            factory.SetPrimaryKey(contentDto.PrimaryKey);
            var dto = factory.BuildDto(entity);

            //Updates the (base) node data - umbracoNode
            var nodeDto = dto.ContentVersionDto.ContentDto.NodeDto;
            var o       = Database.Update(nodeDto);

            //Only update this DTO if the contentType has actually changed
            if (contentDto.ContentTypeId != entity.ContentTypeId)
            {
                //Create the Content specific data - cmsContent
                var newContentDto = dto.ContentVersionDto.ContentDto;
                Database.Update(newContentDto);
            }

            //If Published state has changed then previous versions should have their publish state reset.
            //If state has been changed to unpublished the previous versions publish state should also be reset.
            if (((ICanBeDirty)entity).IsPropertyDirty("Published") && (entity.Published || publishedState == PublishedState.Unpublished))
            {
                var publishedDocs = Database.Fetch <DocumentDto>("WHERE nodeId = @Id AND published = @IsPublished", new { Id = entity.Id, IsPublished = true });
                foreach (var doc in publishedDocs)
                {
                    var docDto = doc;
                    docDto.Published = false;
                    Database.Update(docDto);
                }
            }

            var contentVersionDto = dto.ContentVersionDto;

            if (shouldCreateNewVersion)
            {
                //Look up (newest) entries by id in cmsDocument table to set newest = false
                //NOTE: This is only relevant when a new version is created, which is why its done inside this if-statement.
                var documentDtos = Database.Fetch <DocumentDto>("WHERE nodeId = @Id AND newest = @IsNewest", new { Id = entity.Id, IsNewest = true });
                foreach (var documentDto in documentDtos)
                {
                    var docDto = documentDto;
                    docDto.Newest = false;
                    Database.Update(docDto);
                }

                //Create a new version - cmsContentVersion
                //Assumes a new Version guid and Version date (modified date) has been set
                Database.Insert(contentVersionDto);
                //Create the Document specific data for this version - cmsDocument
                //Assumes a new Version guid has been generated
                Database.Insert(dto);
            }
            else
            {
                //In order to update the ContentVersion we need to retreive its primary key id
                var contentVerDto = Database.SingleOrDefault <ContentVersionDto>("WHERE VersionId = @Version", new { Version = entity.Version });
                contentVersionDto.Id = contentVerDto.Id;

                Database.Update(contentVersionDto);
                Database.Update(dto);
            }

            //Create the PropertyData for this version - cmsPropertyData
            var propertyFactory  = new PropertyFactory(((Content)entity).ContentType, entity.Version, entity.Id);
            var propertyDataDtos = propertyFactory.BuildDto(entity.Properties);
            var keyDictionary    = new Dictionary <int, int>();

            //Add Properties
            foreach (var propertyDataDto in propertyDataDtos)
            {
                if (shouldCreateNewVersion == false && propertyDataDto.Id > 0)
                {
                    Database.Update(propertyDataDto);
                }
                else
                {
                    int primaryKey = Convert.ToInt32(Database.Insert(propertyDataDto));
                    keyDictionary.Add(propertyDataDto.PropertyTypeId, primaryKey);
                }
            }

            //Update Properties with its newly set Id
            if (keyDictionary.Any())
            {
                foreach (var property in entity.Properties)
                {
                    if (keyDictionary.ContainsKey(property.PropertyTypeId) == false)
                    {
                        continue;
                    }

                    property.Id = keyDictionary[property.PropertyTypeId];
                }
            }

            ((ICanBeDirty)entity).ResetDirtyProperties();
        }
Ejemplo n.º 8
0
        protected override void PersistNewItem(IContent entity)
        {
            ((Content)entity).AddingEntity();

            //Ensure unique name on the same level
            entity.Name = EnsureUniqueNodeName(entity.ParentId, entity.Name);

            var factory = new ContentFactory(NodeObjectTypeId, entity.Id);
            var dto     = factory.BuildDto(entity);

            //NOTE Should the logic below have some kind of fallback for empty parent ids ?
            //Logic for setting Path, Level and SortOrder
            var parent    = Database.First <NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
            int level     = parent.Level + 1;
            int sortOrder =
                Database.ExecuteScalar <int>("SELECT COUNT(*) FROM umbracoNode WHERE parentID = @ParentId AND nodeObjectType = @NodeObjectType",
                                             new { ParentId = entity.ParentId, NodeObjectType = NodeObjectTypeId });

            //Create the (base) node data - umbracoNode
            var nodeDto = dto.ContentVersionDto.ContentDto.NodeDto;

            nodeDto.Path      = parent.Path;
            nodeDto.Level     = short.Parse(level.ToString(CultureInfo.InvariantCulture));
            nodeDto.SortOrder = sortOrder;
            var o = Database.IsNew(nodeDto) ? Convert.ToInt32(Database.Insert(nodeDto)) : Database.Update(nodeDto);

            //Update with new correct path
            nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
            Database.Update(nodeDto);

            //Update entity with correct values
            entity.Id        = nodeDto.NodeId; //Set Id on entity to ensure an Id is set
            entity.Path      = nodeDto.Path;
            entity.SortOrder = sortOrder;
            entity.Level     = level;


            //Assign the same permissions to it as the parent node
            // http://issues.umbraco.org/issue/U4-2161
            var parentPermissions = GetPermissionsForEntity(entity.ParentId).ToArray();

            //if there are parent permissions then assign them, otherwise leave null and permissions will become the
            // user's default permissions.
            if (parentPermissions.Any())
            {
                var userPermissions = parentPermissions.Select(
                    permissionDto => new KeyValuePair <object, string>(
                        permissionDto.UserId,
                        permissionDto.Permission));
                AssignEntityPermissions(entity, userPermissions);
                //flag the entity's permissions changed flag so we can track those changes.
                //Currently only used for the cache refreshers to detect if we should refresh all user permissions cache.
                ((Content)entity).PermissionsChanged = true;
            }

            //Create the Content specific data - cmsContent
            var contentDto = dto.ContentVersionDto.ContentDto;

            contentDto.NodeId = nodeDto.NodeId;
            Database.Insert(contentDto);

            //Create the first version - cmsContentVersion
            //Assumes a new Version guid and Version date (modified date) has been set
            var contentVersionDto = dto.ContentVersionDto;

            contentVersionDto.NodeId = nodeDto.NodeId;
            Database.Insert(contentVersionDto);

            //Create the Document specific data for this version - cmsDocument
            //Assumes a new Version guid has been generated
            dto.NodeId = nodeDto.NodeId;
            Database.Insert(dto);

            //Create the PropertyData for this version - cmsPropertyData
            var propertyFactory  = new PropertyFactory(entity.ContentType, entity.Version, entity.Id);
            var propertyDataDtos = propertyFactory.BuildDto(entity.Properties);
            var keyDictionary    = new Dictionary <int, int>();

            //Add Properties
            foreach (var propertyDataDto in propertyDataDtos)
            {
                var primaryKey = Convert.ToInt32(Database.Insert(propertyDataDto));
                keyDictionary.Add(propertyDataDto.PropertyTypeId, primaryKey);
            }

            //Update Properties with its newly set Id
            foreach (var property in entity.Properties)
            {
                property.Id = keyDictionary[property.PropertyTypeId];
            }

            ((ICanBeDirty)entity).ResetDirtyProperties();
        }
 /// <summary>
 /// A method for filling the playing board with cells 
 /// </summary>
 /// <param name="board">The current playing board to be filled</param>
 private void FillBoard(IBoard board)
 {
     var contentFactory = new ContentFactory();
     for (var row = 0; row < board.Rows; row++)
     {
         for (int col = 0; col < board.Cols; col++)
         {
             board.Cells[row, col] = new Cell()
                 .SetContent(contentFactory.GetContent(ContentType.Empty))
                 .SetState(CellState.Sealed)
                 .GetContext();
         }
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Start Game logic
        /// </summary>
        public void Start()
        {
            // Initialize the two basic objects needed for user interactions
            this.InputProvider = this.inputProvider ?? new ConsoleInputProvider();
            this.OutputRenderer = this.outputRenderer ?? new ConsoleRenderer();

            // Render initial UI
            this.OutputRenderer.RenderWelcomeScreen(string.Join(string.Empty, RenderersConstants.GameTitle));
            this.OutputRenderer.RenderNewPlayerCreationRequest();

            // Create the active player
            var player = new Player(this.InputProvider.ReceiveInputLine());

            // Render console menu handler and execute logic for requesting board settings
            // TODO: Refactor menu handler logic
            int[] cursorPosition = this.OutputRenderer.GetCursor();
            var menuItems = new List<IGameMode>()
            {
                new BeginnerMode(),
                new IntermediateMode(),
                new ExpertMode()
            };

            var menuHandler = new ConsoleMenuHandler(this.inputProvider, this.outputRenderer, menuItems, cursorPosition[0] + 1, cursorPosition[1]);

            menuHandler.ShowSelections();

            BoardSettings boardSettings = menuHandler.RequestUserSelection();
            this.OutputRenderer.ClearScreen();
            this.OutputRenderer.SetCursor(visible: true);
            //// End of menu handler logic

            var board = new Board(boardSettings, new List<IBoardObserver>());
            var scoreboard = new Scoreboard();
            var contentFactory = new ContentFactory();
            var initializationStrategy = new StandardGameInitializationStrategy(contentFactory);
            var boardOperator = new CommandOperator(board, scoreboard);
            var engine = new StandardOnePlayerMinesweeperEngine(board, this.inputProvider, this.outputRenderer, boardOperator, scoreboard, player);

            engine.Initialize(initializationStrategy);
            board.Subscribe(engine);
            engine.Run();
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Creates a new region.
 /// </summary>
 /// <param name="api">The current api</param>
 /// <param name="typeId">The page type id</param>
 /// <param name="regionId">The region id</param>
 /// <returns>The new region value</returns>
 public static object CreateRegion(IApi api, string typeId, string regionId)
 {
     using (var factory = new ContentFactory(api.PageTypes.GetAll())) {
         return(factory.CreateDynamicRegion(typeId, regionId));
     }
 }
Ejemplo n.º 12
0
        private List <Entity> GetGeometry(DeferredRenderer renderer)
        {
            IShaderProgram defaultShader = renderer.GetShader(DeferredRenderer.DrawableType.deferredDefaultMesh);
            List <Entity>  res           = new List <Entity>();
            float          islandScale   = 30f;
            var            islePlane     = Meshes.CreatePlane(30, 30, 120, 120).Transform(Transformation.Translation(0, islandScale / 2, 0));
            Renderable     isle          = ContentFactory.GetDefaultRenderable(renderer, islePlane);


            ITexture2D isleAlbedo = contentLoader.Load <ITexture2D>("terrain.png");

            isleAlbedo.Filter = TextureFilterMode.Linear;
            //ITexture2D isleNormal = contentLoader.Load<ITexture2D>("normalTest1.jpg");
            isle.SetAlbedoTexture(isleAlbedo);
            //isle.SetNormalMap(isleNormal);
            ITexture2D isleHeightmap = contentLoader.Load <ITexture2D>("hmapUnity.png");

            isle.SetHeightMap(isleHeightmap);
            isle.heightScaleFactor = islandScale;
            Entity isleEntity = new Entity();

            isleEntity.name       = "isle";
            isleEntity.renderable = isle;

            Terrain isleTerrain = new Terrain(contentLoader, "hmapUnity.png", islandScale, 30, 30);

            isleTerrain.transform.position = new Vector3(0, islandScale / 2, 0);



            var        waterplane       = Meshes.CreatePlane(100, 100, 225, 225).Transform(Transformation.Translation(0, 1f, 0));
            VAO        waterDrawable    = renderer.GetDrawable(waterplane, DeferredRenderer.DrawableType.deferredDefaultMesh);
            Renderable water            = ContentFactory.GetDefaultRenderable(renderer, waterplane);
            ITexture2D waterEnvironment = contentLoader.Load <ITexture2D>("sky_low.jpg");

            water.SetEnvironmentMap(waterEnvironment);
            water.reflectivity = 1;
            //water.SetAlbedoTexture(isleAlbedo);
            Entity waterEntity = new Entity();

            waterEntity.name       = "water";
            waterEntity.renderable = water;

            var        grassPlane = Meshes.CreatePlane(1, 1, 2, 2).Transform(Transformation.Rotation(-90, Axis.X));
            Renderable grass      = ContentFactory.GetDefaultRenderable(renderer, grassPlane);

            grass.faceCullingMode = FaceCullingMode.NONE;
            ITexture2D grassAlbedo = contentLoader.Load <ITexture2D>("Grass_512_albedo.tif");
            ITexture2D grassAlpha  = contentLoader.Load <ITexture2D>("tGrass_512_alpha.tif");

            grass.SetAlbedoTexture(grassAlbedo);
            grass.SetAlphaMap(grassAlpha);
            //Entity grassEntity = new Entity();
            //grassEntity.renderable = grass;
            Vector3[]    spawnPositions = { new Vector3(-0.1f, 7.1f, 2.5f), new Vector3(-3.5f, 7.1f, -1.5f),
                                            new Vector3(6f,       7.1f, 2.5f), new Vector3(6f,    7.1f, -1.5f),new Vector3(5f,7.1f, -6f), new Vector3(1f, 7.1f, -8f), new Vector3(-3f, 7.1f, -8f) };
            float[]      radius      = { 2f, 1.9f, 2f, 2f, 2f, 2f, 2f };
            int[]        amountGrass = { 50, 60, 50, 60, 60, 60, 60 };
            Range3D      scaleRange  = new Range3D(new Vector3(0.5f), new Vector3(1.5f));
            TerrainLayer layer       = new TerrainLayer(isleTerrain, grass);

            for (int i = 0; i < spawnPositions.Length; i++)
            {
                SphericalTerrainSpawner grassSpawner = new SphericalTerrainSpawner(spawnPositions[i], radius[i], amountGrass[i]);
                grassSpawner.randomScaleRange = scaleRange;
                layer.AddSpawner(grassSpawner);
            }
            layer.SpawnElements();
            res.Add(layer);
            var skysphere = Meshes.CreateSphere(60, 2);

            skysphere.SwitchTriangleMeshWinding();
            Renderable skydome = ContentFactory.GetDefaultRenderable(renderer, skysphere);

            skydome.faceCullingMode = FaceCullingMode.FRONT_SIDE;
            skydome.unlit           = 1;
            skydome.SetAlbedoTexture(waterEnvironment);
            Entity skyEntity = new Entity();

            skyEntity.renderable = skydome;
            skyEntity.name       = "skydome";

            var        msphere = Meshes.CreateSphere(1, 2).Transform(Transformation.Translation(0, 2, 0));
            Renderable sphere  = ContentFactory.GetDefaultRenderable(renderer, msphere);
            VAO        spVao   = renderer.GetDrawable(msphere, DeferredRenderer.DrawableType.deferredDefaultMesh);

            sphere.SetEnvironmentMap(waterEnvironment);
            Entity spEntity = new Entity();

            spEntity.name       = "sphere";
            spEntity.renderable = sphere;

            //res.Add(grassEntity);
            res.Add(isleEntity);
            res.Add(waterEntity);
            //res.Add(spEntity);
            res.Add(skyEntity);
            return(res);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Creates a new region.
 /// </summary>
 /// <param name="typeId">The block type id</param>
 /// <param name="regionId">The region id</param>
 /// <returns>The new region value</returns>
 public static object CreateRegion(string typeId, string regionId)
 {
     using (var factory = new ContentFactory(App.BlockTypes)) {
         return(factory.CreateRegion(typeId, regionId));
     }
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Creates a new block model using the given block type id.
 /// </summary>
 /// <param name="typeId">The unique block type id</param>
 /// <returns>The new model</returns>
 public static T Create(string typeId)
 {
     using (var factory = new ContentFactory(App.BlockTypes)) {
         return(factory.Create <T>(typeId));
     }
 }
Ejemplo n.º 15
0
 public void FixtureSetUp()
 {
     _contentFactory = new ContentFactory(_services);
     Initialize();
 }
 public StandardGameInitializationStrategy(ContentFactory contentFactory)
 {
     this.contentFactory = contentFactory;
 }
Ejemplo n.º 17
0
 protected override HttpInteraction GetHttpInteraction(string resource)
 {
     return(Put.DataAsJson(ContentFactory.SomeContent()).To(resource));
 }
Ejemplo n.º 18
0
        protected override void PersistNewItem(IContent entity)
        {
            ((Content)entity).AddingEntity();

            var factory = new ContentFactory(NodeObjectTypeId, entity.Id);
            var dto     = factory.BuildDto(entity);

            //NOTE Should the logic below have some kind of fallback for empty parent ids ?
            //Logic for setting Path, Level and SortOrder
            var parent    = Database.First <NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
            int level     = parent.Level + 1;
            int sortOrder =
                Database.ExecuteScalar <int>("SELECT COUNT(*) FROM umbracoNode WHERE parentID = @ParentId AND nodeObjectType = @NodeObjectType",
                                             new { ParentId = entity.ParentId, NodeObjectType = NodeObjectTypeId });

            //Create the (base) node data - umbracoNode
            var nodeDto = dto.ContentVersionDto.ContentDto.NodeDto;

            nodeDto.Path      = parent.Path;
            nodeDto.Level     = short.Parse(level.ToString(CultureInfo.InvariantCulture));
            nodeDto.SortOrder = sortOrder;
            var o = Database.IsNew(nodeDto) ? Convert.ToInt32(Database.Insert(nodeDto)) : Database.Update(nodeDto);

            //Update with new correct path
            nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
            Database.Update(nodeDto);

            //Update entity with correct values
            entity.Id        = nodeDto.NodeId; //Set Id on entity to ensure an Id is set
            entity.Path      = nodeDto.Path;
            entity.SortOrder = sortOrder;
            entity.Level     = level;

            //Create the Content specific data - cmsContent
            var contentDto = dto.ContentVersionDto.ContentDto;

            contentDto.NodeId = nodeDto.NodeId;
            Database.Insert(contentDto);

            //Create the first version - cmsContentVersion
            //Assumes a new Version guid and Version date (modified date) has been set
            var contentVersionDto = dto.ContentVersionDto;

            contentVersionDto.NodeId = nodeDto.NodeId;
            Database.Insert(contentVersionDto);

            //Create the Document specific data for this version - cmsDocument
            //Assumes a new Version guid has been generated
            dto.NodeId = nodeDto.NodeId;
            Database.Insert(dto);

            //Create the PropertyData for this version - cmsPropertyData
            var propertyFactory  = new PropertyFactory(entity.ContentType, entity.Version, entity.Id);
            var propertyDataDtos = propertyFactory.BuildDto(entity.Properties);
            var keyDictionary    = new Dictionary <int, int>();

            //Add Properties
            foreach (var propertyDataDto in propertyDataDtos)
            {
                var primaryKey = Convert.ToInt32(Database.Insert(propertyDataDto));
                keyDictionary.Add(propertyDataDto.PropertyTypeId, primaryKey);
            }

            //Update Properties with its newly set Id
            foreach (var property in entity.Properties)
            {
                property.Id = keyDictionary[property.PropertyTypeId];
            }

            ((ICanBeDirty)entity).ResetDirtyProperties();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Start Game logic
        /// </summary>
        public void Start(Grid root)
        {
            // Initialize the two basic objects needed for user interactions
            this.InputProvider = this.inputProvider ?? new WpfInputProvider();
            this.OutputRenderer = this.outputRenderer ?? new WpfRenderer(root);

            string testPlayerName = "John";

            // Create the active player
            var player = new Player(testPlayerName);

            BoardSettings testBoardSettings = new EasyBoardSettings();

            var board = new Board(testBoardSettings, new List<IBoardObserver>());
            var scoreboard = new Scoreboard();
            var contentFactory = new ContentFactory();
            var initializationStrategy = new StandardGameInitializationStrategy(contentFactory);
            var boardOperator = new CommandOperator(board, scoreboard);
            var engine = new StandardOnePlayerMinesweeperEngine(board, this.inputProvider, this.outputRenderer, boardOperator, scoreboard, player);

            engine.Initialize(initializationStrategy);
            board.Subscribe(engine);
            engine.Run();
        }