private void BlockField_CreateDataBlock(BlockField field, long baseOffset, ref long offset) { //Create a condensed block if (field.BlockList.Count > 0) { //Prepare ITagBlock block = field.BlockList[0]; int localOffset = (int)(field.BlockAddress - baseOffset); //Create using (VirtualStream vs = new VirtualStream(offset)) using (BinaryWriter writer = new BinaryWriter(vs)) { //Align vs.Align(block.Alignment); //Write foreach (ITagBlock child in field.BlockList) { child.Write(writer); } //Add tagBlockView.Blocks.Add(localOffset, (int)vs.Length, block.BlockName); offset = field.BlockAddress + vs.Length; } } //Create child blocks foreach (ITagBlock block in field.BlockList) { TagBlock_CreateChildBlocks(block, baseOffset, ref offset); } }
private TreeNode BlockField_CreateTreeNode(BlockField blockField) { //Prepare string displayName = blockField.Name; if (string.IsNullOrEmpty(displayName)) { displayName = $"unnamed ({blockField.Create().BlockName})"; } //Create tag block tree node TreeNode fieldNode = new TreeNode(displayName) { Tag = blockField }; //Add children foreach (Block tagBlock in blockField.BlockList) { fieldNode.Nodes.Add(TagBlock_CreateTreeNode(tagBlock)); } //Return return(fieldNode); }
private void TagBlock_CreateChildBlocks(ITagBlock block, long baseOffset, ref long offset) { //Loop through fields foreach (Field field in block) { switch (field.Type) { case FieldType.FieldStruct: StructField structField = (StructField)field; TagBlock_CreateChildBlocks((ITagBlock)structField.Value, baseOffset, ref offset); break; case FieldType.FieldBlock: BlockField blockField = (BlockField)field; BlockField_CreateDataBlock(blockField, baseOffset, ref offset); break; case FieldType.FieldData: DataField dataField = (DataField)field; int localOffset = (int)(dataField.DataAddress - baseOffset); tagBlockView.Blocks.Add(localOffset, dataField.BufferLength, block.BlockName); offset = dataField.DataAddress + dataField.BufferLength; break; } } }
/// <summary> /// Transforms the given blocks to the internal data model. /// </summary> /// <param name="models">The blocks</param> /// <returns>The data model</returns> public IList <Block> TransformBlocks(IList <Extend.Block> models) { var blocks = new List <Block>(); if (models != null) { for (var n = 0; n < models.Count; n++) { var type = App.Blocks.GetByType(models[n].GetType().FullName); if (type != null) { var block = new Block() { Id = models[n].Id != Guid.Empty ? models[n].Id : Guid.NewGuid(), CLRType = models[n].GetType().FullName, Created = DateTime.Now, LastModified = DateTime.Now }; foreach (var prop in models[n].GetType().GetProperties(App.PropertyBindings)) { if (typeof(Extend.IField).IsAssignableFrom(prop.PropertyType)) { // Only save fields to the database var field = new BlockField() { Id = Guid.NewGuid(), BlockId = block.Id, FieldId = prop.Name, SortOrder = 0, CLRType = prop.PropertyType.FullName, Value = App.SerializeObject(prop.GetValue(models[n]), prop.PropertyType) }; block.Fields.Add(field); } } blocks.Add(block); if (typeof(Extend.BlockGroup).IsAssignableFrom(models[n].GetType())) { var blockItems = TransformBlocks(((Extend.BlockGroup)models[n]).Items); if (blockItems.Count() > 0) { foreach (var item in blockItems) { item.ParentId = block.Id; } blocks.AddRange(blockItems); } } } } } return(blocks); }
public async Task <IList <dynamic> > RenderAsync(BlockField field) { return(await RenderAsync(new BlockParserContext { ContentItem = field.ContentItem, HttpContext = _httpContextAccessor.HttpContext, LiquidTemplateManager = _liquidTemplateManager, ShapeFactory = _shapeFactory }, field.Data)); }
public DocxDocumentBlockFieldContextBuilder(WordprocessingDocument document, string fieldName) : base(document) { _documentFields = BlockField.Get(document, fieldName); foreach (var blockField in _documentFields) { blockField.ContentWrapper.RemoveAllChildren(); } SaveDocument(); }
public void CollectResources(ITagBlock tagBlock) { //Check if (tagBlock == null) { throw new ArgumentNullException(nameof(tagBlock)); } //Loop through fields foreach (Field field in tagBlock) { //Get value string value = field.Value?.ToString() ?? string.Empty; BlockField blockField = field as BlockField; //Handle type switch (field.Type) { case FieldType.FieldStruct: CollectResources((ITagBlock)field.Value); break; case FieldType.FieldBlock: foreach (ITagBlock nestedTagBlock in blockField.BlockList) { CollectResources(nestedTagBlock); } break; case FieldType.FieldOldStringId: case FieldType.FieldStringId: if (!string.IsNullOrEmpty(value) && !m_StringsList.Contains(value)) { m_StringsList.Add(value); } break; case FieldType.FieldTagIndex: case FieldType.FieldTagReference: if (!string.IsNullOrEmpty(value) && !m_ResourceList.Contains(value)) { m_ResourceList.Add(value); CollectResources(ResolveResource.Invoke(value)); } break; } } }
private static Group Bitmap_ToGuerilla(Group cacheBitmap, TagResourceContainer data, HaloMap map) { Group bitmap = new Abide.Tag.Guerilla.Generated.Bitmap(); Block cacheBitmapBlock = cacheBitmap.TagBlocks[0]; Block bitmapBlock = bitmap.TagBlocks[0]; using (MemoryStream ms = new MemoryStream()) using (BinaryWriter bitmapDataWriter = new BinaryWriter(ms)) { BlockField cacheSequences = (BlockField)cacheBitmapBlock.Fields[28]; BlockField cacheBitmaps = (BlockField)cacheBitmapBlock.Fields[29]; BlockField sequences = (BlockField)bitmapBlock.Fields[28]; BlockField bitmaps = (BlockField)bitmapBlock.Fields[29]; for (int i = 0; i < 28; i++) { if (bitmapBlock.Fields[i].Type != FieldType.FieldData) { bitmapBlock.Fields[i].Value = cacheBitmapBlock.Fields[i].Value; } } foreach (Block cacheBitmapSequenceBlock in cacheSequences.BlockList) { if (sequences.AddNew(out Block bitmapSequenceBlock)) { TagBlock_ToGuerilla(bitmapSequenceBlock, cacheBitmapSequenceBlock, map); } } foreach (Block cacheBitmapDataBlock in cacheBitmaps.BlockList) { if (bitmaps.AddNew(out Block bitmapDataBlock)) { TagBlock_ToGuerilla(bitmapDataBlock, cacheBitmapDataBlock, map); } } } return(bitmap); }
// Modify: modify a packet private Packet Modify(Packet packet, IPEndPoint endPoint, Direction direction) { if (modifiedPackets.ContainsKey(packet.Type)) { try { Dictionary <BlockField, object> changes = modifiedPackets[packet.Type]; Type packetClass = packet.GetType(); foreach (KeyValuePair <BlockField, object> change in changes) { BlockField bf = change.Key; FieldInfo blockField = packetClass.GetField(bf.block); if (blockField.FieldType.IsArray) // We're modifying a variable block. { // Modify each block in the variable block identically. // This is really simple, can probably be improved. object[] blockArray = (object[])blockField.GetValue(packet); foreach (object blockElement in blockArray) { MagicSetField(blockElement, bf.field, change.Value); } } else { //Type blockClass = blockField.FieldType; object blockObject = blockField.GetValue(packet); MagicSetField(blockObject, bf.field, change.Value); } } } catch (Exception e) { Console.WriteLine("failed to modify " + packet.Type + ": " + e.Message); Console.WriteLine(e.StackTrace); } } return(packet); }
public static TagBlockList FromBlockField(BlockField blockField, int index, int count) { int addedCount = 0; var block = blockField.Create(); var data = new TagBlockList() { BlockName = block.Name }; for (int i = 0; i < count; i++) { int currentIndex = index + i; if (currentIndex < blockField.BlockList.Count) { data.blocks.Add((Block)blockField.BlockList[currentIndex].Clone()); addedCount++; } } data.Count = addedCount; return(data); }
/// <summary> /// Saves the given page model /// </summary> /// <param name="model">The page model</param> public void Save <T>(T model) where T : Models.PageBase { var type = api.PageTypes.GetById(model.TypeId); if (type != null) { // Ensure that we have a slug if (string.IsNullOrWhiteSpace(model.Slug)) { var prefix = ""; // Check if we should generate hierarchical slugs using (var config = new Config(api)) { if (config.HierarchicalPageSlugs && model.ParentId.HasValue) { var parentSlug = db.Pages .AsNoTracking() .FirstOrDefault(p => p.Id == model.ParentId)?.Slug; if (!string.IsNullOrWhiteSpace(parentSlug)) { prefix = parentSlug + "/"; } } model.Slug = prefix + Utils.GenerateSlug(model.NavigationTitle != null ? model.NavigationTitle : model.Title); } } else { model.Slug = Utils.GenerateSlug(model.Slug); } // Set content type model.ContentType = type.ContentTypeId; var page = db.Pages .Include(p => p.Blocks).ThenInclude(b => b.Block).ThenInclude(b => b.Fields) .Include(p => p.Fields) .FirstOrDefault(p => p.Id == model.Id); // Transform the model if (page == null) { page = new Page() { Id = model.Id != Guid.Empty ? model.Id : Guid.NewGuid(), ParentId = model.ParentId, SortOrder = model.SortOrder, PageTypeId = model.TypeId, Created = DateTime.Now, LastModified = DateTime.Now }; db.Pages.Add(page); model.Id = page.Id; // Make room for the new page MovePages(page.Id, model.SiteId, model.ParentId, model.SortOrder, true); } else { // Check if the page has been moved if (page.ParentId != model.ParentId || page.SortOrder != model.SortOrder) { // Remove the old position for the page MovePages(page.Id, page.SiteId, page.ParentId, page.SortOrder + 1, false); // Add room for the new position of the page MovePages(page.Id, model.SiteId, model.ParentId, model.SortOrder, true); } page.LastModified = DateTime.Now; } page = contentService.Transform <T>(model, type, page); // Transform blocks IList <Extend.Block> blockModels = null; if (model is Models.IPage) { blockModels = ((Models.IPage)model).Blocks; } else if (model is Models.IDynamicPage) { blockModels = ((Models.IDynamicPage)model).Blocks; } if (blockModels != null && blockModels.Count > 0) { var blocks = contentService.TransformBlocks(blockModels); var current = blocks.Select(b => b.Id).ToArray(); // Delete removed blocks var removed = page.Blocks .Where(b => !current.Contains(b.BlockId) && !b.Block.IsReusable) .Select(b => b.Block); db.Blocks.RemoveRange(removed); // Delete the old page blocks page.Blocks.Clear(); // Now map the new block for (var n = 0; n < blocks.Count; n++) { var block = db.Blocks .Include(b => b.Fields) .FirstOrDefault(b => b.Id == blocks[n].Id); if (block == null) { block = new Block() { Id = blocks[n].Id != Guid.Empty ? blocks[n].Id : Guid.NewGuid(), Created = DateTime.Now }; db.Blocks.Add(block); } block.CLRType = blocks[n].CLRType; block.IsReusable = blocks[n].IsReusable; block.Title = blocks[n].Title; block.LastModified = DateTime.Now; var currentFields = blocks[n].Fields.Select(f => f.FieldId).Distinct(); var removedFields = block.Fields.Where(f => !currentFields.Contains(f.FieldId)); db.BlockFields.RemoveRange(removedFields); foreach (var newField in blocks[n].Fields) { var field = block.Fields.FirstOrDefault(f => f.FieldId == newField.FieldId); if (field == null) { field = new BlockField() { Id = newField.Id != Guid.Empty ? newField.Id : Guid.NewGuid(), BlockId = block.Id, FieldId = newField.FieldId }; db.BlockFields.Add(field); block.Fields.Add(field); } field.SortOrder = newField.SortOrder; field.CLRType = newField.CLRType; field.Value = newField.Value; } // Create the page block page.Blocks.Add(new PageBlock() { Id = Guid.NewGuid(), BlockId = block.Id, Block = block, PageId = page.Id, SortOrder = n }); } } db.SaveChanges(); if (cache != null) { RemoveFromCache(page); } InvalidateSitemap(model.SiteId); } }
private static void TagBlock_ToGuerilla(Block guerilla, Block cache, HaloMap map) { if (guerilla.Name != cache.Name) { return; } string tagPath; Group tagGroup; for (int i = 0; i < guerilla.FieldCount; i++) { if (guerilla.Fields[i].Type != cache.Fields[i].Type) { continue; } switch (cache.Fields[i]) { case Abide.Tag.Cache.BaseStringIdField stringField: if (map.Strings.Count > stringField.Id.Index) { string stringId = map.Strings[stringField.Id.Index] ?? string.Empty; guerilla.Fields[i].Value = stringId; } break; case Abide.Tag.Cache.TagReferenceField tagReferenceField: if (map.IndexEntries.ContainsId(tagReferenceField.Reference.Id)) { tagGroup = Abide.Tag.Guerilla.Generated.TagLookup.CreateTagGroup(map.IndexEntries[tagReferenceField.Reference.Id].Root); tagPath = $@"{map.IndexEntries[tagReferenceField.Reference.Id].Filename}.{tagGroup.Name}"; guerilla.Fields[i].Value = tagPath; } break; case Abide.Tag.Cache.TagIndexField tagIndexField: if (map.IndexEntries.ContainsId(tagIndexField.Id)) { tagGroup = Abide.Tag.Guerilla.Generated.TagLookup.CreateTagGroup(map.IndexEntries[tagIndexField.Id].Root); tagPath = $@"{map.IndexEntries[tagIndexField.Id].Filename}.{tagGroup.Name}"; guerilla.Fields[i].Value = tagPath; } break; case BlockField cacheBlockField: BlockField guerillaBlockField = (BlockField)guerilla.Fields[i]; for (int j = 0; j < cacheBlockField.BlockList.Count; j++) { if (guerillaBlockField.AddNew(out Block guerillaBlock)) { TagBlock_ToGuerilla(guerillaBlock, cacheBlockField.BlockList[j], map); } } break; case StructField cacheStructField: StructField guerillaStructField = (StructField)guerilla.Fields[i]; TagBlock_ToGuerilla(guerillaStructField.Block, cacheStructField.Block, map); break; case DataField cacheDataField: DataField guerillaDataField = (DataField)guerilla.Fields[i]; guerillaDataField.SetBuffer(cacheDataField.GetBuffer()); break; default: guerilla.Fields[i].Value = cache.Fields[i].Value; break; } } }
private static Group CacheFileSound_ToGuerilla(Group cacheFileSound, Group soundCacheFileGestalt, HaloMap map) { Group sound = new Abide.Tag.Guerilla.Generated.Sound(); Block soundCacheFileGestaltBlock = soundCacheFileGestalt.TagBlocks[0]; Block cacheFileSoundBlock = cacheFileSound.TagBlocks[0]; Block soundBlock = sound.TagBlocks[0]; BlockField playbacks = (BlockField)soundCacheFileGestaltBlock.Fields[0]; BlockField scales = (BlockField)soundCacheFileGestaltBlock.Fields[1]; BlockField importNames = (BlockField)soundCacheFileGestaltBlock.Fields[2]; BlockField pitchRangeParameters = (BlockField)soundCacheFileGestaltBlock.Fields[3]; BlockField pitchRanges = (BlockField)soundCacheFileGestaltBlock.Fields[4]; BlockField permutations = (BlockField)soundCacheFileGestaltBlock.Fields[5]; BlockField customPlaybacks = (BlockField)soundCacheFileGestaltBlock.Fields[6]; BlockField chunks = (BlockField)soundCacheFileGestaltBlock.Fields[8]; BlockField promotions = (BlockField)soundCacheFileGestaltBlock.Fields[9]; BlockField extraInfos = (BlockField)soundCacheFileGestaltBlock.Fields[10]; soundBlock.Fields[0].Value = (int)(short)cacheFileSoundBlock.Fields[0].Value; // flags soundBlock.Fields[1].Value = cacheFileSoundBlock.Fields[1].Value; // class soundBlock.Fields[2].Value = cacheFileSoundBlock.Fields[2].Value; // sample rate soundBlock.Fields[9].Value = cacheFileSoundBlock.Fields[3].Value; // encoding soundBlock.Fields[10].Value = cacheFileSoundBlock.Fields[4].Value; // compression using (MemoryStream ms = new MemoryStream((byte[])soundBlock.Fields[12].Value)) // padding field using (BinaryWriter writer = new BinaryWriter(ms)) { writer.Write((int)cacheFileSoundBlock.Fields[12].Value); // maximum play time writer.Write((byte)cacheFileSoundBlock.Fields[9].Value); // promotion index } if ((short)cacheFileSoundBlock.Fields[5].Value != nullShortIndex) // playback short index { Block playback = playbacks.BlockList[(short)cacheFileSoundBlock.Fields[5].Value]; soundBlock.Fields[5].Value = playback.Fields[0].Value; // playback parameters } if ((byte)cacheFileSoundBlock.Fields[8].Value != nullByteIndex) // scale byte index { Block scale = scales.BlockList[(byte)cacheFileSoundBlock.Fields[8].Value]; soundBlock.Fields[6].Value = scale.Fields[0].Value; // scale } if ((byte)cacheFileSoundBlock.Fields[9].Value != nullByteIndex) // promotion byte index { Block promotion = promotions.BlockList[(byte)cacheFileSoundBlock.Fields[9].Value]; soundBlock.Fields[11].Value = promotion.Fields[0].Value; // platform parameters } if ((byte)cacheFileSoundBlock.Fields[10].Value != nullByteIndex) // custom playback byte index { BlockField platformParameters = (BlockField)soundBlock.Fields[14]; if (platformParameters.AddNew(out Block soundPlatformPlaybackBlock)) { Block customPlayback = customPlaybacks.BlockList[(byte)cacheFileSoundBlock.Fields[10].Value]; soundPlatformPlaybackBlock.Fields[0].Value = customPlayback.Fields[0].Value; //playback definition } } if ((short)cacheFileSoundBlock.Fields[11].Value != nullShortIndex) // extra infos { BlockField unnamed = (BlockField)soundBlock.Fields[15]; if (unnamed.AddNew(out Block extraInfo)) { //Get encoded permutation section Block soundGestaltExtraInfo = extraInfos.BlockList[(short)cacheFileSoundBlock.Fields[11].Value]; foreach (Block section in ((BlockField)soundGestaltExtraInfo.Fields[0]).BlockList) { ((BlockField)extraInfo.Fields[1]).BlockList.Add(section); } //Get geometry block info TagBlock_ToGuerilla((Block)extraInfo.Fields[2].Value, (Block)soundGestaltExtraInfo.Fields[1].Value, map); ((Block)extraInfo.Fields[2].Value).Fields[6].Value = string.Empty; } } if ((short)cacheFileSoundBlock.Fields[6].Value != nullShortIndex) // pitch range short index { short pitchRangeIndex = (short)cacheFileSoundBlock.Fields[6].Value; byte pitchRangeCount = (byte)cacheFileSoundBlock.Fields[7].Value; BlockField soundPitchRanges = (BlockField)soundBlock.Fields[13]; for (int i = 0; i < pitchRangeCount; i++) { if (soundPitchRanges.AddNew(out Block soundPitchRange)) { Block pitchRange = pitchRanges.BlockList[pitchRangeIndex + i]; Block importName = importNames.BlockList[(short)pitchRange.Fields[0].Value]; Block pitchRangeParameter = pitchRangeParameters.BlockList[(short)pitchRange.Fields[1].Value]; //Setup sound pitch range soundPitchRange.Fields[0].Value = map.Strings[((StringId)importName.Fields[0].Value).Index]; soundPitchRange.Fields[2].Value = (short)pitchRangeParameter.Fields[0].Value; soundPitchRange.Fields[4].Value = (ShortBounds)pitchRangeParameter.Fields[1].Value; soundPitchRange.Fields[5].Value = (ShortBounds)pitchRangeParameter.Fields[2].Value; if ((short)pitchRange.Fields[4].Value != nullShortIndex) // sound permutation short index { short permutationIndex = (short)pitchRange.Fields[4].Value; short permutationCount = (short)pitchRange.Fields[5].Value; BlockField soundPermutations = (BlockField)soundPitchRange.Fields[7]; for (int j = 0; j < permutationCount; j++) { if (soundPermutations.AddNew(out Block soundPermutation)) { Block permutation = permutations.BlockList[permutationIndex + j]; importName = importNames.BlockList[(short)permutation.Fields[0].Value]; soundPermutation.Fields[0].Value = map.Strings[((StringId)importName.Fields[0].Value).Index]; soundPermutation.Fields[1].Value = (ushort)(short)permutation.Fields[1].Value / 65535f; soundPermutation.Fields[2].Value = (byte)permutation.Fields[2].Value / 255f; soundPermutation.Fields[3].Value = (int)permutation.Fields[5].Value; soundPermutation.Fields[4].Value = (short)(byte)permutation.Fields[3].Value; soundPermutation.Fields[5].Value = (short)permutation.Fields[4].Value; if ((short)permutation.Fields[6].Value != nullShortIndex) // sound chunk short index { short chunkIndex = (short)permutation.Fields[6].Value; short chunkCount = (short)permutation.Fields[7].Value; BlockField soundChunks = (BlockField)soundPermutation.Fields[6]; for (int k = 0; k < chunkCount; k++) { soundChunks.BlockList.Add(chunks.BlockList[chunkIndex + k]); } } } } } } } } return(sound); }
/// <summary> /// Saves the given post model /// </summary> /// <param name="model">The post model</param> public void Save <T>(T model) where T : Models.PostBase { var type = api.PostTypes.GetById(model.TypeId); if (type != null) { // Ensure category if (model.Category.Id == Guid.Empty) { Data.Category category = null; if (!string.IsNullOrWhiteSpace(model.Category.Slug)) { category = api.Categories.GetBySlug(model.BlogId, model.Category.Slug); } if (category == null && !string.IsNullOrWhiteSpace(model.Category.Title)) { category = api.Categories.GetByTitle(model.BlogId, model.Category.Title); } if (category == null) { category = new Data.Category() { Id = Guid.NewGuid(), BlogId = model.BlogId, Title = model.Category.Title }; api.Categories.Save(category); } model.Category.Id = category.Id; } // Ensure tags foreach (var t in model.Tags) { if (t.Id == Guid.Empty) { Data.Tag tag = null; if (!string.IsNullOrWhiteSpace(t.Slug)) { tag = api.Tags.GetBySlug(model.BlogId, t.Slug); } if (tag == null && !string.IsNullOrWhiteSpace(t.Title)) { tag = api.Tags.GetByTitle(model.BlogId, t.Title); } if (tag == null) { tag = new Data.Tag() { Id = Guid.NewGuid(), BlogId = model.BlogId, Title = t.Title }; api.Tags.Save(tag); } t.Id = tag.Id; } } // Ensure that we have a slug if (string.IsNullOrWhiteSpace(model.Slug)) { model.Slug = Utils.GenerateSlug(model.Title, false); } else { model.Slug = Utils.GenerateSlug(model.Slug, false); } var post = db.Posts .Include(p => p.Blocks).ThenInclude(b => b.Block).ThenInclude(b => b.Fields) .Include(p => p.Fields) .Include(p => p.Tags) .FirstOrDefault(p => p.Id == model.Id); // If not, create a new post if (post == null) { post = new Post() { Id = model.Id != Guid.Empty ? model.Id : Guid.NewGuid(), Created = DateTime.Now, LastModified = DateTime.Now }; db.Posts.Add(post); model.Id = post.Id; } else { post.LastModified = DateTime.Now; } post = contentService.Transform <T>(model, type, post); // Transform blocks var blockModels = model.Blocks; if (blockModels != null && blockModels.Count > 0) { var blocks = contentService.TransformBlocks(blockModels); var current = blocks.Select(b => b.Id).ToArray(); // Delete removed blocks var removed = post.Blocks .Where(b => !current.Contains(b.BlockId) && !b.Block.IsReusable) .Select(b => b.Block); db.Blocks.RemoveRange(removed); // Delete the old page blocks post.Blocks.Clear(); // Now map the new block for (var n = 0; n < blocks.Count; n++) { var block = db.Blocks .Include(b => b.Fields) .FirstOrDefault(b => b.Id == blocks[n].Id); if (block == null) { block = new Block() { Id = blocks[n].Id != Guid.Empty ? blocks[n].Id : Guid.NewGuid(), Created = DateTime.Now }; db.Blocks.Add(block); } block.CLRType = blocks[n].CLRType; block.IsReusable = blocks[n].IsReusable; block.Title = blocks[n].Title; block.LastModified = DateTime.Now; var currentFields = blocks[n].Fields.Select(f => f.FieldId).Distinct(); var removedFields = block.Fields.Where(f => !currentFields.Contains(f.FieldId)); db.BlockFields.RemoveRange(removedFields); foreach (var newField in blocks[n].Fields) { var field = block.Fields.FirstOrDefault(f => f.FieldId == newField.FieldId); if (field == null) { field = new BlockField() { Id = newField.Id != Guid.Empty ? newField.Id : Guid.NewGuid(), BlockId = block.Id, FieldId = newField.FieldId }; db.BlockFields.Add(field); block.Fields.Add(field); } field.SortOrder = newField.SortOrder; field.CLRType = newField.CLRType; field.Value = newField.Value; } // Create the page block post.Blocks.Add(new PostBlock() { Id = Guid.NewGuid(), BlockId = block.Id, Block = block, PostId = post.Id, SortOrder = n }); } } // Remove tags var removedTags = new List <PostTag>(); foreach (var tag in post.Tags) { if (!model.Tags.Any(t => t.Id == tag.TagId)) { removedTags.Add(tag); } } foreach (var removed in removedTags) { post.Tags.Remove(removed); } // Add tags foreach (var tag in model.Tags) { if (!post.Tags.Any(t => t.PostId == post.Id && t.TagId == tag.Id)) { post.Tags.Add(new PostTag() { PostId = post.Id, TagId = tag.Id }); } } db.SaveChanges(); if (cache != null) { RemoveFromCache(post); } } }
/// <summary> /// Saves the given page model /// </summary> /// <param name="model">The page model</param> public void Save <T>(T model) where T : Models.PageBase { var type = _api.PageTypes.GetById(model.TypeId); var shouldUpdateSiteDate = false; if (type != null) { // Ensure that we have a slug if (string.IsNullOrWhiteSpace(model.Slug)) { var prefix = ""; // Check if we should generate hierarchical slugs using (var config = new Config(_api)) { if (config.HierarchicalPageSlugs && model.ParentId.HasValue) { var parentSlug = _db.Pages .AsNoTracking() .FirstOrDefault(p => p.Id == model.ParentId)?.Slug; if (!string.IsNullOrWhiteSpace(parentSlug)) { prefix = parentSlug + "/"; } } model.Slug = prefix + Utils.GenerateSlug(model.NavigationTitle != null ? model.NavigationTitle : model.Title); } } else { model.Slug = Utils.GenerateSlug(model.Slug); } // Set content type model.ContentType = type.ContentTypeId; var page = _db.Pages .Include(p => p.Blocks).ThenInclude(b => b.Block).ThenInclude(b => b.Fields) .Include(p => p.Fields) .FirstOrDefault(p => p.Id == model.Id); var site = _db.Sites .FirstOrDefault(s => s.Id == model.SiteId); if (model.OriginalPageId.HasValue) { var originalPageIsCopy = _db.Pages.FirstOrDefault(p => p.Id == model.OriginalPageId)?.OriginalPageId.HasValue ?? false; if (originalPageIsCopy) { throw new InvalidOperationException("Can not set copy of a copy"); } var originalPageType = _db.Pages.FirstOrDefault(p => p.Id == model.OriginalPageId)?.PageTypeId; if (originalPageType != model.TypeId) { throw new InvalidOperationException("Copy can not have a different content type"); } // Transform the model if (page == null) { page = new Page() { Id = model.Id != Guid.Empty ? model.Id : Guid.NewGuid(), }; _db.Pages.Add(page); // Make room for the new page MovePages(page.Id, model.SiteId, model.ParentId, model.SortOrder, true); // We're adding a page to the site structure, update // the global last modified date shouldUpdateSiteDate = true; } else { // Check if the page has been moved if (page.ParentId != model.ParentId || page.SortOrder != model.SortOrder) { // Remove the old position for the page MovePages(page.Id, page.SiteId, page.ParentId, page.SortOrder + 1, false); // Add room for the new position of the page MovePages(page.Id, model.SiteId, model.ParentId, model.SortOrder, true); // We've moved pages, update the global last // modified date shouldUpdateSiteDate = true; } } if (page.Title != model.Title || page.NavigationTitle != model.NavigationTitle) { // We've changed the title which is reflected in the // sitemap, update the global last modified date. shouldUpdateSiteDate = true; } page.PageTypeId = model.TypeId; page.OriginalPageId = model.OriginalPageId; page.SiteId = model.SiteId; page.Title = model.Title; page.NavigationTitle = model.NavigationTitle; page.Slug = model.Slug; page.ParentId = model.ParentId; page.SortOrder = model.SortOrder; page.IsHidden = model.IsHidden; page.Route = model.Route; page.Published = model.Published; if (shouldUpdateSiteDate) { site.ContentLastModified = DateTime.Now; } _db.SaveChanges(); if (_cache != null) { RemoveFromCache(page); } _api.Sites.InvalidateSitemap(model.SiteId); return; } // Transform the model if (page == null) { page = new Page { Id = model.Id != Guid.Empty ? model.Id : Guid.NewGuid(), ParentId = model.ParentId, SortOrder = model.SortOrder, PageTypeId = model.TypeId, Created = DateTime.Now, LastModified = DateTime.Now }; _db.Pages.Add(page); model.Id = page.Id; // Make room for the new page MovePages(page.Id, model.SiteId, model.ParentId, model.SortOrder, true); // We're adding a page to the site structure, update // the global last modified date shouldUpdateSiteDate = true; } else { // Check if the page has been moved if (page.ParentId != model.ParentId || page.SortOrder != model.SortOrder) { // Remove the old position for the page MovePages(page.Id, page.SiteId, page.ParentId, page.SortOrder + 1, false); // Add room for the new position of the page MovePages(page.Id, model.SiteId, model.ParentId, model.SortOrder, true); // We've moved pages, update the global last // modified date shouldUpdateSiteDate = true; } page.LastModified = DateTime.Now; } if (page.Title != model.Title || page.NavigationTitle != model.NavigationTitle) { // We've changed the title which is reflected in the // sitemap, update the global last modified date. shouldUpdateSiteDate = true; } page = _contentService.Transform <T>(model, type, page); // Transform blocks var blockModels = model.Blocks; if (blockModels != null) { var pageBlocks = _contentService.TransformBlocks <PageBlock>(blockModels); var current = pageBlocks.Select(b => b.Block.Id).ToArray(); // Delete removed blocks var removed = page.Blocks .Where(b => !current.Contains(b.BlockId) && !b.Block.IsReusable) .Select(b => b.Block); _db.Blocks.RemoveRange(removed); // Delete the old page blocks page.Blocks.Clear(); // Now map the new block for (var n = 0; n < pageBlocks.Count; n++) { var block = _db.Blocks .Include(b => b.Fields) .FirstOrDefault(b => b.Id == pageBlocks[n].Block.Id); if (block == null) { block = new Block { Id = pageBlocks[n].Block.Id != Guid.Empty ? pageBlocks[n].Block.Id : Guid.NewGuid(), Created = DateTime.Now }; _db.Blocks.Add(block); } block.CLRType = pageBlocks[n].Block.CLRType; block.IsReusable = pageBlocks[n].Block.IsReusable; block.Title = pageBlocks[n].Block.Title; block.LastModified = DateTime.Now; var currentFields = pageBlocks[n].Block.Fields.Select(f => f.FieldId).Distinct(); var removedFields = block.Fields.Where(f => !currentFields.Contains(f.FieldId)); _db.BlockFields.RemoveRange(removedFields); foreach (var newField in pageBlocks[n].Block.Fields) { var field = block.Fields.FirstOrDefault(f => f.FieldId == newField.FieldId); if (field == null) { field = new BlockField { Id = newField.Id != Guid.Empty ? newField.Id : Guid.NewGuid(), BlockId = block.Id, FieldId = newField.FieldId }; _db.BlockFields.Add(field); block.Fields.Add(field); } field.SortOrder = newField.SortOrder; field.CLRType = newField.CLRType; field.Value = newField.Value; } // Create the page block page.Blocks.Add(new PageBlock { Id = pageBlocks[n].Id, ParentId = pageBlocks[n].ParentId, BlockId = block.Id, Block = block, PageId = page.Id, SortOrder = n }); } } if (shouldUpdateSiteDate) { site.ContentLastModified = DateTime.Now; } _db.SaveChanges(); if (_cache != null) { RemoveFromCache(page); } _api.Sites.InvalidateSitemap(model.SiteId); } }
private void OverlayEntities(MapElement entities, Bitmap map, VirtualMap <char> solids, bool background) { CassetteBlock.Blocks.Clear(); using (Graphics g = Graphics.FromImage(map)) { List <Entity> ents = new List <Entity>(); for (int i = entities.Children.Count - 1; i >= 0; i--) { MapElement child = entities.Children[i]; Entity entity = null; if (child.Name.IndexOf("spikes", StringComparison.OrdinalIgnoreCase) == 0) { entity = background ? Spikes.FromElement(child) : null; } else if (child.Name.IndexOf("triggerSpikes", StringComparison.OrdinalIgnoreCase) == 0) { entity = background ? TriggerSpikes.FromElement(child) : null; } else if (child.Name.IndexOf("strawberry", StringComparison.OrdinalIgnoreCase) == 0) { entity = background ? Strawberry.FromElement(child) : null; } else if (child.Name.Equals("goldenBerry", StringComparison.OrdinalIgnoreCase)) { entity = background ? Strawberry.FromElement(child) : null; } else if (child.Name.Equals("redBlocks", StringComparison.OrdinalIgnoreCase)) { entity = background ? ClutterBlock.FromElement(child) : null; } else if (child.Name.Equals("greenBlocks", StringComparison.OrdinalIgnoreCase)) { entity = background ? ClutterBlock.FromElement(child) : null; } else if (child.Name.Equals("yellowBlocks", StringComparison.OrdinalIgnoreCase)) { entity = background ? ClutterBlock.FromElement(child) : null; } else if (child.Name.Equals("clutterCabinet", StringComparison.OrdinalIgnoreCase)) { entity = background ? ClutterCabinet.FromElement(child) : null; } else if (child.Name.Equals("introCar", StringComparison.OrdinalIgnoreCase)) { entity = background ? IntroCar.FromElement(child) : null; } else if (child.Name.Equals("clothesLine", StringComparison.OrdinalIgnoreCase)) { entity = background ? ClothesLine.FromElement(child) : null; } else if (child.Name.Equals("colorSwitch", StringComparison.OrdinalIgnoreCase)) { entity = background ? ColorSwitch.FromElement(child) : null; } else if (child.Name.Equals("memorialTextController", StringComparison.OrdinalIgnoreCase)) { entity = background ? Strawberry.FromElement(child) : null; } else if (child.Name.Equals("bonfire", StringComparison.OrdinalIgnoreCase)) { entity = background ? Bonfire.FromElement(child) : null; } else if (child.Name.Equals("trapDoor", StringComparison.OrdinalIgnoreCase)) { entity = background ? TrapDoor.FromElement(child) : null; } else if (child.Name.Equals("movingPlatform", StringComparison.OrdinalIgnoreCase)) { entity = background ? MovingPlatform.FromElement(child) : null; } else if (child.Name.Equals("sinkingPlatform", StringComparison.OrdinalIgnoreCase)) { entity = background ? SinkingPlatform.FromElement(child) : null; } else if (child.Name.Equals("clutterDoor", StringComparison.OrdinalIgnoreCase)) { entity = background ? ClutterDoor.FromElement(child) : null; } else if (child.Name.Equals("bridge", StringComparison.OrdinalIgnoreCase)) { entity = background ? Bridge.FromElement(child) : null; } else if (child.Name.Equals("bridgeFixed", StringComparison.OrdinalIgnoreCase)) { entity = background ? BridgeFixed.FromElement(child) : null; } else if (child.Name.Equals("jumpThru", StringComparison.OrdinalIgnoreCase)) { entity = background ? JumpThru.FromElement(child) : null; } else if (child.Name.Equals("door", StringComparison.OrdinalIgnoreCase)) { entity = background ? Door.FromElement(child) : null; } else if (child.Name.Equals("blockField", StringComparison.OrdinalIgnoreCase)) { entity = background ? BlockField.FromElement(child) : null; } else if (child.Name.Equals("lamp", StringComparison.OrdinalIgnoreCase)) { entity = background ? Lamp.FromElement(child) : null; } else if (child.Name.Equals("hahaha", StringComparison.OrdinalIgnoreCase)) { entity = background ? Haha.FromElement(child) : null; } else if (child.Name.Equals("waterFall", StringComparison.OrdinalIgnoreCase)) { entity = background ? WaterFall.FromElement(child) : null; } else if (child.Name.Equals("water", StringComparison.OrdinalIgnoreCase)) { entity = background ? Water.FromElement(child) : null; } else if (child.Name.Equals("key", StringComparison.OrdinalIgnoreCase)) { entity = background ? Key.FromElement(child) : null; } else if (child.Name.Equals("resortLantern", StringComparison.OrdinalIgnoreCase)) { entity = background ? ResortLantern.FromElement(child) : null; } else if (child.Name.Equals("bird", StringComparison.OrdinalIgnoreCase)) { entity = background ? Bird.FromElement(child) : null; } else if (child.Name.Equals("memorial", StringComparison.OrdinalIgnoreCase)) { entity = background ? Memorial.FromElement(child) : null; } else if (child.Name.Equals("player", StringComparison.OrdinalIgnoreCase)) { entity = background ? PlayerSpawn.FromElement(child) : null; } else if (child.Name.Equals("zipMover", StringComparison.OrdinalIgnoreCase)) { entity = background ? ZipMover.FromElement(child) : null; } else if (child.Name.Equals("wire", StringComparison.OrdinalIgnoreCase)) { entity = background ? Wire.FromElement(child) : null; } else if (child.Name.Equals("crumbleBlock", StringComparison.OrdinalIgnoreCase)) { entity = background ? CrumbleBlock.FromElement(child) : null; } else if (child.Name.Equals("refill", StringComparison.OrdinalIgnoreCase)) { entity = background ? Refill.FromElement(child) : null; } else if (child.Name.Equals("spring", StringComparison.OrdinalIgnoreCase)) { entity = background ? Spring.FromElement(child) : null; } else if (child.Name.Equals("fakeWall", StringComparison.OrdinalIgnoreCase)) { entity = background ? FakeWall.FromElement(child) : null; } else if (child.Name.Equals("exitBlock", StringComparison.OrdinalIgnoreCase)) { entity = background ? FakeWall.FromElement(child) : null; } else if (child.Name.Equals("lightBeam", StringComparison.OrdinalIgnoreCase)) { entity = background ? LightBeam.FromElement(child) : null; } else if (child.Name.Equals("cobweb", StringComparison.OrdinalIgnoreCase)) { entity = background ? Cobweb.FromElement(child) : null; } else if (child.Name.Equals("cassette", StringComparison.OrdinalIgnoreCase)) { entity = background ? Cassette.FromElement(child) : null; } else if (child.Name.Equals("flutterBird", StringComparison.OrdinalIgnoreCase)) { entity = background ? FlutterBird.FromElement(child) : null; } else if (child.Name.Equals("checkpoint", StringComparison.OrdinalIgnoreCase)) { entity = background ? Checkpoint.FromElement(child) : null; } else if (child.Name.Equals("fallingBlock", StringComparison.OrdinalIgnoreCase)) { entity = background ? FallingBlock.FromElement(child) : null; } else if (child.Name.Equals("introCrusher", StringComparison.OrdinalIgnoreCase)) { entity = background ? FallingBlock.FromElement(child) : null; } else if (child.Name.Equals("cassetteBlock", StringComparison.OrdinalIgnoreCase)) { entity = background ? CassetteBlock.FromElement(child) : null; } else if (child.Name.Equals("dashBlock", StringComparison.OrdinalIgnoreCase)) { entity = background ? DashBlock.FromElement(child) : null; } else if (child.Name.Equals("coverupWall", StringComparison.OrdinalIgnoreCase)) { entity = background ? CoverupWall.FromElement(child) : null; } else if (child.Name.Equals("npc", StringComparison.OrdinalIgnoreCase)) { entity = background ? NPC.FromElement(child) : null; } else if (child.Name.Equals("birdForsakenCityGem", StringComparison.OrdinalIgnoreCase)) { entity = background ? ForsakenCityGem.FromElement(child) : null; } else if (child.Name.Equals("soundSource", StringComparison.OrdinalIgnoreCase)) { entity = background ? SoundSource.FromElement(child) : null; } else if (child.Name.Equals("friendlyGhost", StringComparison.OrdinalIgnoreCase)) { entity = background ? FriendlyGhost.FromElement(child) : null; } else if (child.Name.Equals("floatingDebris", StringComparison.OrdinalIgnoreCase)) { entity = background ? FloatingDebris.FromElement(child) : null; } else if (child.Name.Equals("hangingLamp", StringComparison.OrdinalIgnoreCase)) { entity = background ? HangingLamp.FromElement(child) : null; } else if (child.Name.Equals("lockBlock", StringComparison.OrdinalIgnoreCase)) { entity = background ? LockBlock.FromElement(child) : null; } else if (child.Name.Equals("heartGem", StringComparison.OrdinalIgnoreCase)) { entity = background ? HeartGem.FromElement(child) : null; } else if (child.Name.Equals("blackGem", StringComparison.OrdinalIgnoreCase)) { entity = background ? HeartGem.FromElement(child) : null; } else if (child.Name.Equals("dreamMirror", StringComparison.OrdinalIgnoreCase)) { entity = background ? DreamMirror.FromElement(child) : null; } else if (child.Name.Equals("darkChaser", StringComparison.OrdinalIgnoreCase)) { entity = background ? DarkChaser.FromElement(child) : null; } else if (child.Name.Equals("dreamBlock", StringComparison.OrdinalIgnoreCase)) { entity = background ? DreamBlock.FromElement(child) : null; } else if (child.Name.Equals("touchSwitch", StringComparison.OrdinalIgnoreCase)) { entity = background ? TouchSwitch.FromElement(child) : null; } else if (child.Name.Equals("switchGate", StringComparison.OrdinalIgnoreCase)) { entity = background ? SwitchGate.FromElement(child) : null; } else if (child.Name.Equals("invisibleBarrier", StringComparison.OrdinalIgnoreCase)) { entity = background ? InvisibleBarrier.FromElement(child) : null; } else if (child.Name.Equals("payphone", StringComparison.OrdinalIgnoreCase)) { entity = background ? Payphone.FromElement(child) : null; } else if (child.Name.Equals("spinner", StringComparison.OrdinalIgnoreCase)) { entity = background ? Spinner.FromElement(child) : null; } else if (child.Name.Equals("rotateSpinner", StringComparison.OrdinalIgnoreCase)) { entity = background ? RotateSpinner.FromElement(child) : null; } else if (child.Name.Equals("trackSpinner", StringComparison.OrdinalIgnoreCase)) { entity = background ? TrackSpinner.FromElement(child) : null; } else if (child.Name.Equals("towerViewer", StringComparison.OrdinalIgnoreCase)) { entity = background ? TowerViewer.FromElement(child) : null; } else if (child.Name.Equals("foregroundDebris", StringComparison.OrdinalIgnoreCase)) { entity = !background?ForegroundDebris.FromElement(child) : null; } else if (background) { Console.WriteLine(child.Name); } if (entity != null) { ents.Add(entity); } } ents.Sort(delegate(Entity one, Entity two) { int comp = two.Depth.CompareTo(one.Depth); return(comp == 0 ? one.ID.CompareTo(two.ID) : comp); }); for (int i = 0; i < ents.Count; i++) { Entity entity = ents[i]; entity.Render(g, solids); } } }
private void tagStructureTreeView_AfterSelect(object sender, TreeViewEventArgs e) { //Hide deleteBlockToolStripButton.Visible = false; cloneBlockToolStripButton.Visible = false; addBlockToolStripButton.Visible = false; deleteTagBlocksToolStripButton.Visible = false; toolStripSeparator2.Visible = false; copyToolStripMenuItem.Enabled = false; pasteToolStripMenuButton.Enabled = false; toolStripSeparator3.Visible = false; moveBlockUpToolStripButton.Visible = false; moveBlockDownToolStripButton.Visible = false; //Prepare BlockField tagBlockField = null; DataField dataField = null; ITagBlock tagBlock = null; //Check if (e.Node.Tag is ITagBlock && e.Node.Parent != null && e.Node.Parent.Tag is BlockField) { //Get variables tagBlock = (ITagBlock)e.Node.Tag; tagBlockField = (BlockField)e.Node.Parent.Tag; //Show toolStripSeparator2.Visible = true; deleteBlockToolStripButton.Visible = true; copyToolStripMenuItem.Enabled = true; pasteToolStripMenuButton.Enabled = true; cloneBlockToolStripButton.Visible = tagBlockField.BlockList.Count < tagBlockField.Create().MaximumElementCount; toolStripSeparator3.Visible = true; moveBlockUpToolStripButton.Visible = true; moveBlockDownToolStripButton.Visible = true; } else if (e.Node.Tag is BlockField) { //Get variables tagBlockField = (BlockField)e.Node.Tag; //Show toolStripSeparator2.Visible = true; deleteTagBlocksToolStripButton.Visible = true; copyToolStripMenuItem.Enabled = true; pasteToolStripMenuButton.Enabled = true; addBlockToolStripButton.Visible = tagBlockField.BlockList.Count < tagBlockField.Create().MaximumElementCount; } else if (e.Node.Tag is DataField) { //Get vairables dataField = (DataField)e.Node.Tag; //Do nothing for now... toolStripSeparator2.Visible = true; copyToolStripMenuItem.Enabled = true; pasteToolStripMenuButton.Enabled = true; } else if (e.Node.Tag is StructField structField) { //Show toolStripSeparator2.Visible = true; copyToolStripMenuItem.Enabled = true; pasteToolStripMenuButton.Enabled = true; } }
/// <summary> /// Saves the given page model /// </summary> /// <param name="model">The page model</param> private async Task <IEnumerable <Guid> > Save <T>(T model, bool isDraft) where T : Models.PageBase { var type = App.PageTypes.GetById(model.TypeId); var affected = new List <Guid>(); var isNew = false; var lastModified = DateTime.MinValue; if (type != null) { // Set content type model.ContentType = type.ContentTypeId; IQueryable <Page> pageQuery = _db.Pages; if (isDraft) { pageQuery = pageQuery.AsNoTracking(); } var page = await pageQuery .Include(p => p.Blocks).ThenInclude(b => b.Block).ThenInclude(b => b.Fields) .Include(p => p.Fields) .FirstOrDefaultAsync(p => p.Id == model.Id) .ConfigureAwait(false); if (page == null) { isNew = true; } else { lastModified = page.LastModified; } if (model.OriginalPageId.HasValue) { var originalPageIsCopy = (await _db.Pages.AsNoTracking().FirstOrDefaultAsync(p => p.Id == model.OriginalPageId).ConfigureAwait(false))?.OriginalPageId.HasValue ?? false; if (originalPageIsCopy) { throw new InvalidOperationException("Can not set copy of a copy"); } var originalPageType = (await _db.Pages.AsNoTracking().FirstOrDefaultAsync(p => p.Id == model.OriginalPageId).ConfigureAwait(false))?.PageTypeId; if (originalPageType != model.TypeId) { throw new InvalidOperationException("Copy can not have a different content type"); } // Transform the model if (page == null) { page = new Page() { Id = model.Id != Guid.Empty ? model.Id : Guid.NewGuid(), }; if (!isDraft) { _db.Pages.Add(page); // Make room for the new page var dest = await _db.Pages.Where(p => p.SiteId == model.SiteId && p.ParentId == model.ParentId).ToListAsync().ConfigureAwait(false); affected.AddRange(MovePages(dest, page.Id, model.SiteId, model.ParentId, model.SortOrder, true)); } } else { // Check if the page has been moved if (!isDraft && (page.ParentId != model.ParentId || page.SortOrder != model.SortOrder)) { var source = await _db.Pages.Where(p => p.SiteId == page.SiteId && p.ParentId == page.ParentId && p.Id != model.Id).ToListAsync().ConfigureAwait(false); var dest = page.ParentId == model.ParentId ? source : await _db.Pages.Where(p => p.SiteId == model.SiteId && p.ParentId == model.ParentId).ToListAsync().ConfigureAwait(false); // Remove the old position for the page affected.AddRange(MovePages(source, page.Id, page.SiteId, page.ParentId, page.SortOrder + 1, false)); // Add room for the new position of the page affected.AddRange(MovePages(dest, page.Id, model.SiteId, model.ParentId, model.SortOrder, true)); } } if (!isDraft && (isNew || page.Title != model.Title || page.NavigationTitle != model.NavigationTitle)) { // If this is new page or title has been updated it means // the global sitemap changes. Notify the service. affected.Add(page.Id); } page.PageTypeId = model.TypeId; page.OriginalPageId = model.OriginalPageId; page.SiteId = model.SiteId; page.Title = model.Title; page.NavigationTitle = model.NavigationTitle; page.Slug = model.Slug; page.ParentId = model.ParentId; page.SortOrder = model.SortOrder; page.IsHidden = model.IsHidden; page.Route = model.Route; page.Published = model.Published; if (!isDraft) { await _db.SaveChangesAsync().ConfigureAwait(false); } else { var draft = await _db.PageRevisions .FirstOrDefaultAsync(r => r.PageId == page.Id && r.Created > lastModified) .ConfigureAwait(false); if (draft == null) { draft = new PageRevision { Id = Guid.NewGuid(), PageId = page.Id }; await _db.PageRevisions .AddAsync(draft) .ConfigureAwait(false); } draft.Data = JsonConvert.SerializeObject(page); draft.Created = page.LastModified; await _db.SaveChangesAsync().ConfigureAwait(false); } return(affected); } // Transform the model if (page == null) { page = new Page { Id = model.Id != Guid.Empty ? model.Id : Guid.NewGuid(), ParentId = model.ParentId, SortOrder = model.SortOrder, PageTypeId = model.TypeId, Created = DateTime.Now, LastModified = DateTime.Now }; model.Id = page.Id; if (!isDraft) { await _db.Pages.AddAsync(page); // Make room for the new page var dest = await _db.Pages.Where(p => p.SiteId == model.SiteId && p.ParentId == model.ParentId).ToListAsync().ConfigureAwait(false); affected.AddRange(MovePages(dest, page.Id, model.SiteId, model.ParentId, model.SortOrder, true)); } } else { // Check if the page has been moved if (!isDraft && (page.ParentId != model.ParentId || page.SortOrder != model.SortOrder)) { var source = await _db.Pages.Where(p => p.SiteId == page.SiteId && p.ParentId == page.ParentId && p.Id != model.Id).ToListAsync().ConfigureAwait(false); var dest = page.ParentId == model.ParentId ? source : await _db.Pages.Where(p => p.SiteId == model.SiteId && p.ParentId == model.ParentId).ToListAsync().ConfigureAwait(false); // Remove the old position for the page affected.AddRange(MovePages(source, page.Id, page.SiteId, page.ParentId, page.SortOrder + 1, false)); // Add room for the new position of the page affected.AddRange(MovePages(dest, page.Id, model.SiteId, model.ParentId, model.SortOrder, true)); } page.LastModified = DateTime.Now; } if (isNew || page.Title != model.Title || page.NavigationTitle != model.NavigationTitle) { // If this is new page or title has been updated it means // the global sitemap changes. Notify the service. affected.Add(page.Id); } page = _contentService.Transform <T>(model, type, page); // Transform blocks var blockModels = model.Blocks; if (blockModels != null) { var blocks = _contentService.TransformBlocks(blockModels); var current = blocks.Select(b => b.Id).ToArray(); // Delete removed blocks var removed = page.Blocks .Where(b => !current.Contains(b.BlockId) && !b.Block.IsReusable && b.Block.ParentId == null) .Select(b => b.Block); var removedItems = page.Blocks .Where(b => !current.Contains(b.BlockId) && b.Block.ParentId != null && removed.Select(p => p.Id).ToList().Contains(b.Block.ParentId.Value)) .Select(b => b.Block); if (!isDraft) { _db.Blocks.RemoveRange(removed); _db.Blocks.RemoveRange(removedItems); } // Delete the old page blocks page.Blocks.Clear(); // Now map the new block for (var n = 0; n < blocks.Count; n++) { IQueryable <Block> blockQuery = _db.Blocks; if (isDraft) { blockQuery = blockQuery.AsNoTracking(); } var block = await blockQuery .Include(b => b.Fields) .FirstOrDefaultAsync(b => b.Id == blocks[n].Id) .ConfigureAwait(false); if (block == null) { block = new Block { Id = blocks[n].Id != Guid.Empty ? blocks[n].Id : Guid.NewGuid(), Created = DateTime.Now }; if (!isDraft) { await _db.Blocks.AddAsync(block).ConfigureAwait(false); } } block.ParentId = blocks[n].ParentId; block.CLRType = blocks[n].CLRType; block.IsReusable = blocks[n].IsReusable; block.Title = blocks[n].Title; block.LastModified = DateTime.Now; var currentFields = blocks[n].Fields.Select(f => f.FieldId).Distinct(); var removedFields = block.Fields.Where(f => !currentFields.Contains(f.FieldId)); if (!isDraft) { _db.BlockFields.RemoveRange(removedFields); } foreach (var newField in blocks[n].Fields) { var field = block.Fields.FirstOrDefault(f => f.FieldId == newField.FieldId); if (field == null) { field = new BlockField { Id = newField.Id != Guid.Empty ? newField.Id : Guid.NewGuid(), BlockId = block.Id, FieldId = newField.FieldId }; if (!isDraft) { await _db.BlockFields.AddAsync(field).ConfigureAwait(false); } block.Fields.Add(field); } field.SortOrder = newField.SortOrder; field.CLRType = newField.CLRType; field.Value = newField.Value; } // Create the page block page.Blocks.Add(new PageBlock { Id = Guid.NewGuid(), BlockId = block.Id, Block = block, PageId = page.Id, SortOrder = n }); } } if (!isDraft) { await _db.SaveChangesAsync().ConfigureAwait(false); } else { var draft = await _db.PageRevisions .FirstOrDefaultAsync(r => r.PageId == page.Id && r.Created > lastModified) .ConfigureAwait(false); if (draft == null) { draft = new PageRevision { Id = Guid.NewGuid(), PageId = page.Id }; await _db.PageRevisions .AddAsync(draft) .ConfigureAwait(false); } draft.Data = JsonConvert.SerializeObject(page); draft.Created = page.LastModified; await _db.SaveChangesAsync().ConfigureAwait(false); } } return(affected); }
public bool Equals(Block other) { bool equals = Fields.Count == other.Fields.Count && BlockName == other.BlockName; if (equals) { for (int i = 0; i < Fields.Count; i++) { if (!equals) { break; } Field f1 = Fields[i], f2 = other.Fields[i]; equals &= f1.Type == f2.Type; if (equals) { switch (Fields[i].Type) { case FieldType.FieldBlock: BlockField bf1 = (BlockField)f1; BlockField bf2 = (BlockField)f2; equals &= bf1.BlockList.Count == bf2.BlockList.Count; if (equals) { for (int j = 0; j < bf1.BlockList.Count; j++) { if (equals) { equals = bf1.BlockList[j].Equals(bf2.BlockList[j]); } } } break; case FieldType.FieldStruct: equals &= ((Block)f1.Value).Equals((Block)f2.Value); break; case FieldType.FieldPad: PadField pf1 = (PadField)f1; PadField pf2 = (PadField)f2; for (int j = 0; j < pf1.Length; j++) { if (equals) { equals &= ((byte[])pf1.Value)[j] == ((byte[])pf2.Value)[j]; } } break; default: if (f1.Value == null && f2.Value == null) { continue; } else { equals &= f1.Value.Equals(f2.Value); } break; } } } } return(equals); }
private void Map_Decompile(object state) { Console.WriteLine($"Decompiling {map.Name}..."); Group globalsGroup; Group soundGestaltGroup = null; IndexEntry soundGestalt = null; IndexEntry globals = map.Globals; try { using (var tagReader = globals.Data.GetVirtualStream().CreateReader()) { tagReader.BaseStream.Seek(globals.Address, SeekOrigin.Begin); globalsGroup = TagLookup.CreateTagGroup(globals.Root); globalsGroup.Read(tagReader); BlockField soundGlobalsTagBlock = (BlockField)globalsGroup.TagBlocks[0].Fields[4]; if (soundGlobalsTagBlock.BlockList.Count > 0) { TagId soundGestaltId = (TagId)soundGlobalsTagBlock.BlockList[0].Fields[4].Value; soundGestalt = map.IndexEntries[soundGestaltId]; soundGlobalsTagBlock.BlockList[0].Fields[4].Value = (int)TagId.Null; } } if (soundGestalt != null) { using (BinaryReader reader = soundGestalt.Data.GetVirtualStream().CreateReader()) { soundGestaltGroup = TagLookup.CreateTagGroup(soundGestalt.Root); reader.BaseStream.Seek(soundGestalt.Address, SeekOrigin.Begin); soundGestaltGroup.Read(reader); } } int num = 0; float total = map.IndexEntries.Count; var result = Parallel.ForEach(map.IndexEntries, entry => { num++; Group guerillaTagGroup; var tagGroup = TagLookup.CreateTagGroup(entry.Root); var reader = entry.Data.GetVirtualStream().CreateReader(); reader.BaseStream.Seek(entry.Address, SeekOrigin.Begin); try { tagGroup.Read(reader); } finally { guerillaTagGroup = Convert.ToGuerilla(tagGroup, soundGestaltGroup, entry, map); } string localFileName = Path.Combine($"{entry.Filename}.{guerillaTagGroup.GroupName}"); string tagGroupFileName = Path.Combine(OutputDirectory, localFileName); if (!Directory.Exists(Path.GetDirectoryName(tagGroupFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(tagGroupFileName)); } TagGroupHeader header = new TagGroupHeader(); using (FileStream fs = new FileStream(tagGroupFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read)) using (BinaryReader fileReader = new BinaryReader(fs)) using (BinaryWriter fileWriter = new BinaryWriter(fs)) { fs.Seek(TagGroupHeader.Size, SeekOrigin.Begin); guerillaTagGroup.Write(fileWriter); switch (guerillaTagGroup.GroupTag) { case "snd!": SoundTagGroup_CreateResources(guerillaTagGroup, soundGestalt, fileWriter, ref header); break; case "mode": RenderModelTagGroup_CreateResources(guerillaTagGroup, entry, fileWriter, ref header); break; case "sbsp": ScenarioStructureBspTagGroup_CreateResources(guerillaTagGroup, entry, fileWriter, ref header); break; case "ltmp": ScenarioStructureLightmapTagGroup_CreateResources(guerillaTagGroup, entry, fileWriter, ref header); break; case "weat": WeatherSystemTagGroup_CreateResources(guerillaTagGroup, entry, fileWriter, ref header); break; case "DECR": DecoratorSetTagGroup_CreateResources(guerillaTagGroup, entry, fileWriter, ref header); break; case "PRTM": ParticleModelTagGroup_CreateResources(guerillaTagGroup, entry, fileWriter, ref header); break; case "jmad": AnimationTagGroup_CreateResources(guerillaTagGroup, entry, fileWriter, ref header); break; case "bitm": BitmapTagGroup_CreateResources(guerillaTagGroup, entry, fileWriter, ref header); break; } header.Checksum = (uint)TagGroup_CalculateChecksum(guerillaTagGroup); header.GroupTag = guerillaTagGroup.GroupTag.FourCc; header.Id = entry.Id.Dword; header.AbideTag = "atag"; fs.Seek(0, SeekOrigin.Begin); fileWriter.Write(header); Host.Report(num / total); } }); } catch { #if DEBUG throw; #endif } finally { GC.Collect(); } Host.Report(1); Thread.Sleep(500); Host.Complete(); }
private void FixSystemLinkButton_Click(object sender, EventArgs e) { /* * Heh I guess Entity is good for something :P */ //Prepare ITagGroup tagGroup = null; ITagGroup scenario = new Scenario(); ITagBlock scenarioBlock = null, simulationDefinitionTableElementBlock = null; BlockField simulationDefinitionTableField = null; List <IndexEntry> simulationDefinitionEntries = new List <IndexEntry>(); bool success = false; //Build table foreach (IndexEntry entry in Map.IndexEntries) { switch (entry.Root) { case "bipd": case "bloc": case "ctrl": case "jpt!": case "mach": case "scen": case "ssce": case "vehi": simulationDefinitionEntries.Add(entry); break; case "eqip": case "garb": case "proj": simulationDefinitionEntries.Add(entry); simulationDefinitionEntries.Add(entry); break; case "weap": simulationDefinitionEntries.Add(entry); simulationDefinitionEntries.Add(entry); simulationDefinitionEntries.Add(entry); break; } } //Read scenario using (BinaryReader reader = Map.Scenario.TagData.CreateReader()) { reader.BaseStream.Seek((uint)Map.Scenario.PostProcessedOffset, SeekOrigin.Begin); scenario.Read(reader); } //Re-create simulation definition table scenarioBlock = scenario[0]; simulationDefinitionTableField = (BlockField)scenarioBlock[143]; simulationDefinitionTableField.BlockList.Clear(); foreach (IndexEntry entry in simulationDefinitionEntries) { //Attempt to add tag block simulationDefinitionTableElementBlock = simulationDefinitionTableField.Add(out success); if (success) { simulationDefinitionTableElementBlock[0].Value = entry.Id; } } //Rebuild map using (VirtualStream tagDataStream = new VirtualStream(Map.TagDataStream.MemoryAddress)) using (BinaryWriter writer = tagDataStream.CreateWriter()) using (BinaryReader reader = Map.TagDataStream.CreateReader()) { //Loop foreach (IndexEntry entry in Map.IndexEntries.Where(ie => ie.Offset > 0 && ie.Size > 0)) { //Read (unless it's our modified scenario) if (entry != Map.Scenario) { tagGroup = TagLookup.CreateTagGroup(entry.Root); reader.BaseStream.Seek(entry.Offset, SeekOrigin.Begin); tagGroup.Read(reader); } else { tagGroup = scenario; } //Create buffer using (VirtualStream stream = new VirtualStream(tagDataStream.Position)) using (BinaryWriter tagWriter = stream.CreateWriter()) using (BinaryReader tagReader = stream.CreateReader()) { //Write tagGroup.Write(tagWriter); //Recalculate raw addresses Helper.RecalculateRawAddresses(entry.Raws, entry.Root, stream, tagReader, tagWriter); //Setup tag entry.Offset = (uint)stream.MemoryAddress; entry.Size = (int)stream.Length; //Write to tag data stream writer.Write(stream.ToArray()); } } //Align tagDataStream.Align(4096); //Swap Map.SwapTagBuffer(tagDataStream.ToArray(), tagDataStream.MemoryAddress); } }
public BlockControl(BlockField blockField) : this() { Tags.GenerateControls(controlsFlowLayoutPanel, blockField.Create()); titleLabel.Text = blockField.Name; Field = blockField; }
/// <summary> /// Saves the given post model /// </summary> /// <param name="model">The post model</param> private async Task Save <T>(T model, bool isDraft) where T : Models.PostBase { var type = App.PostTypes.GetById(model.TypeId); var lastModified = DateTime.MinValue; if (type != null) { // Ensure category var category = await _db.Categories .FirstOrDefaultAsync(c => c.Id == model.Category.Id) .ConfigureAwait(false); if (category == null) { if (!string.IsNullOrWhiteSpace(model.Category.Slug)) { category = await _db.Categories .FirstOrDefaultAsync(c => c.BlogId == model.BlogId && c.Slug == model.Category.Slug) .ConfigureAwait(false); } if (category == null && !string.IsNullOrWhiteSpace(model.Category.Title)) { category = await _db.Categories .FirstOrDefaultAsync(c => c.BlogId == model.BlogId && c.Title == model.Category.Title) .ConfigureAwait(false); } if (category == null) { category = new Category { Id = model.Category.Id != Guid.Empty ? model.Category.Id : Guid.NewGuid(), BlogId = model.BlogId, Title = model.Category.Title, Slug = Utils.GenerateSlug(model.Category.Title), Created = DateTime.Now, LastModified = DateTime.Now }; await _db.Categories.AddAsync(category).ConfigureAwait(false); } model.Category.Id = category.Id; model.Category.Title = category.Title; model.Category.Slug = category.Slug; } // Ensure tags foreach (var t in model.Tags) { var tag = await _db.Tags .FirstOrDefaultAsync(tg => tg.Id == t.Id) .ConfigureAwait(false); if (tag == null) { if (!string.IsNullOrWhiteSpace(t.Slug)) { tag = await _db.Tags .FirstOrDefaultAsync(tg => tg.BlogId == model.BlogId && tg.Slug == t.Slug) .ConfigureAwait(false); } if (tag == null && !string.IsNullOrWhiteSpace(t.Title)) { tag = await _db.Tags .FirstOrDefaultAsync(tg => tg.BlogId == model.BlogId && tg.Title == t.Title) .ConfigureAwait(false); } if (tag == null) { tag = new Tag { Id = t.Id != Guid.Empty ? t.Id : Guid.NewGuid(), BlogId = model.BlogId, Title = t.Title, Slug = Utils.GenerateSlug(t.Title), Created = DateTime.Now, LastModified = DateTime.Now }; await _db.Tags.AddAsync(tag).ConfigureAwait(false); } t.Id = tag.Id; } t.Title = tag.Title; t.Slug = tag.Slug; } // Ensure that we have a slug if (string.IsNullOrWhiteSpace(model.Slug)) { model.Slug = Utils.GenerateSlug(model.Title, false); } else { model.Slug = Utils.GenerateSlug(model.Slug, false); } IQueryable <Post> postQuery = _db.Posts; if (isDraft) { postQuery = postQuery.AsNoTracking(); } var post = await postQuery .Include(p => p.Blocks).ThenInclude(b => b.Block).ThenInclude(b => b.Fields) .Include(p => p.Fields) .Include(p => p.Tags).ThenInclude(t => t.Tag) .FirstOrDefaultAsync(p => p.Id == model.Id) .ConfigureAwait(false); // If not, create a new post if (post == null) { post = new Post { Id = model.Id != Guid.Empty ? model.Id : Guid.NewGuid(), Created = DateTime.Now, LastModified = DateTime.Now }; model.Id = post.Id; if (!isDraft) { await _db.Posts.AddAsync(post).ConfigureAwait(false); } } else { post.LastModified = DateTime.Now; } post = _contentService.Transform <T>(model, type, post); if (isDraft) { post.Category = new Category { Id = model.Category.Id, BlogId = model.BlogId, Title = model.Category.Title, Slug = model.Category.Slug }; } // Transform blocks var blockModels = model.Blocks; if (blockModels != null) { var blocks = _contentService.TransformBlocks(blockModels); var current = blocks.Select(b => b.Id).ToArray(); // Delete removed blocks var removed = post.Blocks .Where(b => !current.Contains(b.BlockId) && !b.Block.IsReusable && b.Block.ParentId == null) .Select(b => b.Block); var removedItems = post.Blocks .Where(b => !current.Contains(b.BlockId) && b.Block.ParentId != null && removed.Select(p => p.Id).ToList().Contains(b.Block.ParentId.Value)) .Select(b => b.Block); if (!isDraft) { _db.Blocks.RemoveRange(removed); _db.Blocks.RemoveRange(removedItems); } // Delete the old page blocks post.Blocks.Clear(); // Now map the new block for (var n = 0; n < blocks.Count; n++) { IQueryable <Block> blockQuery = _db.Blocks; if (isDraft) { blockQuery = blockQuery.AsNoTracking(); } var block = blockQuery .Include(b => b.Fields) .FirstOrDefault(b => b.Id == blocks[n].Id); if (block == null) { block = new Block { Id = blocks[n].Id != Guid.Empty ? blocks[n].Id : Guid.NewGuid(), Created = DateTime.Now }; if (!isDraft) { await _db.Blocks.AddAsync(block).ConfigureAwait(false); } } block.ParentId = blocks[n].ParentId; block.CLRType = blocks[n].CLRType; block.IsReusable = blocks[n].IsReusable; block.Title = blocks[n].Title; block.LastModified = DateTime.Now; var currentFields = blocks[n].Fields.Select(f => f.FieldId).Distinct(); var removedFields = block.Fields.Where(f => !currentFields.Contains(f.FieldId)); if (!isDraft) { _db.BlockFields.RemoveRange(removedFields); } foreach (var newField in blocks[n].Fields) { var field = block.Fields.FirstOrDefault(f => f.FieldId == newField.FieldId); if (field == null) { field = new BlockField { Id = newField.Id != Guid.Empty ? newField.Id : Guid.NewGuid(), BlockId = block.Id, FieldId = newField.FieldId }; if (!isDraft) { await _db.BlockFields.AddAsync(field).ConfigureAwait(false); } block.Fields.Add(field); } field.SortOrder = newField.SortOrder; field.CLRType = newField.CLRType; field.Value = newField.Value; } // Create the page block post.Blocks.Add(new PostBlock { Id = Guid.NewGuid(), BlockId = block.Id, Block = block, PostId = post.Id, SortOrder = n }); } } // Remove tags var removedTags = new List <PostTag>(); foreach (var tag in post.Tags) { if (!model.Tags.Any(t => t.Id == tag.TagId)) { removedTags.Add(tag); } } foreach (var removed in removedTags) { post.Tags.Remove(removed); } // Add tags foreach (var tag in model.Tags) { if (!post.Tags.Any(t => t.PostId == post.Id && t.TagId == tag.Id)) { var postTag = new PostTag { PostId = post.Id, TagId = tag.Id }; if (isDraft) { postTag.Tag = new Tag { Id = tag.Id, BlogId = post.BlogId, Title = tag.Title, Slug = tag.Slug }; } post.Tags.Add(postTag); } } if (!isDraft) { await _db.SaveChangesAsync().ConfigureAwait(false); await DeleteUnusedCategories(model.BlogId).ConfigureAwait(false); await DeleteUnusedTags(model.BlogId).ConfigureAwait(false); } else { var draft = await _db.PostRevisions .FirstOrDefaultAsync(r => r.PostId == post.Id && r.Created > lastModified) .ConfigureAwait(false); if (draft == null) { draft = new PostRevision { Id = Guid.NewGuid(), PostId = post.Id }; await _db.PostRevisions .AddAsync(draft) .ConfigureAwait(false); } draft.Data = JsonConvert.SerializeObject(post); draft.Created = post.LastModified; await _db.SaveChangesAsync().ConfigureAwait(false); } } }
public GameEnder(ModeText modeText, BlockField field) { this.modeText = modeText; this.field = field; }