Example #1
0
        private JsonModel GetGridResult(CancellationToken ct)
        {
            JsonModel jsonModel;

            try
            {
                if (ct.IsCancellationRequested)
                {
                    return(null);
                }
                MySettings mySettings = Session["mySettings"] as MySettings;
                //                mySettings.Filter.Taxa.TaxonIds = new ObservableCollection<int>() { 5, 7, 8, 11, 14, 16 };
                //mySettings.Filter.Taxa.TaxonIds = new ObservableCollection<int>() { 5, 7, 8, 11, 14, 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };

                mySettings.Filter.Taxa.IsActive = true;
                IUserContext userContext = CoreData.UserManager.GetCurrentUser();
                IList <IGridCellSpeciesObservationCount> res   = GetSpeciesObservationGridCellResultFromWebService(userContext, mySettings);
                SpeciesObservationGridResult             model = SpeciesObservationGridResult.Create(res);
                //SpeciesObservationGridResult model = resultsManager.GetSpeciesObservationGridCellResult();
                jsonModel = JsonModel.CreateFromObject(model);
            }
            catch (Exception ex)
            {
                jsonModel = JsonModel.CreateFailure(ex.Message);
            }
            return(jsonModel);
        }
        private async Task attachUserToContext(HttpContext context, IUserRepository userService, string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var secretKey    = MySettings.GetSecretKey();
                var key          = Encoding.ASCII.GetBytes(secretKey);
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                var userId   = Guid.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);

                // attach user to context on successful jwt validation
                Result result = await userService.GetUserById(userId);

                var  data = result.Data != null ? (List <User>)result.Data : null;
                User user = data.Count > 0 ? data[0] : null;
                context.Items["User"] = user;
            }
            catch
            {
                // do nothing if jwt validation fails
                // user is not attached to context so request won't have access to secure routes
            }
        }
        public void Test_PresentationTableSettings()
        {
            MySettings mySettings = new MySettings();

            mySettings.ResultCacheNeedsRefresh = false;
            MySettings oldMySettings = ObjectCopier.Clone(mySettings);

            // presentation settings doesn't trigger cache refresh
            mySettings.Presentation.Table.IsActive = true;
            Assert.IsFalse(mySettings.ResultCacheNeedsRefresh);
            mySettings.Presentation.Table.SpeciesObservationTable.SelectedTableId = 1;
            Assert.IsFalse(mySettings.ResultCacheNeedsRefresh);

            mySettings.Presentation.Table.IsActive = false;
            mySettings.Presentation.Table.SpeciesObservationTable.SelectedTableId = 0;



            using (ShimsContext.Create())
            {
                base.LoginTestUserAnalyser();
                IUserContext userContext = SessionHandler.UserContext;

                List <ISpeciesObservationFieldDescription> tableFields = mySettings.Presentation.Table.SpeciesObservationTable.GetTableFields(userContext);
                Assert.IsTrue(tableFields.Count > 0);

                tableFields = mySettings.Presentation.Table.SpeciesObservationTable.GetTableFields(userContext, 1, false);
                Assert.IsTrue(tableFields.Count > 0);

                tableFields = mySettings.Presentation.Table.SpeciesObservationTable.GetTableFields(userContext, 0, true);
                Assert.IsTrue(tableFields.Count > 0);
            }
        }
Example #4
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                MySettings.DefaultSettings();

                _timer.Interval  = MySettings.SampleRate * 1000;
                _timer.Elapsed  += TimerMethod;
                _timer.AutoReset = false;
                _timer.Start();

                var json  = GetJsonData.GetJson(MySettings.nodepoolsurl, MySettings.token);
                var Pools = json["data"].ToObject <List <Rancher.NodePool> >();
                nodePools = Pools.Where(np => np.worker).ToList();
                if (nodePools.Count == 0)
                {
                    Console.WriteLine("Node pools empty!");
                    return(StopAsync(cancellationToken));
                }

                Console.WriteLine($"[{nameof(NodeAutoScaler)}] has been started.....");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(Task.CompletedTask);
        }
