Beispiel #1
0
        public OptionsTextBox(
            string name,
            string modId,
            string label,
            StaticConfig config,
            Point slotSize,
            bool floatOnly   = false,
            bool numbersOnly = false,
            bool numAsString = false)
            : base(name, modId, label, config, 32, slotSize.Y / 2 - 4, slotSize.X / 2 - 64, 48)
        {
            NumAsString = numAsString;
            // text field value
            var str = config[name].ToString();

            // if the string is short
            if (str.Length < 12)
            {
                Bounds.Width  /= 2;
                InfoIconBounds = new Rectangle();
            }
            Offset.Y = 8;

            _textBox = new TextBox(SaveState)
            {
                TitleText   = name,
                Width       = Bounds.Width,
                Height      = Bounds.Height,
                numbersOnly = numbersOnly,
                FloatOnly   = floatOnly,
                Text        = !floatOnly ? str : config[name].ToString(Formatting.Indented)
            };
        }
        public void MergeFrom(CommonExtensionConfig other)
        {
            if (other == null)
            {
                return;
            }
            switch (other.ConfigTypeCase)
            {
            case ConfigTypeOneofCase.AdminConfig:
                if (AdminConfig == null)
                {
                    AdminConfig = new global::Envoy.Config.Common.Tap.V2Alpha.AdminConfig();
                }
                AdminConfig.MergeFrom(other.AdminConfig);
                break;

            case ConfigTypeOneofCase.StaticConfig:
                if (StaticConfig == null)
                {
                    StaticConfig = new global::Envoy.Service.Tap.V2Alpha.TapConfig();
                }
                StaticConfig.MergeFrom(other.StaticConfig);
                break;

            case ConfigTypeOneofCase.TapdsConfig:
                if (TapdsConfig == null)
                {
                    TapdsConfig = new global::Envoy.Config.Common.Tap.V2Alpha.CommonExtensionConfig.Types.TapDSConfig();
                }
                TapdsConfig.MergeFrom(other.TapdsConfig);
                break;
            }

            _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
        }
Beispiel #3
0
        public OptionsList(
            string name,
            string modId,
            string label,
            StaticConfig config,
            Point slotSize)
            : base(name, modId, label, config, 32, slotSize.Y / 2 - 10, 48, 44)
        {
            _dropDownOptions = Config[Name].Children().Select(t => t.ToString()).ToList();

            _numbersOnly = Config[Name].Children().Any() && Config[Name].Children().First().Type == JTokenType.Integer;

            _minusButtonBounds = new Rectangle(Bounds.X, Bounds.Y, MinusButtonSource.Width * 4, Bounds.Height);

            // dropdown bounds
            var ddWidth = _dropDownOptions
                          .Select(option => (int)Game1.smallFont.MeasureString(option).X + 28)
                          .Concat(new[] { (int)Game1.smallFont.MeasureString("Windowed Borderless Mod").X })
                          .Max() + 9 * 4;

            _dropDownBounds = new Rectangle(Bounds.X + _minusButtonBounds.Width - 4, Bounds.Y,
                                            ddWidth, Bounds.Height * (_dropDownOptions.Count > 7 ? 7
                             : _dropDownOptions.Count < 1 ? 1 : _dropDownOptions.Count));

            _plusButtonBounds = new Rectangle(Bounds.X - 8 + _minusButtonBounds.Width + _dropDownBounds.Width,
                                              Bounds.Y, 10 * 4, Bounds.Height);

            Bounds.Width = _minusButtonBounds.Width + _dropDownBounds.Width + _plusButtonBounds.Width;


            Offset.Y       = 8;
            InfoIconBounds = new Rectangle(Bounds.Width - 40, 0, 0, 0);
        }
