Exemple #1
0
 private void Start()
 {
     //Add the map incase its missing
     mapConfig = GameObject.FindGameObjectWithTag("Map").GetComponent <MapConfig>();
     xPosMax   = mapConfig.tileMap.mapSizeX * mapConfig.tileMap.offset;
     zPosMax   = mapConfig.tileMap.mapSizeY * mapConfig.tileMap.offset;
 }
Exemple #2
0
        public void OnSnapPointRequested(SnapPointRequestedEventArgs e)
        {
            // If there are no restrictions active, don't interfere
            if (!activeRestrictions.Any())
            {
                return;
            }

            double tolerance        = MapConfig.GetProjectedMouseTolerance(_context.Map);
            var    snapPointChecker = new SnapPointCandidateChecker(new Coordinate(e.PointX, e.PointY), tolerance);

            // First try to snap to an intersection of two restrictions (if possible)
            bool success = snapPointChecker.ContainsBetterCandidate(c => GetIntersectionBetweenRestrictions(c, tolerance));

            // Then try to snap to an intersection of a restriction with layer geometries
            if (!success)
            {
                success = snapPointChecker.ContainsBetterCandidate(c => GetIntersectionsWithLayerFeatures(c, tolerance));
            }

            // Try a regular snap to the restrictions
            if (!success)
            {
                success = snapPointChecker.ContainsBetterCandidateWithoutTolerance(GetSnapPoints);
            }

            e.SnappedX = snapPointChecker.BestSnapPoint.X;
            e.SnappedY = snapPointChecker.BestSnapPoint.Y;
            e.IsFinal  = true;
            e.IsFound  = true;
        }
Exemple #3
0
        /// <summary>
        /// Update map settings
        /// </summary>
        /// <param name="mapSettings"></param>
        internal void UpdateMapSettings(MapSetting mapSettings, string mapFile)
        {
            MapConfig config = readMapConfigFromFile(mapFile);

            config.map = mapSettings;
            this.saveMapConfigToFile(config, mapFile);
        }
Exemple #4
0
        private void reloadAllData()
        {
            mapData = MapConfig.loadMap(curActiveMapNo);
            setPal();
            int videoPageId = curActiveVideo;

            videos = new ImageList[4];
            var chunk = ConfigScript.getVideoChunk(videoPageId);

            for (int i = 0; i < 4; i++)
            {
                videos[i]           = new ImageList();
                videos[i].ImageSize = new Size(16, 16);
                var images = new Image[256];
                for (int t = 0; t < 256; t++)
                {
                    images[t] = UtilsGDI.ResizeBitmap(ConfigScript.videoNes.makeImage(t, chunk, curPal, i), 16, 16);
                }
                videos[i].Images.AddRange(images);
            }

            prepareBlocksPanel();
            mapScreen.Size = new Size(mapData.width * 16, mapData.height * 16);
            mapScreen.Invalidate();
        }
Exemple #5
0
        public void Export()
        {
            FTWorldMap worldMap = this;
            MapConfig  data     = new MapConfig();

            data.MapID      = worldMap.MapID;
            data.MapName    = worldMap.MapName;
            data.MapType    = worldMap.MapType;
            data.AllowPK    = worldMap.AllowPK;
            data.AllowRide  = worldMap.AllowRide;
            data.AllowTrade = worldMap.AllowTrade;
            ExportDCFGByElement <FTBorn, MapBorn>(data.MapBorns, worldMap);
            ExportDCFGByElement <FTArea, MapArea>(data.MapAreas, worldMap);
            ExportDCFGByElement <FTAreaMine, MapAreaMine>(data.MapAreaMines, worldMap);
            ExportDCFGByElement <FTAreaMonster, MapAreaMonster>(data.MapAreaMonsters, worldMap);
            ExportDCFGByElement <FTBarrier, MapBarrier>(data.MapBarriers, worldMap);
            ExportDCFGByElement <FTMutiPoint, MapMutiPoint>(data.MapMutiPoints, worldMap);
            ExportDCFGByElement <FTNpc, MapNpc>(data.MapNpcs, worldMap);
            ExportDCFGByElement <FTPath, MapPath>(data.MapPaths, worldMap);
            ExportDCFGByElement <FTPortal, MapPortal>(data.MapPortals, worldMap);
            ExportDCFGByElement <FTStep, MapStep>(data.MapSteps, worldMap);
            ExportDCFGByElement <FTTimer, MapTimer>(data.MapTimers, worldMap);
            ExportDCFGByElement <FTEvent, MapEvent>(data.MapEvents, worldMap);
            string fileName = string.Format("{0}/Resources/Text/Map/{1}.xml", Application.dataPath, data.MapID);

            data.Save(fileName);
        }