Example #5
0
        /// <summary>
        /// Method that will be called everytime there is a network failure.
        /// </summary>
        internal override void SpecificRestart(IModel model)
        {
            Props = model.CreateBasicProperties();
            MySettings.ConstructProperties(Props);

            if (MySettings.UseConfirms)
            {
                model.ConfirmSelect();
                //requeue all messages that were on the wire. This might lead to duplicates.
                if (MySettings.RequeueMessageAfterFailure && _unacked != null)
                {
                    var unacked = new List <Message>(_unacked.Count);
                    foreach (var m in _unacked.Values)
                    {
                        unacked.Add(new Message
                        {
                            Failed     = m.Failed + 1,
                            RoutingKey = m.RoutingKey,
                            Payload    = m.Payload
                        });
                    }
                    OnNAckHandler(unacked);
                }
                _unacked          = new ConcurrentDictionary <ulong, Message>();
                model.BasicAcks  += (_, args) => HandleAcknowledgement(false, args.DeliveryTag, args.Multiple);
                model.BasicNacks += (_, args) => HandleAcknowledgement(true, args.DeliveryTag, args.Multiple);
            }
        }
        public void Add_Regions()
        {
            MySettings mySettings = new MySettings();

            mySettings.Filter.Spatial.RegionIds.Add(1);
            mySettings.Filter.Spatial.RegionIds.Add(25);
            mySettings.Filter.Spatial.RegionIds.Add(32);
            mySettings.ResultCacheNeedsRefresh = false;
            MySettings oldMySettings = ObjectCopier.Clone(mySettings);

            // No changes is made => cache is up to date
            Assert.IsFalse(mySettings.ResultCacheNeedsRefresh);

            mySettings.Filter.Spatial.RegionIds.RemoveAt(1);
            // One polygon is removed => cache needs refresh
            Assert.IsTrue(mySettings.ResultCacheNeedsRefresh);

            mySettings.Filter.Spatial.RegionIds.Add(25);
            // The removed region is added again => no changes is made => cache is up to date

            mySettings.ResultCacheNeedsRefresh = false;
            Assert.IsFalse(mySettings.Filter.Spatial.IsActive); // is active as default
            Assert.IsFalse(oldMySettings.Filter.Spatial.IsActive);
            mySettings.Filter.Spatial.IsActive = true;
            // changing IsActive => cache needs refresh.
            Assert.IsTrue(mySettings.ResultCacheNeedsRefresh);
        }
 private void SettingsForm_Load(object sender, System.EventArgs e)
 {
     if(settings==null)
         settings = MySettings.Load();
     MinimizedStartCheckbox.Checked=settings.minimizedStart;
     AutostartCheckBox.Checked = settings.runOnWinStart;
 }
Example #8
0
    public void Configure(IApplicationBuilder app)
    {
        var builder = new ConfigurationBuilder();

        builder.Add(new MemoryConfigurationProvider {
            { "MySettings:RetryCount", "42" },
            { "MySettings:DefaultAdBlock", "House" },
            { "MySettings:AdBlock:House:ProductCode", "123" },
            { "MySettings:AdBlock:House:Origin", "blob-456" },
            { "MySettings:AdBlock:Contoso:ProductCode", "contoso2014" },
            { "MySettings:AdBlock:Contoso:Origin", "sql-789" },
        });
        var config = builder.Build();

        var mySettings = new MySettings();

        mySettings.Read(config.GetSection("MySettings"));

        app.Run(async ctx =>
        {
            ctx.Response.ContentType = "text/plain";

            await ctx.Response.WriteAsync(string.Format("Retry Count {0}\r\n", mySettings.RetryCount));
            await ctx.Response.WriteAsync(string.Format("Default Ad Block {0}\r\n", mySettings.DefaultAdBlock));
            foreach (var adBlock in mySettings.AdBlocks.Values)
            {
                await ctx.Response.WriteAsync(string.Format(
                                                  "Ad Block {0} Origin {1} Product Code {2}\r\n",
                                                  adBlock.Name, adBlock.Origin, adBlock.ProductCode));
            }
        });
    }
Example #9
0
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void Close()
    {
        var chages = (MySettings.ConfigFile != _configName) || (MySettings.IsStartWithMenu != _startFromMenu) || (MySettings.IsStereo != _isStereo) || (Configuration.ConfigMaganer.Instance.Application.Debug != _isDebug);

        if (chages)
        {
            // TODO: show message "Save changes?"

            if (_configName != MySettings.ConfigFile)
            {
                // load new one
                if (!Configuration.ConfigMaganer.Init(_configName, false))
                {
                    Debug.LogError("Can't load from new config file " + _configName);
                    // TODO: show notification message
                }
            }

            MySettings.IsStartWithMenu = _startFromMenu;
            MySettings.IsStereo        = _isStereo;
            MySettings.ConfigFile      = _configName;
            MySettings.Save();

            if (Configuration.ConfigMaganer.Instance.Application.Debug != _isDebug)
            {
                Configuration.ConfigMaganer.Instance.Application.Debug = _isDebug;
                Configuration.ConfigMaganer.SaveInstance(MySettings.ConfigFile);
            }

            Debug.Log("Configuration was saved");
        }

        this.enabled  = false;
        _menu.enabled = true;
    }