Beispiel #4
0
        public async Task <IActionResult> Post([FromBody] SysRoleMenuAndRequestModel parameter)
        {
            var _now      = DateTime.Now;
            var apiResult = new ApiResultModel(ErrorCodeType.Success);
            var modelList = new List <SysRoleMenuAndModel>();

            foreach (var mid in parameter.menu_id_list)
            {
                modelList.Add(new SysRoleMenuAndModel()
                {
                    rma_id   = StaticConfig.GetId().ToString(),
                    menu_id  = mid,
                    role_id  = parameter.role_id,
                    rma_time = _now
                });
            }
            //先删除,再添加
            await sysRoleMenuAndService.DeleteAsync(new SysRoleMenuAndRequestModel()
            {
                role_id = parameter.role_id
            });

            if (await sysRoleMenuAndService.CreateAsync(modelList.ToArray()))
            {
                return(Created($"{route}/{parameter.rma_id}", apiResult));
            }
            apiResult.Code = ErrorCodeType.PostError;
            return(BadRequest(apiResult));
        }
Beispiel #5
0
        public ActionResult AddArticle(Article article)
        {
            var data = new object();

            article.CreatedDate = DateTime.Now;
            article.UpdateDate  = DateTime.Now;

            try
            {
                using (var db = new DIYFE.EF.DIYFEEntities())
                {
                    db.Articles.Add(article);
                    db.SaveChanges();
                }
                StaticConfig.LoadStaticCache();
                data = new { success = true };
            }
            catch (Exception ex)
            {
                if (ex.InnerException.Message != null)
                {
                    data = new { success = false, message = ex.InnerException.Message };
                }
                else
                {
                    data = new { success = false, message = ex.Message + " Another reason why EF sucks" };
                }
                return(Json(data));
            }

            return(Json(data));
        }
        public ActionResult List()
        {
            var          orders       = db.Orders.Where(x => x.Active == "POR PAGAR").Include(o => o.Product).Include(o => o.Table);
            StaticConfig staticConfig = db.StaticConfig.FirstOrDefault();

            var ids     = new List <string>();
            var numbers = new List <int>();

            foreach (var item in orders)
            {
                if (!ids.Contains(item.GroupID))
                {
                    ids.Add(item.GroupID);
                }
                if (!numbers.Contains(item.Table.TableNumber))
                {
                    numbers.Add(item.Table.TableNumber);
                }
            }
            ViewBag.ids          = ids;
            ViewBag.numbers      = numbers;
            ViewBag.staticConfig = staticConfig;

            return(View(orders.ToList()));
        }
 public void SetWeather(StaticConfig config)
 {
     rainIntensity   = config.initial_configuration.rain_intensity;
     fogIntensity    = config.initial_configuration.fog_intensity;
     roadWetness     = config.initial_configuration.road_wetness;
     currentHour     = config.initial_configuration.time_of_day;
     freezeTimeOfDay = config.initial_configuration.freeze_time_of_day;
     RefreshControls();
 }
Beispiel #8
0
    void ReadStaticConfigFile()
    {
        var configFile = "";

        if (!Application.isEditor)
        {
            var args = System.Environment.GetCommandLineArgs();
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "--config" && args.Length > i + 1)
                {
                    configFile = args[i + 1];
                }
            }
        }
        else
        {
            // uncomment to test static config in Editor
            //configFile = "static_config_sample.yaml";
        }

        if (!String.IsNullOrEmpty(configFile))
        {
            StreamReader reader       = new StreamReader(configFile);
            var          deserializer = new DeserializerBuilder()
                                        .IgnoreUnmatchedProperties()
                                        .Build();

            staticConfig = deserializer.Deserialize <StaticConfig>(reader);

            // need map and at least one vehicle specified in the static config
            if (!String.IsNullOrEmpty(staticConfig.initial_configuration.map) && staticConfig.vehicles.Count > 0)
            {
                Debug.Log("Static config map: " + staticConfig.initial_configuration.map + " vehicle: " + staticConfig.vehicles[0].type);
                staticConfig.initialized = true;

                Robots.Robots.Clear();
                var candidate = Robots.robotCandidates[0];

                foreach (var staticVehicle in staticConfig.vehicles)
                {
                    foreach (var rob in Robots.robotCandidates)
                    {
                        if (rob.name == staticVehicle.type)
                        {
                            candidate = rob;
                            break;
                        }
                    }

                    Robots.Robots.Add(new RosBridgeConnector(staticVehicle.address, staticVehicle.port, candidate));
                }
            }
        }
        UserInterfaceSetup.staticConfig = staticConfig;
    }
