Example #1
0
        static void Main(string[] args)
        {
            var settings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Error,
                Error            = JsonLoader.DeserializationErrorHandler,
                ContractResolver = new PropertyContractResolver(PropertyMapperHelper.PriceDeserialization)
            };

            ILoader dataLoader = new JsonLoader();
            var     drinks     = dataLoader.Load <Drink>(Path.Combine("Data", "prices.json"), settings);

            settings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Error,
                Error            = JsonLoader.DeserializationErrorHandler,
                ContractResolver = new ErrorContractResolver()
            };
            var orders   = dataLoader.Load <Order>(Path.Combine("Data", "orders.json"), settings);
            var payments = dataLoader.Load <Payment>(Path.Combine("Data", "payments.json"), settings);

            ICalculator calculator            = new StandardCalculator();
            var         totalCostsForUsers    = calculator.CalculateTotalCosts(orders, drinks);
            var         totalPaymentsForUsers = calculator.CalculateTotalPayments(payments);
            var         balanceForUsers       = calculator.CalculateBalance(totalCostsForUsers, totalPaymentsForUsers).ToList();

            settings = new JsonSerializerSettings
            {
                Formatting       = Formatting.Indented,
                ContractResolver = new PropertyContractResolver(PropertyMapperHelper.BalanceSerialization)
            };
            dataLoader.Save(Path.Combine("Data", "result.json"), balanceForUsers, settings);
            Console.WriteLine($"The program has finished. The result was stored to {Path.Combine(Directory.GetCurrentDirectory(), "Data", "result.json")}");
        }
Example #2
0
        /// <summary>
        /// Saves the changes made to an entity
        /// list
        /// </summary>
        /// <typeparam name="T">Entity type</typeparam>
        /// <param name="entities">Entity list reference</param>
        /// <returns>ComplexResponse list of Primary key inserted/updated</returns>
        public static async Task <BasicResponse> Save <T>(this List <T> entities, SqlTransaction transaction = null) where T : class, IEntity, new()
        {
            //Verify entity state
            if (entities.IsNotValid())
            {
                return(new ModelResponse <List <long> >(false, @"The specified entity list is not valid for save operation."));
            }
            string configUrl = $@"{AppDomain.CurrentDomain.BaseDirectory}Storage\SqlServer\DataProvider.json";

            //Verify configuration file
            if (!configUrl.IsFilePath(out _))
            {
                return(new ModelResponse <List <long> >(false, @"The configuration file is not present, the task could not be completed as requested."));
            }
            JsonLoader <Configuration> jsonLoader = new JsonLoader <Configuration>(configUrl);
            await jsonLoader.Load();

            Configuration configuration    = jsonLoader.Instance;
            string        connectionString = configuration.Values
                                             .GetFirst <string>(@"ConnectionString");

            //Verify connection string value
            if (connectionString.IsNotValid())
            {
                return(new ModelResponse <List <long> >(false, @"The specified connection string in the configuration file is not valid for its use, the task could not be completed as requested."));
            }
            //Save entity list
            SqlServerDataProvider <T> provider = new SqlServerDataProvider <T>(connectionString);

            return(await provider.Save(entities, transaction));
        }
Example #3
0
        public AnimatedEntity(string entityName, string twitchHeadName, bool isAvatar, string twitchUseranme, Color tintColor)
        {
            string EntityFilePath = Utility.CONTENT_DIR + "/entities/" + entityName;

            AnimatedEntityData = JsonLoader.Load <AnimatedEntityData>(EntityFilePath);
            var defaultAnim = AnimatedEntityData.Animations[AnimatedEntityData.DefaultAnimation];

            Sprite = new Spritemap(Library.GetTexture(EntityFilePath + ".png"), defaultAnim.FrameWidth, defaultAnim.FrameHeight)
            {
                OriginX = defaultAnim.OriginX,
                OriginY = defaultAnim.OriginY
            };

            foreach (var animation in AnimatedEntityData.Animations.Values)
            {
                Sprite.Add(animation.Name, animation.Frames, animation.FPS, true);
            }

            if (AnimatedEntityData.ShaderName != null)
            {
                Shader shader = new Shader(Shader.ShaderType.Fragment, Library.GetText("content/shaders/" + AnimatedEntityData.ShaderName));
                Sprite.Shader = shader;
                //chromaKey.SetAsCurrentTexture("sampler2D");
                shader.SetParameter("color", tintColor);
            }

            Sprite.Play(AnimatedEntityData.DefaultAnimation);
            AddComponent(Sprite);

            CreateHead(twitchHeadName, isAvatar);
            CreateName(twitchUseranme);
        }