Example #10
0
        // scans bags for offhand weapon if mainhand isn't 2h and none are equipped and uses the highest ilvl one
        private WoWItem FindOffhand()
        {
            WoWItem offHand = _me.Inventory.Equipped.OffHand;

            if (offHand == null)
            {
                offHand = _me.CarriedItems.OrderByDescending(u => u.ItemInfo.Level).
                          FirstOrDefault(i => i.IsSoulbound && (i.ItemInfo.InventoryType == InventoryType.WeaponOffHand ||
                                                                i.ItemInfo.InventoryType == InventoryType.Weapon ||
                                                                i.ItemInfo.InventoryType == InventoryType.Shield) &&
                                         MySettings.MainHand != i.Entry &&
                                         _me.CanEquipItem(i));
                if (offHand != null)
                {
                    MySettings.OffHand = offHand.Entry;
                }
                else
                {
                    Err("Unable to find an offhand weapon to swap to when in combat");
                }
            }
            else
            {
                MySettings.OffHand = offHand.Entry;
            }
            MySettings.Save();
            return(offHand);
        }
Example #11
0
        public void SpeciesObservationSearchCriteriaAPIPost()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                var shimHttpClient = new ShimHttpClient(httpClient);

                // Act
                shimHttpClient.PostAsyncUriHttpContent = (uri, content) =>
                {
                    var responseTask = new TaskCompletionSource <HttpResponseMessage>();
                    var httpResponse = new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.Created,
                        Content    = new ObjectContent(typeof(MySettings), new MySettings(), new JsonMediaTypeFormatter())
                    };

                    responseTask.SetResult(httpResponse);
                    return(responseTask.Task);
                };
                httpResponseMessage = httpClient.PostAsync(SPECIES_OBSERVATION_SEARCH_CRITERIA_API_URI, null).Result;

                // Assert
                Assert.IsNotNull(httpResponseMessage);
                Assert.IsTrue(httpResponseMessage.IsSuccessStatusCode);
                Assert.AreEqual(httpResponseMessage.StatusCode, HttpStatusCode.Created);
                result = javaScriptSerializer.Deserialize <MySettings>(httpResponseMessage.Content.ReadAsStringAsync().Result);
                Assert.IsNotNull(result);
            }
        }
Example #12
0
        private void ConfigureContainer(ContainerBuilder builder)
        {
            builder
            .Register(activator =>
            {
                var mySettings = new MySettings();

                var config = activator.Resolve <IConfiguration>();
                config.GetSection(nameof(MySettings)).Bind(mySettings);

                return(mySettings);
            })
            .AsSelf()
            .SingleInstance();

            builder
            .RegisterAssemblyTypes(typeof(Startup).Assembly)
            .InNamespace("SampleAutofacFunction.Functions")
            .AsSelf()
            .InstancePerTriggerRequest();

            builder
            .RegisterAssemblyTypes(typeof(Startup).Assembly)
            .InNamespace("SampleAutofacFunction.Services")
            .AsImplementedInterfaces()
            .InstancePerTriggerRequest();
        }
Example #13
0
        private WoWItem FindMainHand()
        {
            WoWItem mainHand = _me.Inventory.Equipped.MainHand;

            if (mainHand == null || mainHand.ItemInfo.WeaponClass == WoWItemWeaponClass.FishingPole)
            {
                mainHand = _me.CarriedItems.OrderByDescending(u => u.ItemInfo.Level).
                           FirstOrDefault(i => i.IsSoulbound && (i.ItemInfo.InventoryType == InventoryType.WeaponMainHand ||
                                                                 i.ItemInfo.InventoryType == InventoryType.TwoHandWeapon) &&
                                          _me.CanEquipItem(i));
                if (mainHand != null)
                {
                    MySettings.MainHand = mainHand.Entry;
                }
                else
                {
                    Err("Unable to find a mainhand weapon to swap to when in combat");
                }
            }
            else
            {
                MySettings.MainHand = mainHand.Entry;
            }
            MySettings.Save();
            return(mainHand);
        }
        public void PresentationSummaryStatisticsTest()
        {
            MySettings mySettings = new MySettings();

            mySettings.ResultCacheNeedsRefresh = false;

            //Check that is active and has settings by default.
            Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.IsActive);
            Assert.IsFalse(mySettings.ResultCacheNeedsRefresh);
            // IS set to false by default since ther is no settings for the moment to set
            //Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.HasSettings);
            Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.SelectedReportId == 0);

            // Deactivate summary statistics settings
            mySettings.Presentation.Report.SummaryStatisticsReportSetting.IsActive = false;
            Assert.IsFalse(mySettings.Presentation.Report.SummaryStatisticsReportSetting.IsActive);
            //Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.HasSettings);
            // Set summary statistics active again
            mySettings.Presentation.Report.SummaryStatisticsReportSetting.IsActive = true;
            Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.IsActive);
            //Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.HasSettings);

            // Check that CalculateNumberOfObservationsfromObsData is updated correct
            Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.SelectedReportId == 0);
            // Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.HasSettings);

            mySettings.Presentation.Report.SummaryStatisticsReportSetting.SelectedReportId = 1;
            //Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.HasSettings);
            Assert.IsTrue(mySettings.Presentation.Report.SummaryStatisticsReportSetting.SelectedReportId == 1);
        }
        /// <summary>
        /// Loads the savefile of the plugin settings of the world and stores it
        /// int the Settings member variable
        /// </summary>
        public override void LoadData()
        {
            Static = this;
            if (FileUtils.FileExistsInWorldStorage(FILE_NAME, typeof(SettingsSession)))
            {
                Settings = FileUtils.ReadXmlFileFromWorld <MyObjectBuilder_PluginSettings>(FILE_NAME, typeof(SettingsSession));
            }
            else
            {
                if (MySettings.Static == null)
                {
                    var s = new MySettings();
                    s.LoadSettings();
                }
                if (MySettings.Static.SessionSettings != null)
                {
                    Settings = MySettings.Static.SessionSettings;
                }
                else
                {
                    Settings = MySettings.Static.Settings;
                }

                MySettings.Static.SessionSettings = null;
            }
        }