Beispiel #9
0
        // GET: StaticConfigs/Edit
        public ActionResult Edit()
        {
            StaticConfig staticConfig = db.StaticConfig.FirstOrDefault();

            if (staticConfig == null)
            {
                return(HttpNotFound());
            }
            return(View(staticConfig));
        }
Beispiel #10
0
 public ActionResult Edit([Bind(Include = "Id,Dollar,Name,RFC,Address,Phone")] StaticConfig staticConfig)
 {
     if (ModelState.IsValid)
     {
         db.Entry(staticConfig).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Details"));
     }
     return(View(staticConfig));
 }
Beispiel #11
0
        public ActionResult ArticleDetails(string articleType, string categoryUrl, string subCategoryUrl, string subSubCategoryUrl, string articleName)
        {
            int categoryRowId = 0;

            ArticleModel model = new ArticleModel();
            Category     cat   = new Category();

            using (var db = new DIYFE.EF.DIYFEEntities())
            {
                model.Article = db.Articles.Include("ArticleComments").Where(a => a.URLLink == articleName + ".html").FirstOrDefault();
                model.Article.ViewRequests++;
                db.Entry(model.Article).State = System.Data.EntityState.Modified;
                db.SaveChanges();
            }

            if (model.Article != null)
            {
                cat = StaticConfig.GetCatigroy(model.Article.CategoryRowId);

                model.CrumbLinkList   = StaticConfig.GenerateCrumbLinks(cat, articleType);
                model.RelatedTreeView = StaticConfig.GenerateRelatedTreeView(cat, articleType);

                PageModel.Title       = model.Article.Title;
                PageModel.Description = model.Article.Description;
                PageModel.Author      = model.Article.Author;
                PageModel.Keywords    = model.Article.Keywords;
            }
            else
            {
                //JUST TO GET BY -- REPLACE WITH 404 SOULATION
                model.CrumbLinkList = StaticConfig.GenerateCrumbLinks(new Category(), articleType);
                model.Article       = new Article();
                model.Comments      = new List <ArticleComment>();
                //model.RelatedTreeView = DIYFEHelper.GenerateTreeViewThirdLev(model.Article.CategoryRowId, linkPrefix);

                PageModel.Title       = "";
                PageModel.Description = "";
                PageModel.Author      = "";
                PageModel.Keywords    = "";
            }


            // model.Comments = la.ArticleComments(model.Article.ArticleId);

            //model.MostViewed = la.MostViewed(11, 20);
            // model.CrumbLinkList = DIYFEHelper.GenerateCrumbLinks(categoryRowId, linkPrefix);
            model.RelatedTreeView = StaticConfig.GenerateTreeViewThirdLev(cat, articleType);

            ////PageModel.Title = model.Article.Title;
            ////PageModel.Description = model.Article.Description;
            ////PageModel.Author = model.Article.Author;
            ////PageModel.Keywords = model.Article.Keywords;

            return(View(model));
        }
Beispiel #12
0
 public OptionsCheckbox(
     string name,
     string modId,
     string label,
     StaticConfig config,
     Point slotSize)
     : base(name, modId, label, config, 32, slotSize.Y / 2)
 {
     _isChecked     = config[name].ToString().ToLower() == "true";
     InfoIconBounds = new Rectangle(0, -8, 0, 0);
 }
Beispiel #13
0
        private Log()
        {
            FileInfo logFile = new FileInfo(StaticConfig.GetConfig().GetString("LogPath"));

            if (!Directory.GetParent(logFile.ToString()).Exists)
            {
                Directory.GetParent(logFile.ToString()).Create();
            }
            LogFileStreamWriter = new StreamWriter(StaticConfig.GetConfig().GetString("LogPath"));
            OnInfo  += Log_OnInfo;
            OnError += Log_OnError;
        }
Beispiel #14
0
        /// <summary>
        /// Configures all enabled configuration providers.
        /// </summary>
        public void Initialize(StaticConfig config, AuthenticationBuilder authBuilder)
        {
            var available = new List <AuthProviderVM>();

            foreach (var prov in SupportedProviders)
            {
                if (prov.TryActivate(config, authBuilder))
                {
                    available.Add(prov);
                }
            }

            AvailableProviders = available;
        }