Exemple #6
0
        public void Import()
        {
            FTWorldMap worldMap = this;
            string     fileName = string.Format("Text/Map/{0}", worldMap.MapID);
            MapConfig  data     = new MapConfig();

            data.Load(fileName);
            worldMap.MapID      = data.MapID;
            worldMap.MapName    = data.MapName;
            worldMap.MapType    = data.MapType;
            worldMap.AllowPK    = data.AllowPK;
            worldMap.AllowRide  = data.AllowRide;
            worldMap.AllowTrade = data.AllowTrade;
            ImportEvents(data.MapEvents, worldMap);
            ImportDCFGByElement <FTBorn, MapBorn>(data.MapBorns, worldMap);
            ImportDCFGByElement <FTArea, MapArea>(data.MapAreas, worldMap);
            ImportDCFGByElement <FTAreaMine, MapAreaMine>(data.MapAreaMines, worldMap);
            ImportDCFGByElement <FTAreaMonster, MapAreaMonster>(data.MapAreaMonsters, worldMap);
            ImportDCFGByElement <FTBarrier, MapBarrier>(data.MapBarriers, worldMap);
            ImportDCFGByElement <FTMutiPoint, MapMutiPoint>(data.MapMutiPoints, worldMap);
            ImportDCFGByElement <FTNpc, MapNpc>(data.MapNpcs, worldMap);
            ImportDCFGByElement <FTPath, MapPath>(data.MapPaths, worldMap);
            ImportDCFGByElement <FTPortal, MapPortal>(data.MapPortals, worldMap);
            ImportDCFGByElement <FTStep, MapStep>(data.MapSteps, worldMap);
            ImportDCFGByElement <FTTimer, MapTimer>(data.MapTimers, worldMap);
            MapData = data;
        }
Exemple #7
0
    void Awake()
    {
        map          = GameObject.Find("Map");
        terrains     = GameObject.Find("Terrains");
        meshRenderer = map.GetComponent <MeshRenderer>();

        list = new List <MapConfig>();

        TextAsset obj  = (TextAsset)AssetDatabase.LoadAssetAtPath("Assets/Game/Config/stage_map.csv", typeof(TextAsset));
        string    text = obj.text;

        StringReader stringReader = new StringReader(text);

        stringReader.ReadLine();
        stringReader.ReadLine();
        while (true)
        {
            string line = stringReader.ReadLine();
            if (line == null)
            {
                break;
            }
            string[] csv = line.Split(';');
            if (csv.Length != 0 && !string.IsNullOrEmpty(csv[0]))
            {
                MapConfig mapConfig = new MapConfig();
                mapConfig.ParseCsv(csv, false);
                list.Add(mapConfig);
            }
        }

        index = 0;
        StartCoroutine(Doing());
    }
Exemple #8
0
    void OpenMap(MapConfig mapConfig)
    {
        Clear();

        if (mapConfig.id < 100)
        {
            meshRenderer.sharedMaterial.mainTexture = Resources.Load <Texture2D>(mapConfig.terrain);
            map.SetActive(true);
            terrains.SetActive(false);
        }
        else
        {
            GameObject prefab = Resources.Load <GameObject>(mapConfig.terrain);
            GameObject go     = GameObject.Instantiate(prefab);
            go.transform.SetParent(terrains.transform);
            go.transform.position = Vector3.zero;
            map.SetActive(false);
            terrains.SetActive(true);

            //				Transform map = go.transform.Find("Map");
            //				if(map != null)
            //				{
            //					MeshRenderer mapRenderer = map.GetComponent<MeshRenderer>();
            //					if(mapRenderer != null)
            //					{
            //						mapRenderer.sharedMaterial.shader = Shader.Find("ihaiu/Terrain_3Texture_1Shade");
            //					}
            //				}
        }

        PathUtil.CheckPath(root, false);
        string filename = root + mapConfig.id + ".png";

        ScreenshotTool.Shot(Camera.main, 150, 100, false, filename);
    }