Example #16
0
    public void Configure(IApplicationBuilder app)
    {
        var builder = new ConfigurationBuilder();
        builder.Add(new MemoryConfigurationProvider {
                {"MySettings:RetryCount", "42"},
                {"MySettings:DefaultAdBlock", "House"},
                {"MySettings:AdBlock:House:ProductCode", "123"},
                {"MySettings:AdBlock:House:Origin", "blob-456"},
                {"MySettings:AdBlock:Contoso:ProductCode", "contoso2014"},
                {"MySettings:AdBlock:Contoso:Origin", "sql-789"},
            });
        var config = builder.Build();

        var mySettings = new MySettings();
        mySettings.Read(config.GetSection("MySettings"));

        app.Run(async ctx =>
        {
            ctx.Response.ContentType = "text/plain";

            await ctx.Response.WriteAsync(string.Format("Retry Count {0}\r\n", mySettings.RetryCount));
            await ctx.Response.WriteAsync(string.Format("Default Ad Block {0}\r\n", mySettings.DefaultAdBlock));
            foreach (var adBlock in mySettings.AdBlocks.Values)
            {
                await ctx.Response.WriteAsync(string.Format(
                    "Ad Block {0} Origin {1} Product Code {2}\r\n", 
                    adBlock.Name, adBlock.Origin, adBlock.ProductCode));                
            }
        });
    }
Example #17
0
 public void SalirDeEspera(Alfombra alfombra, DateTime reloj)
 {
     Estado = EstadoArea.Ocupado;
     FechaProximoFinAtencion = reloj.AddHours(MySettings.TiempoPonerAlfombras / 60).AddMilliseconds(37);
     TiempoDeAtencion        = MySettings.RoundTimeSpan(0, FechaProximoFinAtencion - reloj);
     AutoActual._Alfombra    = alfombra;
 }
Example #18
0
 private void Button_Clicked(object sender, System.EventArgs e)
 {
     MySettings.Clear();
     //new NavigationPage(new LoginPage());
     //Navigation.PushModalAsync(new LoginPage());
     Navigation.PopToRootAsync();
 }
        public void GridStatistics()
        {
            MySettings mySettings = new MySettings();

            mySettings.ResultCacheNeedsRefresh = false;
            MySettings oldMySettings = ObjectCopier.Clone(mySettings);

            // Is true by default
            Assert.IsTrue(mySettings.Calculation.GridStatistics.IsActive);
            mySettings.Calculation.GridStatistics.IsActive = true;
            Assert.IsTrue(mySettings.ResultCacheNeedsRefresh);
            mySettings.Calculation.GridStatistics.IsActive = false;

            mySettings.ResultCacheNeedsRefresh = false;
            mySettings.Calculation.GridStatistics.CoordinateSystemId = 2;
            Assert.IsTrue(mySettings.ResultCacheNeedsRefresh);
            mySettings.Calculation.GridStatistics.CoordinateSystemId = null;

            mySettings.ResultCacheNeedsRefresh             = false;
            mySettings.Calculation.GridStatistics.GridSize = 200;
            Assert.IsTrue(mySettings.ResultCacheNeedsRefresh);
            mySettings.Calculation.GridStatistics.GridSize = null;

            mySettings.ResultCacheNeedsRefresh = false;
            Assert.IsTrue(mySettings.Calculation.GridStatistics.CalculateNumberOfObservations);
            mySettings.Calculation.GridStatistics.CalculateNumberOfObservations = false;
            Assert.IsTrue(mySettings.ResultCacheNeedsRefresh);
            mySettings.Calculation.GridStatistics.CalculateNumberOfObservations = true;
        }
        /// <summary>
        /// Loads the savefile of the plugin settings of the world and stores it
        /// int the Settings member variable
        /// </summary>
        public override void LoadData()
        {
            MyPluginLog.Log("Loading Session settings data");
            Static = this;
            if (MyFileUtils.FileExistsInWorldStorage(FILE_NAME))
            {
                Settings = MyFileUtils.ReadXmlFileFromWorld <MyObjectBuilder_WorldSettings>(FILE_NAME);

                MyPluginLog.Log("Session settings read from file");
            }
            else
            {
                MyPluginLog.Log("Session settings do not exist, creating new ones.");
                if (MySettings.Static == null)
                {
                    var s = new MySettings();
                    s.LoadSettings();
                }
                if (MySettings.Static.SessionSettings != null)
                {
                    Settings = MySettings.Static.SessionSettings;
                }
                else
                {
                    Settings = new MyObjectBuilder_WorldSettings();
                }

                MySettings.Static.SessionSettings = null;
            }

            MyPluginLog.Log("Loading Session settings data completed");
        }