Example #4
0
        /// <summary>
        /// 設定ファイル読み込み
        /// </summary>
        /// <param name="targetSettingFileName"></param>
        private void LoadModelSetting(string ModelPath)
        {
            try
            {
                //モデルパス取得
                this.ModelPath = ModelPath;
                string targetSettingFilePath = this.ModelPath + ModelPathDefine.LIPLIS_MODEL_JSON;
                string settingPath           = ModelPath + ModelPathDefine.SETTINGS;
                string chatSettingPath       = settingPath + ModelPathDefine.LIPLIS_CHAT_SETTING;
                string toneSettingPath       = settingPath + ModelPathDefine.LIPLIS_TONE_SETTING;

                // LiplisModel.jsonファイルを読み込む
                // 原則としてApplication.dataPath配下。
                // プリセットモデルの場合はリソース配下となる。
                modelSetting = JsonLoader <LiplisMoonlightModel> .Load(targetSettingFilePath);

                //口調設定
                toneSetting = JsonLoader <LiplisToneSetting> .Load(chatSettingPath);

                //固定セリフ設定
                chatSetting = JsonLoader <LiplisChatSetting> .Load(chatSettingPath);
            }
            catch (Exception ex)
            {
                //ファイル読み込みに失敗したらエクセプション発生
                throw new ApplicationException("LiplisModelLive2d:LoadModelSetting:モデルの読み込みに失敗しました!", ex);
            }
        }
Example #5
0
        public override void Update(Entity entity, GameTime gameTime)
        {
            var player    = entity.Get <Player>();
            var rigidbody = entity.Get <Rigidbody>();
            var renderer  = entity.Get <SpriteRenderer>();

            renderer.Texture = player.LasersCount > 0
                ? _chargedTexture
                : _emptyTexture;

            if (rigidbody.Acceleration.Length() > 0 && player.ExhaustRenderer is null)
            {
                player.ExhaustRenderer           = new SpriteRenderer();
                player.ExhaustAnimation          = _jsonLoader.Load <Animation>("animations/exhaust");
                player.ExhaustAnimation.Renderer = player.ExhaustRenderer;

                entity.Attach(player.ExhaustRenderer);
                entity.Attach(player.ExhaustAnimation);
            }
            else if (player.ExhaustRenderer is not null && rigidbody.Acceleration == Vector2.Zero)
            {
                entity.DeAttach(player.ExhaustAnimation !);
                entity.DeAttach(player.ExhaustRenderer);

                player.ExhaustRenderer  = null;
                player.ExhaustAnimation = null;
            }
        }
Example #6
0
        public void Execute(ServerContext context, ControllerCollection controllerCollection)
        {
            IDatabaseConnection databaseConnection = null;
            var data     = JsonLoader.Load(@"ServerCore/ServerConfig.json");
            var dbConfig = data.GetNode("database");

            switch (dbConfig.GetString("type"))
            {
            case "SQL":
                databaseConnection = new MongoDataBaseConnection(dbConfig.GetNode("settings"));
                break;
            }

            databaseConnection?.OpenConnect();

            if (databaseConnection.IsConnected)
            {
                ServerLoggerModel.Log(TypeLog.Info, "Connected to database");
            }
            else
            {
                ServerLoggerModel.Log(TypeLog.Fatal, "The server did not start correctly due to problems with the connection to the database");
            }

            context.DatabaseConnection = databaseConnection;
        }