Exemple #9
0
        public ProductViewModel ToViewModel(Product Product)
        {
            var config = new MapConfig().ToViewModel();
            var mapper = config.CreateMapper();

            return(mapper.Map <ProductViewModel>(Product));
        }
Exemple #10
0
        public IEnumerable <ProductViewModel> ToListViewModel(IEnumerable <Product> Products)
        {
            var config = new MapConfig().ToViewModel();
            var mapper = config.CreateMapper();

            return(mapper.Map <IEnumerable <Product>, IEnumerable <ProductViewModel> >(Products));
        }
        public QualityResultViewModel ToViewModel(QualityResult QualityResult)
        {
            var config = new MapConfig().ToViewModel();
            var mapper = config.CreateMapper();

            return(mapper.Map <QualityResultViewModel>(QualityResult));
        }
        public IEnumerable <QualityResultViewModel> ToListViewModel(IEnumerable <QualityResult> QualityResults)
        {
            var config = new MapConfig().ToViewModel();
            var mapper = config.CreateMapper();

            return(mapper.Map <IEnumerable <QualityResult>, IEnumerable <QualityResultViewModel> >(QualityResults));
        }
Exemple #13
0
    private void DisplayBackGround()
    {
        var sceneId = LoadingPresenter.Instance.sceneId.Fetch();
        var config  = MapConfig.Get(sceneId);

        m_BackGround.SetSprite(config.backGround);
    }
Exemple #14
0
        public static void Init(string fileName)
        {
            MapConfig <SongDataConfig> ser = new MapConfig <SongDataConfig>();

            ser.FileName = fileName;
            Config       = ser.ReadEntity();
        }
Exemple #15
0
        public IObservable <Unit> Load(Transform mapTransform, MapConfig mapConfig)
        {
            return(_tilesPositionService
                   .GetMostRecent(mapTransform.position.y)
                   .Zip(_boardItemsRepository.GetMostRecent(), (positions, items) => (positions, items))
                   .Select(
                       tuple =>
            {
                var(positions, items) = tuple;

                foreach (var item in items)
                {
                    var(component, gameObject) = _holderFactory.Create(mapTransform, false);
                    var flattenedIndex = _coordinateService.GetFlattenArrayIndexFromAxialCoordinate(
                        item.Coordinate.X,
                        item.Coordinate.Z,
                        mapConfig
                        );

                    gameObject.transform.position = positions[flattenedIndex];
                    gameObject.transform.parent = mapTransform;

                    component.Initialize(item);
                }

                _finishedLoadingEventStream.OnNext(Unit.Default);
                return Unit.Default;
            }
                       ));
        }
        public IEnumerable <LaboratoryViewModel> ToListViewModel(IEnumerable <Laboratory> Laboratorys)
        {
            var config = new MapConfig().ToViewModel();
            var mapper = config.CreateMapper();

            return(mapper.Map <IEnumerable <Laboratory>, IEnumerable <LaboratoryViewModel> >(Laboratorys));
        }
        public LaboratoryViewModel ToViewModel(Laboratory Laboratory)
        {
            var config = new MapConfig().ToViewModel();
            var mapper = config.CreateMapper();

            return(mapper.Map <LaboratoryViewModel>(Laboratory));
        }
Exemple #18
0
        public void Load_xml_config_with_entity_non_existing_map_should_throw()
        {
            string    testMapfile = Path.Combine(SessionHelper.BaseDirectory, "TestFiles", "MapConfigTests", "Test002.data.xml");
            MapConfig config      = new MapConfig();

            Assert.Throws <MappingException>(() => config.Load(testMapfile));
        }
Exemple #19
0
        public void SnapSlope(ICoordinate anchor, double slope, ICoordinate offsetAnchor = null, bool needsUserInput = true, int handle = 0)
        {
            var restriction = new LinearRestriction(anchor, slope, handle);

            double offset = 0;

            if (offsetAnchor != null)
            {
                double tolerance = MapConfig.GetProjectedMouseTolerance(_context.Map);
                offset = restriction.GetOffsetDistance(offsetAnchor, tolerance);
                restriction.OffsetByDistance(offset);
            }

            AddRestriction(restriction);

            if (!needsUserInput)
            {
                return;
            }

            void inputAction(double value)
            {
                restriction.OffsetByDistance(value);
                restriction.RefreshGuideline(_context.Map as IMap);
            }

            // Show input box to end-user to enter the bearing
            // live updating the map with the snap line
            RequestUserInput(
                inputAction,
                "Offset:",
                offset,
                anchor
                );
        }