Example #21
0
 public Function2(IService1 service1, MySettings settings, ILogger logger)
 {
     _service1 = service1;
     _settings = settings;
     _logger   = logger;
     _logger.LogWarning($"Creating {this}");
 }
Example #22
0
        public void CalcularProximaLlegada(DateTime reloj)
        {
            double minutos = MySettings.Distribuciones.Exponencial.Calcular(MySettings.MediaLlegadas);

            FechaProximaLlegada = reloj.AddMinutes(minutos).AddMilliseconds(7);
            TiempoEntreLlegadas = MySettings.RoundTimeSpan(0, FechaProximaLlegada - reloj);
        }
Example #23
0
        private void SetIndexViewData()
        {
            RecipeRepository repo = new RecipeRepository(ConnectionString);

            WeekPlan activeWeekPlan = new WeekPlan();

            List <WeekPlan> weekPlans = repo.GetWeekPlans(User.Id);

            int weekPlanId = 0;

            foreach (WeekPlan weekPlan in weekPlans)
            {
                if (weekPlan.Active)
                {
                    foreach (WeekItem item in weekPlan.WeekItems)
                    {
                        Recipe recipe = repo.GetRecipe(item.RecipeId);

                        item.Recipe = recipe;

                        weekPlanId = weekPlan.Id;
                    }
                    activeWeekPlan = weekPlan;
                }
            }

            List <MySettings> settings = GetMySettings();

            //antar dagar i veckoplanen
            MySettings firstDay = settings.First(x => x.Key == "FirstDay");
            MySettings days     = settings.First(x => x.Key == "DayCount");

            string[] t = new string[] { "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag" };
            string[] m = new string[Int32.Parse(days.Value)];

            int counter = GetDayInt(firstDay.Value);

            for (int i = 1; i <= Int32.Parse(days.Value); i++)
            {
                if (counter == 8)
                {
                    counter = 1;
                }
                m[(i - 1)] = t[counter - 1];

                counter++;
            }
            ViewBag.WeekDays = m;
            //ViewBag.WeekDays = new string[] { "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag" };

            //Add empty
            activeWeekPlan.WeekItems.Insert(0, new WeekItem {
                Id = 0, Recipe = new Recipe {
                    Name = "-", Id = 0
                }, RecipeId = 0
            });

            ViewBag.WeekPlan = activeWeekPlan;
        }
 public Function2(IService1 service1, MySettings settings, ILogger logger, TelemetryClient client)
 {
     _service1 = service1;
     _settings = settings;
     _logger   = logger;
     _client   = client;
     _logger.LogWarning($"Creating {this}");
 }
Example #25
0
 // (0.0.5)
 private void Application_Startup(object sender, StartupEventArgs e)
 {
     if (MySettings.RequireUpgrade)
     {
         MySettings.Upgrade();
         MySettings.RequireUpgrade = false;
     }
 }
Example #26
0
 public SettingsViewModel(MySettings mySettings)
 {
     Rows = new ObservableCollection <OneSetting>();
     foreach (var oneSetting in mySettings)
     {
         Rows.Add(oneSetting);
     }
 }
Example #27
0
 static void Main()
 {
     Settings = MySettings.Load();
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new MainForm());
     Environment.Exit(0);
 }