Example #7
0
        public DynamicSceneWorld(string startingScene, string spawnEntrance)
        {
            SoundManager.PlayMusic(Utility.MainConfig.CurrentMusic);
            avatar = new Avatar(JsonLoader.Load <InteractiveObjectData>("objects/Avatar/MetaData"), "Avatar", new float[1, 1] {
                { 1 }
            }, new InteractiveObjectRef());
            avatar.PlayAnimation("Idle");

            cursor = new Cursor();
            VeryGenericInventorySystem = new Inventory(avatar, this);

            pathNodes = new PathNode[FP.Width / TileSize, FP.Height / TileSize];
            for (int x = 0; x < pathNodes.GetLength(0); x++)
            {
                for (int y = 0; y < pathNodes.GetLength(1); y++)
                {
                    pathNodes[x, y] = new PathNode(null, x * TileSize + TileSize / 2, y * TileSize + TileSize / 2, false);
                }
            }
            for (int x = 0; x < pathNodes.GetLength(0); x++)
            {
                for (int y = 0; y < pathNodes.GetLength(1); y++)
                {
                    PathNode.ConnectedNodes[pathNodes[x, y]] = Utility.SelectTilesAroundTile(x, y, pathNodes);
                }
            }
            nodeGridEntity = new Entity();
            nodeGridEntity.AddComponent <Grid>(nodeGrid = new Grid(FP.Width, FP.Height, TileSize, TileSize));
            nodeGridEntity.Type = "ClickMap";
            //Add(nodeGridEntity);

            uncompletedEvents = GameEvent.loadGameEvents("./content/events/");

            LoadScene(startingScene, spawnEntrance);
        }
Example #8
0
 public void TestMethod1()
 {
     var test5 = JsonLoader.Load <dynamic>("json1.json");
     var test1 = XmlLoader.Load <Test>("XMLFile1.xml");
     var test2 = XmlLoader.Load <XElement>("XMLFile1.xml");
     //var test3 = XmlLoader.Load<object[]>("XMLFile1.xml");
     var test4 = Conv(test2);
 }
 protected override void OnAwake()
 {
     _goldData       = new GoldData();
     _jsonLoader     = new JsonLoader();
     _userData       = _jsonLoader.Load();
     _goldData._Gold = _userData._Gold;
     _goldData.OnGoldChangedEvent += Save;
 }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        public HttpRequestTests()
        {
            JsonLoader <Configuration> config = new JsonLoader <Configuration>($@"{AppDomain.CurrentDomain.BaseDirectory}Tools\Http\HttpConfig.json");

            config.Load()
            .Wait();
            BinUrlBase = config.Instance.Values.GetFirst <string>(@"UrlBin");
            BinMethod  = config.Instance.Values.GetFirst <string>(@"MethodBin");
        }
Example #11
0
        /// <summary>
        /// Creates a new Sql Server Command tests instance
        /// </summary>
        public SqlServerCommandTests()
        {
            JsonLoader <Configuration> config = new JsonLoader <Configuration>($@"{AppDomain.CurrentDomain.BaseDirectory}Storage\SqlServer\DataProvider.json");

            config.Load()
            .Wait();
            ConnectionString = config.Instance.Values
                               .GetFirst <string>(@"ConnectionString");
        }
Example #12
0
        public StartScreenWorld()
        {
            string configPath = "MainConfig";

            if (File.Exists(JsonLoader.PATH_PREFIX + JsonWriter.SAVE_PREFIX + configPath + JsonLoader.RESOURCE_EXT))
            {
                configPath = JsonWriter.SAVE_PREFIX + configPath;
            }

            Utility.MainConfig = JsonLoader.Load <MainConfig>(configPath);
            start   = new Text("Start [Enter]");
            start.X = (FP.Width / 2) - (start.Width / 2);
            start.Y = (FP.Height / 3) + 25;

            instructions   = new Text("Instructions [Space]");
            instructions.X = (FP.Width / 2) - (instructions.Width / 2);
            instructions.Y = (FP.Height / 3) + 50;

            // Testing stuff
            //SceneData sd = JsonLoader.LoadStream<SceneData>("{Name: \"testscene\", Objects: [{Name: \"Cool Beans\", Position: {X: 40, Y:50}, DefaultAnimation: \"Idle\"}], Regions: [] }");
            //var iobj = JsonLoader.Load<InteractiveObjectData>("Testdata");

//            TextBox box = new TextBox("Testing! dkfn aiofnosdian fiasdiof asdio fnasdion fioasdnf oasdnio fsdnoifn asiodnf oasdn fioasdnfio nasdiof nioasdnf ioasdnf iosadnf sndoafn asdiofn ioasdnf ioasdnfo iasdnoif nsdio fnaiosdnf oiasdnf onfiosdfioasndiofnasodn fd af sd fsdjf sdajf huisdafsduif uisdhf sdhi fasdui fhasduifh uisdh fuiasdhfiwehiufhasdufh wuhgidfb gidf giuadfhgiadhilgh weuifh uisdfh uiasdgh uidfh gfui asdh fpwe ip weipfj sdipj fkasdf lkasdnfjkwenuohweruoig adui ghodg ipsdj fosdfljasdnkfbweruih uisdh ud sh sdhof hauodhfbsda bnvbgnbvhyjhnbgdhyjfnbhjcdn vjdn vbnhjcm njcm nhmjc bnh mc njm c nm cnm vf cn mcbxn cnh  cbhnxs xcbxns cbhxjzmx cbvchxnjzsmn cbz cbxnhsjax cbxnhzsx dsf sd fds asd sad fasd fjsdah isdaf shadiufhvb chnbvhndhfg bidfhgh yudbhdbyshg idyfh byusdfg yusdfysdgyufg yusdg fsduayf gyusdg fyusd yufgsd ufgufasd fasd fasdf sdf ttt");
//            box.show();
//
//            Timer t = new Timer(3000);
//            t.Elapsed += new ElapsedEventHandler( (Object sender, ElapsedEventArgs e) => {
//                                                  t.Stop();
//                                                  List<CommandData> cl = new List<CommandData>();
//                                                  var c = new CommandData();
//                                                  c.Name = "Talk";
//                                                  c.Actions = null;
//                                                  cl.Add(c);
//
//                                                  c = new CommandData();
//                                                  c.Name = "Use";
//                                                  c.Actions = null;
//                                                  cl.Add(c);
//
//                                                  c = new CommandData();
//                                                  c.Name = "Look";
//                                                  c.Actions = null;
//                                                  cl.Add(c);
//
//                                                  CommandWheel wheel = new CommandWheel(cl.ToArray());
//
//
//                                                  Add(wheel);
//                                                 });
//
//            t.Start();
//            Add(box);
            //Add(wheel);

            AddGraphic(start);
//            AddGraphic(instructions);
        }