Exemple #20
0
        public void Load_statement_not_depending_on_entity_with_no_name_should_throw()
        {
            string    testMapfile = Path.Combine(SessionHelper.BaseDirectory, "TestFiles", "MapConfigTests", "Test_statement_invalid_missing_name.xml");
            MapConfig config      = new MapConfig();

            Assert.Throws <MappingSerializationException>(() => config.Load(testMapfile));
        }
Exemple #21
0
        /// <summary>
        /// Generates the code for each entity map.
        /// </summary>
        /// <param name="templateFile">The templateFile.</param>
        /// <param name="workingFolder">The working folder.</param>
        /// <param name="mapfile">The mapfile.</param>
        /// <param name="fileNameFunction">The file name function.</param>
        /// <param name="excludedTables">The excluded tables.</param>
        /// <param name="properties"></param>
        public void GenerateCodeForEachEntityMap(string templateFile, string workingFolder, string mapfile,
                                                 Func <string, int?, string> fileNameFunction = null, IDictionary <string, string> properties = null, params string[] excludedTables)
        {
            var project = MapConfig.Create(mapfile, true);

            GenerateCodeForEachEntityMap(templateFile, workingFolder, project, fileNameFunction, properties, excludedTables);
        }
Exemple #22
0
        public void Load_generic_statement_without_operation_type_should_throw()
        {
            string    testMapfile = Path.Combine(SessionHelper.BaseDirectory, "TestFiles", "MapConfigTests", "Test_statement_invalid_statement_operationType.xml");
            MapConfig config      = new MapConfig();

            Assert.Throws <MappingSerializationException>(() => config.Load(testMapfile));
        }
Exemple #23
0
        public UserViewModel ToViewModel(User User)
        {
            var config = new MapConfig().ToViewModel();
            var mapper = config.CreateMapper();

            return(mapper.Map <UserViewModel>(User));
        }
Exemple #24
0
        public IEnumerable <UserViewModel> ToListViewModel(IEnumerable <User> Users)
        {
            var config = new MapConfig().ToViewModel();
            var mapper = config.CreateMapper();

            return(mapper.Map <IEnumerable <User>, IEnumerable <UserViewModel> >(Users));
        }
Exemple #25
0
        private void reloadAllData()
        {
            mapDatas = MapConfig.loadMap(curActiveMapNo);
            setPal();
            int videoPageId = curActiveVideo;

            videos = new Image[4][];
            var chunk = ConfigScript.getVideoChunk(videoPageId);

            for (int i = 0; i < 4; i++)
            {
                var images = new Image[256];
                for (int t = 0; t < 256; t++)
                {
                    images[t] = UtilsGDI.ResizeBitmap(ConfigScript.videoNes.makeImage(t, chunk, curPal, i), 16, 16);
                }
                videos[i] = images;
            }

            blocksScreen.Invalidate();

            mapScreen.Size = new Size(mapDatas[0].width * 16, mapDatas[0].height * 16);
            mapScreen.Invalidate();

            mapScreen2.Visible  = showSecondNametable;
            mapScreen2.Size     = mapScreen.Size;
            mapScreen2.Location = new Point(mapScreen.Location.X + mapScreen.Width, mapScreen2.Location.Y);
            mapScreen2.Invalidate();
        }
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     MapConfig.RegisterMap();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 }
Exemple #27
0
 private MapUtil()
 {
     mapConfig = MapConfig.getInstance();
     ballConfig = BallConfig.getInstance();
     row = Convert.ToInt32(mapConfig.MapWidth() / mapConfig.TileWidth());
     col = Convert.ToInt32(mapConfig.MapHeight() / mapConfig.TileHeight());
 }