Example #28
0
 /// <summary>
 /// Конструктор, принимает объект иконки трея
 /// </summary>
 /// <param name="tb"></param>
 public HeadViewModel(TaskbarIcon tb)
 {
     try
     {
         dispatcher    = Dispatcher.CurrentDispatcher;
         thread_object = new Object();
         //инициализируем объект иконки и объект класса всплывающих сообщений
         this.Tb = tb;
         mb      = new MyBalloon(tb.GetPopupTrayPosition().X, tb.GetPopupTrayPosition().Y);
         mb.baloon_panel.ItemsSource = FormatText.baloon_msg;
         mb.Show();
         //инициализируем переменную для хранения настроек окна
         CheckBoxSettings = new MySettings();
         //инициализируем сериализатор
         formatter = new XmlSerializer(typeof(MySettings));
         //загружаем данные из xml при открытии приложения
         Deserializable();
         //выгружаем из бд список аккаунтов
         dbAccounts = new AccountContext();
         dbAccounts.Accounts.Load();
         Accounts = dbAccounts.Accounts.Local.ToBindingList();
         //выгружаем из бд офсеты
         dbOffsets = new OffsetContext();
         dbOffsets.Offsets.Load();
         offsetsFromDb = dbOffsets.Offsets.FirstOrDefault((p) => p.Version == "1.5.5_2591");
         if (offsetsFromDb != null)
         {
             OpenOffsets();
         }
         //выгружаем настройки из бд, в будующем планируется выполнять этот шаг через вебсервис
         dbSettings = new SettingContext();
         dbSettings.Settings.Load();
         //генерируем уникльный ключ компьютера
         String serial = CalcMethods.GenerateSerialNumber();
         //проверяем, есть ли в бд настройки, привязанные к этому ключу
         settings = dbSettings.Settings.FirstOrDefault((p) => p.Serialnumber == serial);
         //если настройки отсутствуют, то создаем новые и заносим в бд
         if (settings == null)
         {
             settings = new Models.Login.Setting
             {
                 Downloader   = "Downloader/12650 MailRuGameCenter/1265",
                 Serialnumber = CalcMethods.GenerateSerialNumber(),
                 UserId_1     = CalcMethods.RandomStringValue(20),
                 UserId_2     = CalcMethods.RandomStringValue(20),
                 Filepath     = String.Empty
             };
             dbSettings.Settings.Add(settings);
             dbSettings.SaveChanges();
         }
         ApplySettings();
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
        public static void SetBalanceForUser(string uid, int value)
        {
            MySettings settings = Instance.Settings;

            CheckUserHasData(uid);
            value = Math.Max(0, Math.Min(settings.EcoHardBalanceLimit, value));
            settings.UserBalances[uid] = value;
            settings.DelayedSave();
        }
Example #30
0
    static void Main(string[] args)
    {
        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(MySettings));

        using (var stream = System.IO.File.OpenRead("config file path")){
            Program.ProgramSettings = (MySettings)serializer.Deserialize(stream);
        }
        SomeMethod();
    }
Example #31
0
        public void PropertyValuesUninitialized()
        {
            MySettings s = new MySettings();

            s.Initialize(new SettingsContext(), new SettingsPropertyCollection(), new SettingsProviderCollection());
            s.Properties.Add(new SettingsProperty("Foo"));
            // values are filled only at initialization phase.
            Assert.AreEqual(0, s.PropertyValues.Count, "#1");
        }
 public void CanReadAStringValue()
 {
     var settingsSource = new NameValueCollection();
     settingsSource["My:Name"] = "Mike";
     var reader = new SimpleSettingsReader(settingsSource);
     var injector = new SimpleSettingsInjector();
     var settings = new MySettings();
     injector.Inject(settings, reader);
     Assert.AreEqual("Mike", settings.Name);
 }
        private static void CheckUserHasData(string uid)
        {
            MySettings settings = Instance.Settings;

            if (!settings.UserBalances.ContainsKey(uid))
            {
                settings.UserBalances.Add(uid, 0);
                settings.DelayedSave();
            }
        }
        public FacebookUserInformation(FacebookClient facebookClient, MySettings mySettings)
        {
            Guard.MakeSureAllInstancesIsNullNot(mySettings);

            _facebookClient = facebookClient;
            _mySettings = mySettings;
            _facebookClient = facebookClient;
            _facebookClient.ClientIdentifier = _mySettings.FacebookAppId;
            _facebookClient.ClientSecret = _mySettings.FacebookAppSecret;
        }
Example #35
0
		public void PropertyDefaults ()
		{
			MySettings s = new MySettings ();
			Assert.IsNull (s.Properties, "#1");
			Assert.IsNull (s.Providers, "#2");
			Assert.IsNull (s.Context, "#3");
			Assert.AreEqual (0, s.PropertyValues.Count, "#4");
			Assert.IsNull (s.Properties, "#5");
			Assert.IsNull (s.Providers, "#6");
			Assert.IsNull (s.Context, "#7");
			s.Initialize (s.Context, s.Properties, s.Providers);
		}
           public void CanReadManySettingsFromASingleSource()
           {
               var settingsSource = new NameValueCollection();
               settingsSource["Smtp:Server"] = "test-server";
               settingsSource["My:Name"] = "Mike";
               var reader = new SimpleSettingsReader(settingsSource);
               var injector = new SimpleSettingsInjector();
               var smtpSettings = new SmtpSettings();
               var mySettings = new MySettings();

               injector.Inject(smtpSettings, reader);
               injector.Inject(mySettings, reader);

               Assert.AreEqual("test-server", smtpSettings.Server);
               Assert.AreEqual("Mike", mySettings.Name);
           }
 public void FailsIfSettingsHaveNoCorrespondingProperty()
 {
     SimpleSettingsReader reader = null;
     SimpleSettingsInjector injector = null; 
     try
     {
         var settingsSource = new NameValueCollection();
         settingsSource["My:Name"] = "Mike";
         settingsSource["My:Blog"] = "http://codermike.com";
         reader = new SimpleSettingsReader(settingsSource);
         injector = new SimpleSettingsInjector();
     }
     catch (Exception ex)
     {
         Assert.Inconclusive("Unexpected Exception occurred: {0}", ex);
     }
     var settings = new MySettings();
     injector.Inject(settings, reader);
     Assert.Fail("Should have thrown");
 }
Example #38
0
        static void Main(string[] args)
        {
            using(MySettings settings = new MySettings())
            {
                string myValue = settings.GetSetting<string>("MySettingName1", "MySettingValueDefault1");

                settings.PutSetting("MySettingName2", "MySettingValue2");
                settings.PutSetting(MySettings.SomeSettingName, MySettings.SomeSettingDefaultValue);

                string myValue2 = settings.GetSetting<string>("MySettingName2", "MySettingValueDefault2");
                double myValueDouble2 = settings.GetSetting(MySettings.SomeSettingName, MySettings.SomeSettingDefaultValue);

                string secret = "secret password";

                string unencryptedDefault = settings.GetEncryptedSetting(secret, "MyEncryptedSettingName", "MyEncryptedSettingValueDefault");
                settings.PutEncryptedSetting(secret, "MyEncryptedSettingName", "blah blah blah secrets");
                string encryptedText = settings.GetSetting("MyEncryptedSettingName", "MyEncryptedSettingValueDefault");
                string unencryptedText = settings.GetEncryptedSetting(secret, "MyEncryptedSettingName", "MyEncryptedSettingValueDefault");
            }
        }
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            pars = new MySettings();
            settingsContent.DataContext = pars;

            if (pars.FieldSize != null)
            {
                ButtonsGrid.RowDefinitions.Clear();
                ButtonsGrid.ColumnDefinitions.Clear();
                for (int i = 0; i < pars.FieldSize; i++)
                {
                    ButtonsGrid.RowDefinitions.Add(new RowDefinition());
                    ButtonsGrid.ColumnDefinitions.Add(new ColumnDefinition());
                }
            }

            for (int i = 0; i < ButtonsGrid.RowDefinitions.Count; i++)
            {
                for (int j = 0; j < ButtonsGrid.RowDefinitions.Count; j++)
                {
                    Button b = new Button();
                    b.Background = (App.Current.Resources["PhoneAccentBrush"] as SolidColorBrush);
                    b.Foreground = (App.Current.Resources["PhoneBackgroundBrush"] as SolidColorBrush);
                    b.Padding = new Thickness(0);
                    b.FontSize = 35;
                    b.BorderThickness = new Thickness(1);
                    b.Tag = new Point(i + 1, j + 1);
                    b.Margin = new Thickness(-12);
                    b.Click += new RoutedEventHandler(b_Click);
                    b.Content = "";
                    Grid.SetColumn(b, i);
                    Grid.SetRow(b, j);
                    ButtonsGrid.Children.Add(b);
                }
            }

            RecursionLevel = 3;
            if (!pars.HumanFirst.Value)
                MakeMove();
            //LayoutRoot.Background = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Hydrangeas.jpg", UriKind.RelativeOrAbsolute)) };
            //GetButton(new Point(1, 1)).Content = 'o';
            //GetButton(new Point(2, 1)).Content = 'o';
            //GetButton(new Point(5, 1)).Content = 'o';
            //GetButton(new Point(4, 1)).Content = 'o';

            //GetButton(new Point(4, 3)).Content = 'x';
            //GetButton(new Point(5, 4)).Content = 'x';
            //GetButton(new Point(6, 5)).Content = 'x';
            //GetButton(new Point(7, 6)).Content = 'x';
        }