Beispiel #15
0
        public async Task <ActionResult> Create(CreateViewModel viewModel)
        {
            userManager = StaticConfig.ConfigureApplicationUserManager(userManager);

            if (ModelState.IsValid)
            {
                IdentityResult result = await _service.CreateMentorAsync(viewModel);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                AddErrors(result);
            }
            return(View(viewModel));
        }
 public OptionsDropDown(
     string name,
     string modId,
     string label,
     StaticConfig config,
     Point slotSize,
     List <string> dropDownOptions)
     : base(name, modId, label, config, 32, slotSize.Y / 2 - 10,
            (int)Game1.smallFont.MeasureString("Windowed Borderless Mode   ").X + 48, 44)
 {
     _dropDownOptions = dropDownOptions;
     _selectedOption  = dropDownOptions.FindIndex(s => s == config[name].ToString());
     _dropDownBounds  = new Rectangle(Bounds.X, Bounds.Y, Bounds.Width - 44,
                                      Bounds.Height * _dropDownOptions.Count);
     Offset.Y = 8;
 }
        /// <summary>
        /// Sets up the cosmetic data for this model, or, what's displayed in the GUI for the program.
        /// </summary>
        /// <param name="model">The <see cref="StaticConfig"/> to pull data from.</param>
        /// <param name="dataTreeParent">This is the instance in the data tree that represents this object in the hierarchy.</param>
        public void SetupCosmeticInformation(StaticConfig model, DataTreeObject dataTreeParent)
        {
            if (dataTreeParent == null)
            {
                return;
            }

            if (model.meshes != null && model.meshes.visible != null)
            {
                List <object> subModels = new List <object>();
                int           idx       = 0;
                foreach (VisibleMesh mesh in model.meshes.visible)
                {
                    subModels.Add(new DataTreeObjectProperty("Mesh " + idx, SilkImage.Triangle));
                    idx++;
                }
                dataTreeParent.AddSimpleProperty("Geometry", subModels.ToArray(), SilkImage.Variant, SilkImage.Value, false);
            }
        }
        public SmapiIntegration()
        {
            var configPath = Path.Combine(Constants.ExecutionPath, "smapi-internal/config.json");

            if (!File.Exists(configPath))
            {
                Helper.Console.Error("SMAPI Config not found? :)");
                return;
            }

            var json = File.ReadAllText(configPath);

            json = Regex.Replace(json, "\\/{2}\"(ParanoidWarnings|UseBetaChannel)\": true,", "\"$1\": false,");
            var jObj = JObject.Parse(json);

            _staticConfig = new StaticConfig(configPath, jObj, "Pathoschild.SMAPI");

            InitOptions();
        }