Exemple #28
0
        public Config(string configSuffix = "")
        {
            configSuffix = configSuffix.Trim().Replace(" ", "");
            if (configSuffix != "")
            {
                _configFile = "config_" + configSuffix + ".config";
            }

            var appData = (string)ConfigItems.Debug_Logpath.Default;

            if (!Directory.Exists(appData))
            {
                Directory.CreateDirectory(appData);
            }

            string config = Path.Combine(appData, _configFile);

            _c = new MapConfig(config);

            Fields.Elpis_HotKeys = new Dictionary <int, HotkeyConfig>();

            //If not config file, init with defaults then save
            if (!File.Exists(config))
            {
                LoadConfig();
                SaveConfig();
            }
        }
Exemple #29
0
        /// <summary>
        /// Save config as JSON-file
        /// </summary>
        /// <param name="mapConfig"></param>
        private void saveMapConfigToFile(MapConfig mapConfig)
        {
            string file       = String.Format("{0}App_Data\\{1}", HostingEnvironment.ApplicationPhysicalPath, this.mapFile);
            string jsonOutput = JsonConvert.SerializeObject(mapConfig, Formatting.Indented);

            System.IO.File.WriteAllText(file, jsonOutput);
        }
    private Map Generate()
    {
        MapConfig config = new MapConfig();

        config.type = MapType.A;
        config.size = new int[2] {
            (int)size.x, (int)size.y
        };
        config.seed              = seed;
        config.frequency         = frequency;
        config.amplitude         = amplitude;
        config.persistance       = persistance;
        config.octaves           = octaves;
        config.bushLevel         = bushLevel;
        config.targetPointWidth  = (int)targetPointSize.x;
        config.targetPointHeight = (int)targetPointSize.y;
        config.numBirthPoints    = numBirthPoints;
        config.birthPointWidth   = (int)birthPointSize.x;
        config.birthPointHeight  = (int)birthPointSize.y;
        config.pathBreadth       = pathBreadth;
        config.pathCurvity       = pathCurvity;

        map = new Map(config);
        return(map);
    }