Example #40
0
 private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
 {
     using (OptionsForm form = new OptionsForm())
     {
         form.Settings = settings;
         if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
             settings = form.Settings;
     }
 }
		public void AddPropertyTypeMismatch ()
		{
			SettingsPropertyCollection props = new SettingsPropertyCollection ();
			SettingsProviderCollection provs = new SettingsProviderCollection ();

			MyProvider p = new MyProvider ();
			MySettings s = new MySettings ();

			props.Add (new SettingsProperty ("Foo", typeof (string), p, false, 10, SettingsSerializeAs.String, null, true, true));
			provs.Add (p);

			s.Initialize (new SettingsContext (), props, provs);
			int i = s.Foo; // it still works as int, regardless of the settings property type...
		}
		public void PropertyValuesInitialized ()
		{
			SettingsPropertyCollection props = new SettingsPropertyCollection ();
			SettingsProviderCollection provs = new SettingsProviderCollection ();

			MyProvider p = new MyProvider ();
			MySettings s = new MySettings ();
			int i;

			try {
				i = s.Foo;
				Assert.Fail ("#1-2");
			} catch (SettingsPropertyNotFoundException) {
			}

			s.Initialize (new SettingsContext (), props, provs);
			Assert.AreEqual (0, s.PropertyValues.Count, "#2-1");
			Assert.AreEqual (0, s.Context.Count, "#2-2");

			props.Add (new SettingsProperty ("Foo", typeof (int), p, false, 10, SettingsSerializeAs.String, null, true, true));
			// initialize w/o the provider
			s.Initialize (new SettingsContext (), props, provs);
			Assert.AreEqual (0, s.PropertyValues.Count, "#3-0");
			Assert.AreEqual (100, s.Foo, "#3-1");
			// ... !!!
			Assert.AreEqual (1, s.PropertyValues.Count, "#3-2");
			SettingsPropertyValue v = s.PropertyValues ["Foo"];
			Assert.AreEqual (100, v.PropertyValue, "#3-3");
			Assert.AreEqual (0, s.Context.Count, "#3-4");

			// initialize w/ the provider
			provs.Add (p);
			provs.Add (new MyProvider2 ("Bar", 25));
			props.Add (new SettingsProperty ("Bar", typeof (int), provs ["MyProvider2"], false, 10, SettingsSerializeAs.String, null, true, true));
			s.Initialize (new SettingsContext (), props, provs);
			Assert.AreEqual (1, s.PropertyValues.Count, "#4-1");
			Assert.AreEqual (100, s.Foo, "#4-2");
			Assert.AreEqual (25, s.Bar, "#4-3");
			// ... !!!
			Assert.AreEqual (2, s.PropertyValues.Count, "#4-3-2");
			Assert.AreEqual (0, s.Context.Count, "#4-4");

			// wrong provider
			props.Remove ("Bar");
			props.Add (new SettingsProperty ("Bar", typeof (int), provs ["MyProvider"], false, 10, SettingsSerializeAs.String, null, true, true));
			s = new MySettings ();
			s.Initialize (new SettingsContext (), props, provs);
			Assert.AreEqual (0, s.PropertyValues.Count, "#5-1");
			Assert.AreEqual (100, s.Foo, "#5-2");
			Assert.AreEqual (10, s.Bar, "#5-3");
		}
		public void PropertyValuesUninitialized ()
		{
			MySettings s = new MySettings ();
			s.Initialize (new SettingsContext (), new SettingsPropertyCollection (), new SettingsProviderCollection ());
			s.Properties.Add (new SettingsProperty ("Foo"));
			// values are filled only at initialization phase.
			Assert.AreEqual (0, s.PropertyValues.Count, "#1");
		}
		public void PropertyValuesInstance ()
		{
			SettingsPropertyCollection props = new SettingsPropertyCollection ();
			SettingsProviderCollection provs = new SettingsProviderCollection ();

			MyProvider p = new MyProvider ();
			MySettings s = new MySettings ();

			props.Add (new SettingsProperty ("Foo", typeof (string), p, false, 10, SettingsSerializeAs.String, null, true, true));
			provs.Add (p);

			s.Initialize (new SettingsContext (), props, provs);
			Assert.AreEqual (s.PropertyValues, s.PropertyValues);
		}