Example #13
0
        /// <summary>
        /// Creates a new query condition tests instance
        /// </summary>
        public QueryConditionTests()
        {
            JsonLoader <Configuration> config = new JsonLoader <Configuration>($@"{AppDomain.CurrentDomain.BaseDirectory}Storage\SqlServer\DataProvider.json");

            config.Load()
            .Wait();
            ConnectionString = config.Instance.Values
                               .GetFirst <string>(@"ConnectionString");
            DataProvider = new SqlServerDataProvider <TestingEntity>(ConnectionString);
        }
Example #14
0
        public void Loading_WithEmptyResponseData_ReturnsEmptyDictionary()
        {
            var rawResponseData = string.Empty;

            var loader = new JsonLoader();

            var result = loader.Load(rawResponseData);

            Assert.Empty(result);
        }
Example #15
0
        public void Loading_WithNullResponseData_ThrowsException()
        {
            string rawResponseData = null;

            var loader = new JsonLoader();

            Assert.Throws <ArgumentNullException>(() =>
            {
                loader.Load(rawResponseData);
            });
        }
Example #16
0
        public static MainConfig LoadMainConfig(string path = null)
        {
            var config = JsonLoader.Load <MainConfig>(path ?? MainConfig.MainConfigPath, false);

            if (String.IsNullOrWhiteSpace(config.OverrideOauth))
            {
                config.OverrideBotUser = Dont.Do1;
                config.OverrideOauth   = Dont.Do2;
            }
            config.Channel = config.Channel.ToLower();
            return(config);
        }