Exemple #31
0
        public void TestInitialize()
        {
            var config = ConfigurationFactory.Configuration;

            MapConfig = config.MapConfig;
            generator = new MapGenerator(config);
        }
        private static void ConfigureFileMaps(IImageConverter imageConverter)
        {
            // Map a file to a base64 string if available.
            var fileConfig = new MapConfig<object, object>();

            fileConfig.AfterMapAction = (content, model) =>
            {
                var fileProperties = model.GetType().GetProperties().Where(pr => pr.GetCustomAttributes(typeof(ImageAttribute), true).Any());

                foreach (var fileProperty in fileProperties)
                {
                    var file = model.GetPropertyValue(fileProperty.Name) as FileDisplayModel;
                    var attribute = fileProperty.GetAttribute<ImageAttribute>();
                    var sizeX = string.IsNullOrWhiteSpace(attribute.WidthProperty) ? attribute.Width : (int)model.GetPropertyValue(attribute.WidthProperty);
                    var sizeY = string.IsNullOrWhiteSpace(attribute.HeightProperty) ? attribute.Height : (int)model.GetPropertyValue(attribute.HeightProperty);
                    string path = null;

                    if (file != null && file.Folder != null)
                    {
                        var imagePath = string.Format("{0}.{1}", System.IO.Path.Combine(file.Folder, file.Path, file.FileName), file.Extension);
                        path = imageConverter.ImageAsPath(imagePath, sizeX, sizeY, attribute.KeepAspectRatio);
                    }

                    if (model.HasProperty(fileProperty.Name + "Path"))
                    {
                        model.SetPropertyValue(fileProperty.Name + "Path", path);
                    }
                }
            };

            DataMapper.RegisterMapConfig(fileConfig);
        }
        private void Init()
        {
            if (!_initialized)
            {
                var config = new MapConfig<IntEntity, IntEntityViewModel>();
                config.MembersToMap.Add(d => d.EntityName, s => s.Name);
                config.MembersToMap.Add(d => d.Order, s => s.Number);
                config.MembersToMap.Add(d => d.Required, s => s.IsRequired);
                config.MembersToMap.Add(d => d.Date, s => s.StartDate);
                DataMapper.RegisterMapConfig(config);

                var returnConfig = new MapConfig<IntEntityViewModel, IntEntity>();
                returnConfig.MembersToMap.Add(d => d.Name, s => s.EntityName);
                returnConfig.MembersToMap.Add(d => d.Number, s => s.Order);
                returnConfig.MembersToMap.Add(d => d.IsRequired, s => s.Required);
                returnConfig.MembersToMap.Add(d => d.StartDate, s => s.Date);
                DataMapper.RegisterMapConfig(returnConfig);

                var testConfig = new MapConfig<TestEntity, TestEntityViewModel>();
                testConfig.MembersToIgnore.Add(d => d.Description);
                DataMapper.RegisterMapConfig(testConfig);
            }
        }
        internal static void ConfigureEntityMaps()
        {
            if (_isInitialized)
            {
                return;
            }

            DataMapper.CreateMap<PlatformEntity, SelectRelationDto<Guid>>().ForMember(s => s.EntityId, c => c.MapFrom(p => p.Id));

            var idConfig = new MapConfig<IContent, EntityListModel>();
            idConfig.MembersToMap.Add(d => d.Id, s => s.EntityId);
            DataMapper.RegisterMapConfig(idConfig);

            var listUrlConfig = new MapConfig<IContent, EntityListModel>();
            listUrlConfig.MembersToMap.Add(d => d.Url, s => s.Entity.Url);
            DataMapper.RegisterMapConfig(listUrlConfig);

            var detailUrlConfig = new MapConfig<IContent, EntityViewModel>();
            detailUrlConfig.MembersToMap.Add(d => d.Url, s => s.Entity.Url);
            DataMapper.RegisterMapConfig(detailUrlConfig);

            var entityCollectionConfig = new MapConfig<PlatformBaseViewModel, PlatformEntity>();
            entityCollectionConfig.MembersToIgnore.Add(d => d.EntityType);
            DataMapper.RegisterMapConfig(entityCollectionConfig);

            var entityConfig = new MapConfig<EntityViewModel, IContent>();

            entityConfig.AfterMapAction = (x, y) =>
            {
                var content = y as IContent;
                var model = x as EntityViewModel;

                if (content.Entity == null)
                {
                    content.Entity = new PlatformEntity();
                }

                content.Entity.Url = model.Url;
            };

            DataMapper.RegisterMapConfig(entityConfig);

            _isInitialized = true;
        }
        internal void RegisterMappings()
        {
            ConfigureFilterMaps();
            ConfigureEntityMaps();
            ConfigureAuditMaps();
            ConfigureFileMaps(this._imageConverter);

            DataMapper.CreateMap<Vocabulary, VocabularyViewModel>().AfterMap((vocabulary, model) =>
            {
                model.CanEdit = StrixPlatform.User.IsInRole(CmsRoleNames.EDITORROLES);
            });

            DataMapper.CreateMap<Term, TermViewModel>();
            var tagConfig = new MapConfig<IContent, EntityViewModel>();
            tagConfig.MembersToMap.Add(d => d.Tags, s => s.Entity.Tags);
            DataMapper.RegisterMapConfig(tagConfig);

            DataMapper.CreateMap<Comment, CommentViewModel>()
                .ForMember(cv => cv.CreatedBy, ce => ce.MapFrom(co => StrixCms.GetUserName(co.CreatedByUserId)))
                .ForMember(cv => cv.CreatedByEmail, ce => ce.MapFrom(co => StrixCms.GetUserEmail(co.CreatedByUserId)))
                .ForMember(cv => cv.UpdatedBy, ce => ce.MapFrom(co => StrixCms.GetUserName(co.UpdatedByUserId)));
            DataMapper.CreateMap<CommentViewModel, Comment>()
                .ForMember(co => co.CreatedByUserId, ce => ce.Ignore())
                .ForMember(co => co.CreatedOn, ce => ce.Ignore());

            DataMapper.CreateMap<File, FileDisplayModel>();
            DataMapper.CreateMap<FileDisplayModel, File>().ForAllMembers(mem => mem.Ignore());
            DataMapper.CreateMap<MailContentTemplate, MailContentTemplateViewModel>();

            ConfigureHtmlEncoding();
        }
        private static void ConfigureHtmlEncoding()
        {
            Action<object, object> decodingAction = (x, y) =>
            {
                object source = x as IContent == null ? x as Comment == null ? null : (object)(x as Comment) : (object)(x as IContent);
                var target = y as EntityViewModel == null ? y as CommentViewModel == null ? null : (object)(y as CommentViewModel) : (object)(y as EntityViewModel);

                if (source != null && target != null)
                {
                    foreach (var allowHtmlProperty in target.GetType().GetProperties().Where(p => p.HasAttribute<AllowHtmlAttribute>()))
                    {
                        var decodedValue = Web.Helpers.HtmlDecode((string)source.GetPropertyValue(allowHtmlProperty.Name), false);
                        target.SetPropertyValue(allowHtmlProperty.Name, decodedValue);
                    }
                }
            };

            var decodeEntityConfig = new MapConfig<IContent, EntityViewModel>();
            decodeEntityConfig.AfterMapAction = decodingAction;
            DataMapper.RegisterMapConfig(decodeEntityConfig);

            var decodeCommentConfig = new MapConfig<Comment, CommentViewModel>();
            decodeCommentConfig.AfterMapAction = decodingAction;
            DataMapper.RegisterMapConfig(decodeCommentConfig);

            Action<object, object> encodingAction = (x, y) =>
            {
                var source = x as EntityViewModel == null ? x as CommentViewModel == null ? null : (object)(x as CommentViewModel) : (object)(x as EntityViewModel);
                object target = y as IContent == null ? y as Comment == null ? null : (object)(y as Comment) : (object)(y as IContent);

                if (source != null && target != null)
                {
                    foreach (var allowHtmlProperty in source.GetType().GetProperties().Where(p => p.HasAttribute<AllowHtmlAttribute>()))
                    {
                        var encodedValue = Web.Helpers.HtmlEncode((string)source.GetPropertyValue(allowHtmlProperty.Name));
                        target.SetPropertyValue(allowHtmlProperty.Name, encodedValue);
                    }
                }
            };

            var encodeEntityConfig = new MapConfig<EntityViewModel, IContent>();
            encodeEntityConfig.AfterMapAction = encodingAction;
            DataMapper.RegisterMapConfig(encodeEntityConfig);

            var encodeCommentConfig = new MapConfig<CommentViewModel, Comment>();
            encodeCommentConfig.AfterMapAction = encodingAction;
            DataMapper.RegisterMapConfig(encodeCommentConfig);
        }