Beispiel #19
0
        private static void Main(string[] args)
        {
            var config = new StaticConfig
            {
                DesiredConnections     = 22,
                MaxConnections         = 22,
                ConnectCooldown        = TimeSpan.FromMilliseconds(100),
                DisconnectCooldown     = TimeSpan.FromMilliseconds(100),
                MapUpdateCooldown      = TimeSpan.FromMilliseconds(50),
                KeySendCooldown        = TimeSpan.FromSeconds(10),
                ConnectingSocketMaxTTL = TimeSpan.FromMilliseconds(50),
                ConnectingSocketsToConnectionsMultiplier = 1,
                PreconfiguredNodes = Enumerable.Range(1, 22).Select(i => new TcpAddress(new IPEndPoint(IPAddress.Parse(string.Format(AddressFormat, i)), 16800)) as IAddress).ToList(),
                LocalAddress       = GetLocalAddress(16800),
                LongNames          = true
            };
            var node = CreateNode(config, config, "storage");

            node.Start();
        }
    void ReadStaticConfigFile()
    {
        var configFile = "";

        if (!Application.isEditor)
        {
            var args = System.Environment.GetCommandLineArgs();
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "--config" && args.Length > i + 1)
                {
                    configFile = args[i + 1];
                }
            }
        }
        else
        {
            if (isLoadDevConfig)
            {
                configFile = "static_config_sample.yaml";
            }
        }

        if (!String.IsNullOrEmpty(configFile))
        {
            StreamReader reader       = new StreamReader(configFile);
            var          deserializer = new DeserializerBuilder()
                                        .IgnoreUnmatchedProperties()
                                        .Build();

            staticConfig = deserializer.Deserialize <StaticConfig>(reader);

            // need map and at least one vehicle specified in the static config
            if (!String.IsNullOrEmpty(staticConfig.initial_configuration.map) && staticConfig.vehicles.Count > 0)
            {
                //Debug.Log("Static config map: " + staticConfig.initial_configuration.map + " vehicle: " + staticConfig.vehicles[0].type);
                staticConfig.initialized = true;
            }
        }
    }
        public void HandleModelConfig(FileInfo sourceFile, ModelConfig baseModel, List <Model3D> modelCollection, DataTreeObject dataTreeParent = null, Transform3D globalTransform = null, Dictionary <string, dynamic> extraData = null)
        {
            // ModelConfigHandler.SetupCosmeticInformation(baseModel, dataTreeParent);
            StaticConfig model = (StaticConfig)baseModel.implementation;

            SetupCosmeticInformation(model, dataTreeParent);

            //Model3D mdl = new Model3D();
            MeshSet meshes = model.meshes;

            VisibleMesh[] renderedMeshes = meshes.visible;

            SKAnimatorToolsProxy.IncrementEnd(renderedMeshes.Length);
            int    idx           = 0;
            string depth1Name    = ResourceDirectoryGrabber.GetDirectoryDepth(sourceFile);
            string fullDepthName = ResourceDirectoryGrabber.GetDirectoryDepth(sourceFile, -1);

            foreach (VisibleMesh mesh in renderedMeshes)
            {
                string meshTitle = "-Mesh[" + idx + "]";


                Model3D meshToModel = GeometryConfigTranslator.GetGeometryInformation(mesh.geometry, fullDepthName + meshTitle);
                meshToModel.Name      = depth1Name + meshTitle;
                meshToModel.Transform = meshToModel.Transform.compose(globalTransform).compose(new Transform3D(meshes.bounds.getCenter(), Quaternion.IDENTITY, 1f));
                //meshToModel.Textures.SetFrom(ModelConfigHandler.GetTexturesFromModel(sourceFile, model));
                //meshToModel.Textures.SetFrom(ModelPropertyUtility.FindTexturesFromDirects(baseModel));
                //meshToModel.Textures.SetFrom(new List<string>() { mesh.texture });
                //meshToModel.ActiveTexture = mesh.texture;

                (List <string> textureFiles, string active) = ModelPropertyUtility.FindTexturesAndActiveFromDirects(baseModel, mesh.texture);
                meshToModel.Textures.SetFrom(textureFiles);
                meshToModel.ActiveTexture = active;

                modelCollection.Add(meshToModel);
                idx++;
                SKAnimatorToolsProxy.IncrementProgress();
            }
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (configTypeCase_ == ConfigTypeOneofCase.AdminConfig)
            {
                hash ^= AdminConfig.GetHashCode();
            }
            if (configTypeCase_ == ConfigTypeOneofCase.StaticConfig)
            {
                hash ^= StaticConfig.GetHashCode();
            }
            if (configTypeCase_ == ConfigTypeOneofCase.TapdsConfig)
            {
                hash ^= TapdsConfig.GetHashCode();
            }
            hash ^= (int)configTypeCase_;
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        public OptionsPlusMinus(
            string name,
            string modId,
            string label,
            StaticConfig config,
            Point slotSize,
            List <string> plusMinusOptions)
            : base(name, modId, label, config, 32, slotSize.Y / 2 - 10, 56, 44)
        {
            _options        = plusMinusOptions;
            _selectedOption = plusMinusOptions.FindIndex(s => s == config[name].ToString());
            _minusButton    = new Rectangle(Bounds.X, Bounds.Y, MinusButtonSource.Width * 4, Bounds.Height);

            var bWidth = _options
                         .Select(displayOption => (int)Game1.smallFont.MeasureString(displayOption).X + 28)
                         .Concat(new[] { (int)Game1.smallFont.MeasureString(_options[0]).X + 28 })
                         .Max();

            _plusButton    = new Rectangle(Bounds.X + _minusButton.Width + bWidth, Bounds.Y, PlusButtonSource.Width * 4, Bounds.Height);
            Bounds.Width   = _minusButton.Width + bWidth + _plusButton.Width;
            Offset.Y       = 8;
            InfoIconBounds = new Rectangle(bWidth + 40, 0, 0, 0);
        }
 static Net50Configurator()
 {
     StaticConfig.Configure(new Net50Configuration());
 }
 public static void Configure()
 {
     StaticConfig.Configure(new Net50Configuration());
 }
 static Core31Configurator()
 {
     StaticConfig.Configure(new Core31Configuration());
 }
Beispiel #27
0
        public ActionResult ArticleList(string articleType, string categoryUrl, string subCategoryUrl, string subSubCategoryUrl, int?page)
        {
            ArticleListModel model = new ArticleListModel();

            PageModel.Title       = "";
            PageModel.Description = "";
            PageModel.Author      = "";
            PageModel.Keywords    = "";

            string url = HttpContext.Request.RawUrl;
            //int categoryRowId = DIYFEHelper.GetCatigoryRowId(categoryUrl, "", "");

            Category cat = StaticConfig.GetCatigory(categoryUrl, subCategoryUrl, subSubCategoryUrl);

            model.CrumbLinkList   = StaticConfig.GenerateCrumbLinks(cat, articleType);
            model.RelatedTreeView = StaticConfig.GenerateRelatedTreeView(cat, articleType);
            model.PageLinkBase    = StaticConfig.BaseSiteUrl + articleType;
            if (categoryUrl != "")
            {
                model.PageLinkBase += "/" + cat.CategoryUrl;
            }
            if (subCategoryUrl != "")
            {
                model.PageLinkBase += "/" + cat.SecondLevCategoryUrl;
            }
            if (subSubCategoryUrl != "")
            {
                model.PageLinkBase += "/" + cat.ThirdLevCategoryUrl;
            }
            //model.PageLinkBase = model.CrumbLinkList.Last().Href;
            //model.RelatedTreeView = StaticConfig.TreeView(cat, model.PageLinkBase);

            using (var db = new DIYFE.EF.DIYFEEntities())
            {
                //BASED ON CAT
                //model.ArticleList = db.Articles.Include("ArticleComments").Where(a => a.Category.CategoryId == cat.CategoryId).OrderBy(a => a.CreatedDate);
                if (categoryUrl != "")
                {
                    model.PagedArticle = db.Articles.Include("ArticleComments").Include("ArticleStatus.StatusType").Where(a => a.Category.CategoryId == cat.CategoryId && a.ArticleStatus.Any(aStat => aStat.StatusId == 1)).OrderByDescending(a => a.CreatedDate).ToPagedList(page ?? 1, pageSize);
                    //model.PagedArticle = db.Articles.Include("ArticleComments").Include("ArticleStatus.StatusType").Where(a => a.ArticleStatus.Any(aStat => aStat.StatusId == 1)).OrderByDescending(a => a.CreatedDate).ToPagedList(page ?? 1, pageSize);
                    if (subSubCategoryUrl != "")
                    {
                        model.Into = db.Articles.Where(a => a.URLLink == subSubCategoryUrl).FirstOrDefault();
                    }
                    else if (subCategoryUrl != "")
                    {
                        model.Into = db.Articles.Where(a => a.URLLink == subCategoryUrl).FirstOrDefault();
                    }
                    else
                    {
                        model.Into = db.Articles.Where(a => a.URLLink == categoryUrl).FirstOrDefault();
                    }
                }
                else
                {
                    model.PagedArticle = db.Articles.Include("ArticleComments").Include("ArticleStatus.StatusType").Where(a => a.ArticleType.ArticleTypeName == articleType && a.ArticleStatus.Any(aStat => aStat.StatusId == 1)).OrderByDescending(a => a.CreatedDate).ToPagedList(page ?? 1, pageSize);
                }

                model.Into       = new Article();
                model.Into.Title = "Text of H1 in work";
                //CHECK PAGING
                //model.ArticleList = db.Articles.Include("ArticleComments").Where(a => a.ArticleTypeId == 1);
                //model.PagedArticle = model.ArticleList.Concat(db.Articles.Include("ArticleComments").Include("ArticleStatus.StatusType").Where(a => a.ArticleTypeId == 2)).OrderBy(a => a.CreatedDate).ToPagedList(page ?? 1, pageSize);
            }
            //model.PagedArticle = model.ArticleList.ToPagedList(page ?? 1, pageSize);
            return(View(model));
        }
Beispiel #28
0
 public static void Configure()
 {
     StaticConfig.Configure(new Core22Configuration());
 }
Beispiel #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <JwtAuthentication>(Configuration.GetSection("JwtAuthentication"));
            services.AddControllersWithViews()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.Formatting       = Formatting.Indented;
                options.SerializerSettings.TypeNameHandling = TypeNameHandling.None;
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.TypeNameHandling = TypeNameHandling.None;
            });

            services.AddAntiforgery(options =>
            {
                options.HeaderName          = "X-XSRF-Token";
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            });

            services.AddSingleton <IPostConfigureOptions <JwtBearerOptions>, ConfigureJwtBearerOptions>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Admins", policy => policy.RequireRole(RoleType.Admin.ToString()));
                options.AddPolicy("Contributers", policy => policy.RequireRole(RoleType.Contributer.ToString(), RoleType.Admin.ToString()));
                options.AddPolicy("Readers", policy => policy.RequireRole(RoleType.Reader.ToString(), RoleType.Contributer.ToString(), RoleType.Admin.ToString()));
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });

            services.AddSignalR();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "HomePhotos API", Version = "v1"
                });
                c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "SCS.HomePhotos.Web.xml"));
                c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "SCS.HomePhotos.Model.xml"));
                c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "SCS.HomePhotos.Service.xml"));
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In          = ParameterLocation.Header,
                    Description = "Please insert JWT with Bearer into field; for example: Bearer [token here]",
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.ApiKey
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            });

            // config
            var staticConfig  = StaticConfig.Build(Configuration);
            var configData    = new ConfigData(staticConfig);
            var dynamicConfig = new DynamicConfig();

            services.AddSingleton <IStaticConfig>(staticConfig);
            services.AddSingleton <IConfigData>(configData);
            services.AddSingleton <IDynamicConfig>(dynamicConfig);
            var configService = new ConfigService(configData, dynamicConfig, staticConfig);

            SetDynamicConfig(configService).Wait();
            services.AddSingleton <IConfigService>(configService);

            // background tasks
            services.AddHostedService <QueuedHostedService>();
            services.AddHostedService <TimedIndexHostedService>();
            services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>();

            // data objects
            services.AddScoped <IPhotoData, PhotoData>();
            services.AddScoped <ITagData, TagData>();
            services.AddScoped <IUserData, UserData>();
            services.AddScoped <IUserTokenData, UserTokenData>();
            services.AddScoped <ILogData, LogData>();

            // services
            services.AddScoped <IFileSystemService, FileSystemService>();
            services.AddScoped <IImageTransformer, ImageTransformer>();
            services.AddScoped <IImageService, ImageService>();
            services.AddScoped <IPhotoService, PhotoService>();
            services.AddScoped <IFileUploadService, FileUploadService>();
            services.AddScoped <IAccountService, AccountService>();
            services.AddScoped <ISecurityService, SecurityService>();
            services.AddSingleton <IAdminLogService>(new AdminLogService(new LogData(staticConfig), staticConfig));
            services.AddSingleton <IIndexEvents, IndexEvents>();
            services.AddSingleton <IQueueEvents, QueueEvents>();
            services.AddSingleton <IClientMessageSender, ClientMessageSender>();
            services.AddSingleton <IUploadTracker, UploadTracker>();
            services.AddSingleton <IImageMetadataService, ImageMetadataService>();
        }