Example #17
0
 public override void Run()
 {
     try
     {
         ControlInput.IsOpenLoop = true;
         Settings settings = Settings.GetInstance();
         settings.GetDefaultSettings();
         logger.Info($"Ligral (R) Simulation Engine version {Program.Version}.\nCopyright (C) Ligral Tech. All rights reserved.");
         PluginLoader pluginLoader = new PluginLoader();
         pluginLoader.Load();
         if (IsJsonFile is bool isJsonFile && isJsonFile)
         {
             JsonLoader jsonLoader = new JsonLoader();
             jsonLoader.Load(FileName);
         }
         else
         {
             Interpreter interpreter = Interpreter.GetInstance(FileName);
             interpreter.Interpret();
         }
         Inspector    inspector   = new Inspector();
         List <Model> routine     = inspector.Inspect(ModelManager.ModelPool);
         string       problemName = Path.GetFileNameWithoutExtension(FileName);
         Problem      problem     = new Problem(problemName, routine);
         Trimmer      trimmer     = new Trimmer();
         if (settings.TrimmerConfiguration != null)
         {
             trimmer.Configure(settings.TrimmerConfiguration);
         }
         else
         {
             logger.Warn("No trimming configuration is set. The model will be trimmed at zero.");
         }
         settings.ApplySetting();
         trimmer.GetCondition();
         trimmer.Trim(problem);
         if (OutputFile is string outputFile)
         {
             try
             {
                 File.WriteAllText(outputFile, trimmer.ToString());
             }
             catch (Exception e)
             {
                 logger.Prompt(trimmer.ToString());
                 throw logger.Error(new LigralException($"Cannot write to {outputFile}, got error: {e.Message}"));
             }
         }
         else
         {
             logger.Prompt(trimmer.ToString());
         }
     }
Example #18
0
        public static List <SpecialtyDTO> GetSpecialties()
        {
            const string url    = "http://public-crest.eveonline.com/industry/specialities/";
            var          json   = JsonLoader.Load(url);
            var          result = JsonConvert.DeserializeObject <RootObject>(json);

            return(result.items.Select(f => new SpecialtyDTO
            {
                SpecialtyId = f.id,
                Name = f.name,
                GroupIds = f.groups.Select(g => g.id).ToList()
            }).ToList());
        }
Example #19
0
        public PolygonRenderer Load(string polygonName)
        {
            var rawPolygon = _jsonLoader.Load <RawPolygon>(polygonName);

            return(new PolygonRenderer()
            {
                Vertices = rawPolygon
                           .Vertices
                           .Select(x => new Vector2(x[0], x[1]))
                           .ToArray(),
                Loop = rawPolygon.Loop
            });
        }
Example #20
0
        public static Dictionary <string, GameEvent> loadGameEvents(string path)
        {
            Dictionary <string, GameEvent> eventDict = new Dictionary <string, GameEvent>();

            var files = Utility.RetrieveFilePathForFilesInDirectory(path, "*.json");

            foreach (var file in files)
            {
                var evt = JsonLoader.Load <GameEvent>(file, false);
                eventDict.Add(Path.GetFileNameWithoutExtension(file), evt);
            }

            return(eventDict);
        }
Example #21
0
	    public async void Initialize()
	    {
	        if (File.Exists(Path.Combine(m_dataDirectory, "SaveDirectory.json")))
	        {
	            var loader = new JsonLoader(m_dataDirectory);
                m_directory = await loader.Load<SaveDirectory>("SaveDirectory", "SaveDirectory");
	        }
	        else
	        {
                m_directory = new SaveDirectory();
                m_jsonWriter.Write("SaveDirectory", m_directory);
	        }
	        IsInitialized = true;
	    }
Example #22
0
        public void Loading_WithResponseData_ReturnsPopulatedDictionary()
        {
            var rawResponseData = "{ \"some-Property\": \"Some Value\" }";

            var loader = new JsonLoader();

            var result = loader.Load(rawResponseData);

            var expectedDictionary = new Dictionary <string, object>
            {
                { "some-Property", "Some Value" }
            };

            Assert.Equal(expected: expectedDictionary, actual: result);
        }
Example #23
0
        public List <TeamDTO> GetAuctions()
        {
            const string url    = "http://public-crest.eveonline.com/industry/teams/auction/";
            var          json   = JsonLoader.Load(url);
            var          result = JsonConvert.DeserializeObject <AuctionRoot>(json);

            return(result.items.Select(f => new TeamDTO
            {
                TeamId = f.id,
                SolarSystemId = f.solarSystem.id,
                StartDate = DateTime.Parse(f.creationTime).AddDays(7),
                TeamDescription = f.name,
                Bonuses = GetBonuses(f.workers).ToList()
            }).ToList());
        }
Example #24
0
        private void SpawnUfo(Vector2 position)
        {
            PolygonRenderer polygon = _polygonLoader.Load($"polygons/ufo");

            _world
            .CreateEntity()
            .Attach(new Transform
            {
                Position = position
            })
            .Attach(new Rigidbody())
            .Attach(polygon)
            .Attach(new Collider(new Polygon2(polygon.Vertices)))
            .Attach(new SpriteRenderer())
            .Attach(new Ufo())
            .Attach(_jsonLoader.Load <Animation>("animations/ufo"));
        }
Example #25
0
        public bool CreateHead(string headName, bool isAvatar)
        {
            try
            {
                var       newHeadImage = Library.GetTexture((isAvatar ? "twitchAvatar//" : "twitch//") + headName);
                var       animDataPath = string.Format("{0}{1}.json", Indigo.Content.TwitchEmoteProvider.TWITCH_CACHE_PATH, headName);
                Spritemap tempSp       = null;
                if (!File.Exists(animDataPath))
                {
                    Head = new Image(newHeadImage);
                }
                else
                {
                    var animationData = JsonLoader.Load <FramePacker.PackedSpriteMapMeta>(animDataPath, false);
                    var headSpriteMap = new Spritemap(newHeadImage, animationData.FrameWidth, animationData.FrameHeight);
                    headSpriteMap.Add("Default", FP.MakeFrames(0, animationData.TotalFrames - 1), 24, true);
                    headSpriteMap.Play("Default");                    //animationData.FPS
                    Head   = headSpriteMap;
                    tempSp = headSpriteMap;
                }
                AddComponent(Head);

                Head.CenterOrigin();
                Head.Scale = AnimatedEntityData.Animations[Sprite.CurrentAnim].HeadWidth / (float)Head.Width;

                Head.X = AnimatedEntityData.Animations[Sprite.CurrentAnim].HeadPositionX;
                Head.Y = AnimatedEntityData.Animations[Sprite.CurrentAnim].HeadPositionY;

                currentHeadTween = Tweener.Tween(Head, new { Y = AnimatedEntityData.Animations[Sprite.CurrentAnim].HeadPositionY - 4 }, .7f);
                currentHeadTween.Ease(Ease.ToAndFro);
                currentHeadTween.Repeat();

                currentHeadName = headName;
                return(true);
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine("Cannot Find: " + headName);
                Console.WriteLine(ex);
#endif
                //throw (ex);
                return(false);
            }
        }
    void LoadAnimals()
    {
        foreach (Transform item in Content)
        {
            Destroy(item.gameObject);
        }

        if (Application.internetReachability != NetworkReachability.NotReachable)
        {
            NotInternetWindow.SetActive(false);
            LoaderBar.SetActive(true);
            StartCoroutine(JsonLoader.Load(List => {
                AddAnimals(List);
            }));
        }
        else
        {
            NotInternetWindow.SetActive(true);
        }
    }
Example #27
0
 public override void Run()
 {
     try
     {
         Settings settings = Settings.GetInstance();
         settings.GetDefaultSettings();
         logger.Info($"Ligral (R) Simulation Engine version {Program.Version}.\nCopyright (C) Ligral Tech. All rights reserved.");
         PluginLoader pluginLoader = new PluginLoader();
         pluginLoader.Load();
         if (IsJsonFile is bool isJsonFile && isJsonFile)
         {
             JsonLoader jsonLoader = new JsonLoader();
             jsonLoader.Load(FileName);
         }
         else
         {
             Interpreter interpreter = Interpreter.GetInstance(FileName);
             interpreter.Interpret();
         }
         if (OutputFolder is string outputFolder)
         {
             settings.OutputFolder = outputFolder;
         }
         if (StepSize is double stepSize)
         {
             settings.StepSize = stepSize;
         }
         if (StopTime is double stopTime)
         {
             settings.StopTime = (double)stopTime;
         }
         settings.ApplySetting();
         Inspector    inspector   = new Inspector();
         List <Model> routine     = inspector.Inspect(ModelManager.ModelPool);
         string       problemName = Path.GetFileNameWithoutExtension(FileName);
         Problem      problem     = new Problem(problemName, routine);
         Solver       solver      = Solver.GetSolver(settings.SolverName.ToLower());
         solver.Solve(problem);
     }
Example #28
0
        public AppSettings GetSettings()
        {
            string settingsPath = this.filePathProvider.SettingsLocation;

            var loader = new JsonLoader <AppSettings>();

            AppSettings settings;

            if (File.Exists(settingsPath))
            {
                settings = loader.Load(settingsPath);
            }
            else
            {
                settings = new AppSettings
                {
                    InstallLocation = this.filePathProvider.SoulstormLocation
                };
                loader.Write(settingsPath, settings);
            }

            return(settings);
        }
Example #29
0
        protected override void Handle(Explosion message)
        {
            _world.Send(new PlaySound("sfx/explosions/3"));

            var animation = _jsonLoader.Load <Animation>("animations/explosion");

            _world
            .CreateEntity()
            .Attach(new Transform
            {
                Position = message.Position,
                Scale    = message.Size / 4f
            })
            .Attach(new Lifetime(animation.Duration))
            .Attach(new SpriteRenderer())
            .Attach(animation);

            for (var i = 0; i < 3 * message.Size; i++)
            {
                _world
                .CreateEntity()
                .Attach(new Transform()
                {
                    Position = message.Position
                })
                .Attach(new PolygonRenderer
                {
                    Vertices = new[] { Vector2.Zero, Vector2.UnitX }
                })
                .Attach(new Rigidbody
                {
                    Velocity = Vector2.UnitX.Rotate((float)_world.Random.NextDouble() * MathF.PI * 2) *
                               ParticlesSpeed
                })
                .Attach(new Lifetime(1f));
            }
        }
Example #30
0
 public static CustomData GetDefault()
 {
     return(JsonLoader <CustomData> .Load(_JsonName));
 }
Example #31
0
        private void _btnProgramLoad_Click(object sender, EventArgs e)
        {
            List <HackingTarget>   items            = JsonLoader.Load(@"C:\Alternative\Source\doc.json");
            DomainController       domainController = new DomainController();
            DomainIgnoreController ignoreController = new DomainIgnoreController();

            foreach (HackingTarget item in items)
            {
                foreach (Target target in item.Targets.in_scope)
                {
                    string platform = "";
                    if (item.URL.Contains("hackerone"))
                    {
                        if (!target.asset_type.Equals("URL"))
                        {
                            continue;
                        }
                        platform = "hackerone";
                    }

                    if (item.URL.Contains("bugcrowd"))
                    {
                        //if (!target.type.Equals("website"))
                        if (!target.target.Contains("http"))
                        {
                            continue;
                        }
                        platform = "bugcrowd";
                    }

                    string domaintext = target.asset_identifier;
                    if (String.IsNullOrEmpty(domaintext))
                    {
                        domaintext = target.target;
                    }

                    domaintext = domaintext.Replace("*.", "").Replace("https://", "").Replace("http://", "").Replace("(", "").Replace(")", "").Split('?')[0].Split('/')[0];

                    string regex = "(\\[.*\\])|(\".*\")|('.*')|(\\(.*\\))|(<.*>)";
                    domaintext = Regex.Replace(domaintext, regex, "");

                    string[] parts = domaintext.Split('.');

                    if (parts.Length >= 2)
                    {
                        int count = parts.Length - 1;
                        domaintext = parts[count - 1] + "." + parts[count];
                    }

                    Clark.Domain.Data.Domain domain = domainController.FindByDomain(domaintext);
                    if (domain == null)
                    {
                        domain = new Domain();

                        domain.Platform      = platform;
                        domain.BountyURL     = item.URL;
                        domain.BountyEndDate = new DateTime(2999, 12, 31);
                        domain.Private       = false;
                        domain.DomainName    = domaintext;

                        UpdateResult res = domainController.Insert(domain);
                        if (res.Error)
                        {
                            MessageBox.Show(target.asset_identifier + " error");
                        }
                    }
                }

                foreach (Target target in item.Targets.out_of_scope)
                {
                    if (!target.asset_type.Equals("URL"))
                    {
                        continue;
                    }

                    DomainIgnore ignore = ignoreController.FindByIgnoreDomain(target.asset_identifier.Replace("*.", ""));
                    if (ignore == null)
                    {
                        ignore = new DomainIgnore();

                        string domain2Ignore = target.asset_identifier;
                        domain2Ignore = domain2Ignore.Replace("*.", "").Replace("https://", "").Replace("http://", "").Replace("(", "").Replace(")", "").Split('?')[0].Split('/')[0];

                        string regex = "(\\[.*\\])|(\".*\")|('.*')|(\\(.*\\))|(<.*>)";
                        domain2Ignore = Regex.Replace(domain2Ignore, regex, "");

                        ignore.DomainToIgnore = domain2Ignore;



                        UpdateResult res = ignoreController.Insert(ignore);
                        if (res.Error)
                        {
                            MessageBox.Show(target.asset_identifier + " error");
                        }
                    }
                }
            }
        }
Example #32
0
        public void EmptyFileThrowsJsonReaderException()
        {
            var testSubject = new JsonLoader();

             Assert.That(() => testSubject.Load(@"TestData\EmptyJsonFile.json"), Throws.InstanceOf<JsonReaderException>());
        }
Example #33
0
        public void MissingFileThrowsFileNotFoundException()
        {
            var testSubject = new JsonLoader();

             Assert.That(() => testSubject.Load("ThisDoesNotExist.json"), Throws.InstanceOf<FileNotFoundException>());
        }