Example #45
0
 private void LoadSettings()
 {
     settings =
         (MySettings)CommonTypes.SettingsManager.LoadSettings(assemblyInfo.CompanyName, assemblyInfo.ProductName)
             ?? MySettings.Default;
 }
 public MyDataGridView()
 {
     _settings = new MySettings(Name);
 }
		public void AddPropertyNoProviderButInProviders ()
		{
			SettingsPropertyCollection props = new SettingsPropertyCollection ();
			SettingsProviderCollection provs = new SettingsProviderCollection ();

			MyProvider p = new MyProvider ();
			MySettings s = new MySettings ();

			props.Add (new SettingsProperty ("Foo", typeof (string), null, false, 10, SettingsSerializeAs.String, null, true, true));
			provs.Add (p);

			s.Initialize (new SettingsContext (), props, provs);
			Assert.AreEqual (100, s.Foo);
		}
 public FormsAuthenticationService(IExConfigurationManager configurationManager, MySettings settings)
 {
     _configurationManager = configurationManager;
     _settings = settings;
 }
		public void ExceptionalGetPropertyValues ()
		{
			SettingsPropertyCollection props = new SettingsPropertyCollection ();
			SettingsProviderCollection provs = new SettingsProviderCollection ();

			MyProvider3 p = new MyProvider3 ();
			MySettings s = new MySettings ();

			props.Add (new SettingsProperty ("Foo", typeof (string), p, false, 10, SettingsSerializeAs.String, null, true, true));
			provs.Add (p);

			s.Initialize (new SettingsContext (), props, provs);
			Assert.AreEqual (0, s.Context.Count, "#0");
			try {
				Assert.AreEqual (100, s.Foo, "#1");
				Assert.Fail ("#2");
#if !TARGET_JVM
			} catch (Win32Exception) {
#else
			} catch (CustomerException) {
#endif
			}
		}