Exemple #37
0
 public static MapConfig getInstance()
 {
     if (m_instance == null)
         m_instance = new MapConfig();
     return m_instance;
 }
        private static void ConfigureAuditMaps()
        {
            Action<object, object> auditAction = (x, y) =>
            {
                var audit = x as IAudit;
                var model = y as AuditViewModel;
                model.CanEdit = StrixPlatform.User.IsInRole(CmsRoleNames.EDITORROLES) || model.CreatedByUserId == StrixPlatform.User.Id;
                model.UpdatedBy = StrixCms.GetUserName(audit.UpdatedByUserId);
                model.CreatedBy = StrixCms.GetUserName(audit.CreatedByUserId);

                var content = x as IContent;

                if (content != null)
                {
                    if (model is EntityViewModel && content.PublishedByUserId.HasValue)
                    {
                        ((EntityViewModel)model).PublishedBy = StrixCms.GetUserName(content.PublishedByUserId.Value);
                    }
                }
            };

            var listAuditConfig = new MapConfig<AuditViewModel, AuditViewModel>();
            listAuditConfig.AfterMapAction = auditAction;
            DataMapper.RegisterMapConfig(listAuditConfig);

            var entityAuditConfig = new MapConfig<IContent, AuditViewModel>();
            entityAuditConfig.AfterMapAction = auditAction;
            DataMapper.RegisterMapConfig(entityAuditConfig);

            var auditReturnConfig = new MapConfig<EntityViewModel, IContent>();
            auditReturnConfig.MembersToIgnore.Add(d => d.IsCurrentVersion);
            auditReturnConfig.MembersToIgnore.Add(d => d.CreatedByUserId);
            auditReturnConfig.MembersToIgnore.Add(d => d.CreatedOn);
            auditReturnConfig.MembersToIgnore.Add(d => d.UpdatedByUserId);
            auditReturnConfig.MembersToIgnore.Add(d => d.UpdatedOn);
            DataMapper.RegisterMapConfig(auditReturnConfig);
        }