public DiagnosticLogCenterLoggerProvider(Microsoft.Extensions.Configuration.IConfiguration configuration) { var logConfig = configuration?.GetValue <string>("Logging:LogLevel:Default"); if (!string.IsNullOrEmpty(logConfig)) { bool suc = Enum.TryParse(logConfig, out LogLevel); if (!suc) { LogLevel = LogLevel.Warning; } } else { LogLevel = LogLevel.Warning; } }
/// <summary> /// Creates a Cadmus repository. /// </summary> /// <returns>repository</returns> /// <exception cref="ArgumentNullException">null database</exception> public ICadmusRepository CreateRepository() { // create the repository (no need to use container here) MongoCadmusRepository repository = new MongoCadmusRepository( _partTypeProvider, new StandardItemSortKeyBuilder()); repository.Configure(new MongoCadmusRepositoryOptions { ConnectionString = string.Format( _configuration.GetConnectionString("Default"), _configuration.GetValue <string>("DatabaseNames:Data")) }); return(repository); }
// GET: /<controller>/ public async Task <IActionResult> Index(string keyword, int?page, string orderby = "importance", string sort = "desc") { var vm = new WebpartListVM() { PageIndex = page ?? 1, PageSize = _config.GetValue <int>("Modules:Webpart:Administrator:PageSize"), Keyword = keyword, OrderBy = orderby, Sort = sort }; var query = _context.Webparts.AsNoTracking().AsQueryable(); if (!string.IsNullOrEmpty(keyword)) { query = query.Where(d => d.Title.Contains(keyword) || d.Body.Contains(keyword)); } vm.TotalCount = await query.CountAsync(); var goSort = $"{orderby}_{sort}"; query = goSort switch { "title_asc" => query.OrderBy(s => s.Title), "title_desc" => query.OrderByDescending(s => s.Title), "date_asc" => query.OrderBy(s => s.CreatedDate), "date_desc" => query.OrderByDescending(s => s.CreatedDate), "importance_asc" => query.OrderBy(s => s.Importance), "importance_desc" => query.OrderByDescending(s => s.Importance), _ => query.OrderByDescending(s => s.Id), }; var pages = await query .Skip((vm.PageIndex - 1) *vm.PageSize) .Take(vm.PageSize).ProjectTo <WebpartVM>(_mapper.ConfigurationProvider).ToListAsync(); vm.Webparts = new StaticPagedList <WebpartVM>(pages, vm.PageIndex, vm.PageSize, vm.TotalCount); ViewBag.PageSizes = new SelectList(Site.PageSizes()); return(View(vm)); }
private void LoadSampleXml() { var sampleFilePath = ""; try { xdoc = new XmlDocument(); sampleFilePath = m_config.GetValue <string>("SampleXMLfilePath"); var owners = System.IO.File.ReadAllText(sampleFilePath); xdoc.LoadXml(owners); isSampalXpathAvailable = true; } catch (Exception ex) { var errormessage = "Failed to load SampleXml from " + sampleFilePath; s_log.Error(errormessage, ex); isSampalXpathAvailable = false; } }
public async Task <UserInfo> Authenticate(TokenRequest req) { // control the requests if (string.IsNullOrWhiteSpace(req.LoginPassword) || string.IsNullOrWhiteSpace(req.LoginUser)) { return(null); } var user = await _dbContext .Users .SingleOrDefaultAsync(user => user.LoginName == req.LoginUser && user.Password == req.LoginPassword); if (user == null) { return(null); } var secretKey = _configuration.GetValue <string>("JwttokenKey"); var singingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); var tokenDesc = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), NotBefore = DateTime.Now, Expires = DateTime.Now.AddHours(1), SigningCredentials = new SigningCredentials(singingKey, SecurityAlgorithms.HmacSha256Signature) }; var tokenHandler = new JwtSecurityTokenHandler(); var newToken = tokenHandler.CreateToken(tokenDesc); var userInfo = _mapper.Map <UserInfo>(user); userInfo.ExpireTime = tokenDesc.Expires ?? DateTime.Now.AddHours(1); // newToken.ValidTo userInfo.Token = tokenHandler.WriteToken(newToken); return(userInfo); }
/// <summary> ///Creates a httpclient to query cocoapods.org to get package details /// </summary> /// <param name="packageName"></param> /// <returns>latest package version</returns> public async Task <string> GetLatestVersion(string packageName) { if (!_cache.TryGetValue($"cocoapods: {packageName}", out string packageVersion)) { var httpClient = _clientFactory.CreateClient(); var apiUrl = $"https://cocoapods.org/pods/{packageName}"; var responseMessage = await httpClient.GetAsync(apiUrl); if (responseMessage.IsSuccessStatusCode) { await using var stream = await responseMessage.Content.ReadAsStreamAsync(); using (var streamReader = new StreamReader(stream)) { var html = await streamReader.ReadToEndAsync(); // Load the HTML into an AngleSharp context for parsing var browsingContext = BrowsingContext.New(Configuration.Default); var htmlDoc = await browsingContext.OpenAsync(req => req.Content(html)); // Version is inside a <span> inside an <h1> var h1Elements = htmlDoc.All.Where(e => e.LocalName == "h1" && e.ChildElementCount == 1); foreach (var h1 in h1Elements) { if (h1.FirstElementChild.LocalName == "span") { // Found the version packageVersion = h1.FirstElementChild.InnerHtml; var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration( TimeSpan.FromSeconds(_config.GetValue <double>(Constants.Timeout))); _cache.Set($"cocoapods: {packageName}", packageVersion, cacheEntryOptions); return(packageVersion); } } } } } return(packageVersion ?? ""); }
public IActionResult Index() { string servicesUrl = _configuration.GetValue <string>("Consumers:UrlService"); string countri = ""; IEnumerable <string> listCountries; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(servicesUrl); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // List all Names. HttpResponseMessage response = client.GetAsync("api/Values/TraerDatos/").Result; if (response.IsSuccessStatusCode) { countri = response.Content.ReadAsStringAsync().Result; } listCountries = JsonConvert.DeserializeObject <IEnumerable <string> >(countri); return(View(listCountries)); }
public async Task <ActionResult <PWSDetail> > PostPws(PWSDetail pws, string secret) { if (secret != _configuration.GetValue <string>("PSWAddSecret")) { return(Unauthorized()); } var exists = await _context.Pws.FirstOrDefaultAsync(p => p.Id == pws.Id); if (exists != null) { return(NotFound("can't add pws")); } _context.Pws.Add(new Pws() { Alt = pws.Alt, Desc = pws.Desc, Id = pws.Id, Lat = pws.Lat, Lon = pws.Lon, Name = pws.Name, Pwd = pws.Pwd }); await _context.SaveChangesAsync(); return(Created($"Pws/{pws.Id}/{pws.Pwd}", pws)); }
private async Task <string> GenerateToken(ApplicationUser user) { //Definimos un secretKey var secretKey = _configuration.GetValue <string>("SecretKey"); var key = Encoding.ASCII.GetBytes(secretKey); //Los Claims contiene información relevante de nuestro usuario var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id),//Asociar el id del usuario new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Name, user.Nombres), new Claim(ClaimTypes.Surname, user.Apellidos) }; //Roles var roles = await _userManager.GetRolesAsync(user); foreach (var role in roles) { claims.Add( new Claim(ClaimTypes.Role, role) ); } //Contiene la información del token var tokenDescriptor = new SecurityTokenDescriptor { //Los Claims contiene información relevante de nuestro usuario Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddDays(1),//Duración de un dia a partir de hoy SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var tokenHandler = new JwtSecurityTokenHandler(); var createdToken = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(createdToken)); }
public static void ConfigureSso(this IServiceCollection services, IConfiguration configuration) { var database = configuration.GetValue <DatabaseType>("ApplicationSettings:DatabaseType"); var connString = configuration.GetConnectionString("SSOConnection"); services .ConfigureUserIdentity <AspNetUser>().AddDatabase(database, connString) .AddCustomClaimsFactory <ApplicationClaimsIdentityFactory>() .ConfigureIdentityServer() .AddSigninCredentialFromConfig(configuration.GetSection("CertificateOptions")) .AddOAuth2Database(database, connString); var configurationExpression = new MapperConfigurationExpression(); SsoMapperConfig.RegisterMappings().ForEach(p => configurationExpression.AddProfile(p)); configurationExpression.AddProfile(new CustomMappingProfile()); var automapperConfig = new MapperConfiguration(configurationExpression); services.TryAddSingleton(automapperConfig.CreateMapper()); // Adding MediatR for Domain Events and Notifications services.AddMediatR(typeof(Startup)); }
public IActionResult add([FromBody] AdvertViewModel model) { var advert = model; if (advert != null) { string imageName = Guid.NewGuid().ToString() + ".jpg"; string base64 = model.Image; if (base64.Contains(",")) { base64 = base64.Split(',')[1]; } var bmp = base64.FromBase64StringToImage(); string fileDestDir = _env.ContentRootPath; fileDestDir = Path.Combine(fileDestDir, _configuration.GetValue <string>("ImagesPath")); string fileSave = Path.Combine(fileDestDir, imageName); if (bmp != null) { int size = 1000; var image = ImageHelper.CompressImage(bmp, size, size); image.Save(fileSave, ImageFormat.Jpeg); } dbcontext.Adverts.Add(new Advert { Title = model.Title, Description = model.Description, ImagePath = imageName, User = _userManager.FindByIdAsync(model.UserId).Result }); dbcontext.SaveChanges(); return(Ok(advert)); } else { return(new BadRequestObjectResult("Server error")); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { //_eventHandler.RegisterHandler("Monitor:ServersMonitorRecordAdded", (handler) => ServersMonitorRecorded += handler.Listener); while (!stoppingToken.IsCancellationRequested) { var timerSeconds = _configuration.GetValue <int>("MonitorSettings:TrackerTimer", 15); var nextTime = DateTime.Now; var secondsLeft = timerSeconds - (nextTime.Second % timerSeconds); nextTime = nextTime.AddTicks(-(nextTime.Ticks % TimeSpan.TicksPerSecond)); // We truncate it nextTime = nextTime.AddSeconds(secondsLeft); // And we add the seconds left TimeSpan difference = nextTime - DateTime.Now; await Task.Delay(difference, stoppingToken); _logger.LogDebug("Fetching all servers data to save it in the database"); using (var scope = _serviceProvider.CreateScope()) using (var db = scope.ServiceProvider.GetService <MonitorDBContext>()) { var servers = db.Servers .Include(s => s.Game) .Include(s => s.Owner) .Include(s => s.Group) .Where(s => s.PID.HasValue); //.ToListAsync(); List <ServerResourceMonitoringRegistry> monitoringEntries = new List <ServerResourceMonitoringRegistry>(); var cancellationToken = new CancellationTokenSource(); cancellationToken.CancelAfter(5000); // 5 seconds max var writeCustomerBlock = new ActionBlock <Server>(async s => { try { var usageTask = GetServerUsage(s); var infoTask = _gameHandler.GetServerInfo(s, cancellationToken.Token); await Task.WhenAll(usageTask, infoTask); var usage = await usageTask; var info = await infoTask; var entry = new ServerResourceMonitoringRegistry() { Server = s, TakenAt = DateTime.Now, CPUUsage = usage.CPUUsage, MemoryUsage = usage.MemoryUsage, ActivePlayers = info.Players }; await db.ServerResourceMonitoring.AddAsync(entry); monitoringEntries.Add(entry); } catch (Exception err) { _logger.LogError(err, "There has been an error while fetching the data of server with id {0}", s.Id); // Ignore, continue with the others } }); await servers.ForEachAsync(async s => { await writeCustomerBlock.SendAsync(s); }); writeCustomerBlock.Complete(); await writeCustomerBlock.Completion; await db.SaveChangesAsync(); _logger.LogDebug("All servers information fetched and saved!"); cancellationToken.Dispose(); if (monitoringEntries.Count > 0) { ServersMonitorRecorded?.Invoke(this, new ServerRecordsEventArgs() { RowsInserted = monitoringEntries.Select(e => e.Id).ToArray() }); } } } }
public async Task OnGet() { CategoryDTO categoryDTO = new CategoryDTO() { Tittle = "Food2" }; Category category = new Category(_mapper, _categoryEFService); categoryDTO.CategoryId = await category.CreateNewCategoryAsync(categoryDTO); ProductDTO productAppleDTO = new ProductDTO() { CategoryId = categoryDTO.CategoryId, Price = 100, Tittle = "Apple" }; ProductDTO productAlmondDTO = new ProductDTO() { CategoryId = categoryDTO.CategoryId, Price = 150, Tittle = "Almond" }; Product product = new Product(_mapper, _productEFService); productAppleDTO.ProductId = await product.CreateProductAsync(productAppleDTO); productAlmondDTO.ProductId = await product.CreateProductAsync(productAlmondDTO); Cart cart = new Cart(_cartEFService, _mapper, _productEFService, _categoryEFService); CartDetailDTO cartDetailDTO1 = new CartDetailDTO() { ProductId = productAlmondDTO.ProductId, ProductQuantity = 3 }; CartDetailDTO cartDetailDTO2 = new CartDetailDTO() { ProductId = productAppleDTO.ProductId, ProductQuantity = 1 }; CartDTO cartDTO = new CartDTO() { CustomerId = 1 }; cartDTO.CartId = await cart.CreateCartAsync(cartDTO); await cart.AddItemAsync(cartDTO.CartId, productAppleDTO, 3); List <CampaignDTO> campaigns = new List <CampaignDTO>(); CampaignDTO campaignDTO1 = new CampaignDTO() { CategoryId = categoryDTO.CategoryId, Discount = 20, DiscountType = DiscountType.Rate, Quantity = 3 }; CampaignDTO campaignDTO2 = new CampaignDTO() { CategoryId = categoryDTO.CategoryId, Discount = 50, DiscountType = DiscountType.Rate, Quantity = 5 }; CampaignDTO campaignDTO3 = new CampaignDTO() { CategoryId = categoryDTO.CategoryId, Discount = 5, DiscountType = DiscountType.Amount, Quantity = 5 }; Campaign campaign = new Campaign(_mapper, _campaignEFService); campaignDTO1.CampaignId = await campaign.CreateCampaignAsync(campaignDTO1); campaignDTO2.CampaignId = await campaign.CreateCampaignAsync(campaignDTO2); campaignDTO3.CampaignId = await campaign.CreateCampaignAsync(campaignDTO3); campaigns.Add(campaignDTO1); campaigns.Add(campaignDTO2); campaigns.Add(campaignDTO3); await cart.ApplyCampaignDiscountAsync(cartDTO, campaigns); CouponDTO couponDTO = new CouponDTO() { Discount = 10, DiscountType = ECommerce.Business.Models.DiscountType.Rate, MinimumCartCost = 100 }; Coupon coupon = new Coupon(_mapper, _couponEFService); couponDTO.CouponId = await coupon.CreateNewCouponAsync(couponDTO); await cart.ApplyCouponDiscountAsync(cartDTO, couponDTO); Delivery delivery = new Delivery(_deliveryEFService, _cartEFService, _productEFService, _categoryEFService, _mapper); double costPerDelivery = _configuration.GetValue <double>("CostPerDelivery"); double costPerProduct = _configuration.GetValue <double>("CostPerProduct"); double fixedCost = _configuration.GetValue <double>("FixedCost"); double deliveryCost = await delivery.CalculateDeliveryCostAndCountAsync(cartDTO.CartId, costPerDelivery, costPerProduct, fixedCost); double cartAmount = await cart.GetTotalAmountAfterDiscountsAsync(cartDTO); double couponDiscount = await cart.GetCouponDiscountAsync(cartDTO); double campaignDiscount = await cart.GetCampaignDiscountAsync(cartDTO); double getDeliveryCost = await delivery.GetDeliveryCostAsync(cartDTO); IList <PrintModel> printModels = await cart.PrintAsync(cartDTO); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddRazorPages() .AddRazorRuntimeCompilation(); services.AddDbContext <BookCycleContext>(); services.AddIdentity <AppUser, AppRole>(opt => { opt.Password.RequireDigit = false; opt.Password.RequireUppercase = false; opt.Password.RequiredLength = 8; opt.Password.RequireLowercase = false; opt.Password.RequireNonAlphanumeric = true; opt.SignIn.RequireConfirmedEmail = true; }).AddErrorDescriber <CustomIdentityValidator>().AddEntityFrameworkStores <BookCycleContext>().AddDefaultTokenProviders(); services.ConfigureApplicationCookie(opt => { opt.Cookie.IsEssential = true; opt.Cookie.Name = "BookCycleCookie"; opt.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict; opt.Cookie.HttpOnly = true; opt.ExpireTimeSpan = TimeSpan.FromDays(20); opt.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest; opt.LoginPath = "/Home/Index"; }); services.AddScoped <IEmailSender, SmtpEmailSender>(i => new SmtpEmailSender(_configuration["EmailSender:Host"], _configuration.GetValue <int>("EmailSender:Port"), _configuration.GetValue <bool>("EmailSender:EnableSSL"), _configuration["EmailSender:UserName"], _configuration["EmailSender:Password"])); services.AddControllersWithViews(); }
public T GetConfigEntry <T>(string entryName) { return(_configuration.GetValue <T>(entryName)); }
public static string GetSection(string key) { return(Configuration.GetValue <string>(key)); }
public T Get <T>(string key) { return(_configuration.GetValue <T>(key)); }
/// <summary> ///Constructs the Url to scrape from according to the desired word. ///Takes as a parameter a word to rhyme with. ///Returns a string with the Url in the right query structure. /// </summary> private string ConstructUrl(string wordToRhymeWith) { string url = _config.GetValue <string>("Settings:Url"); //Gets the url from the appsettings.json return(url.Replace("wordGoesHere", wordToRhymeWith)); //Inserts the new query into the url and returns it }
static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); //.AddUserSecrets<Program>() //.AddEnvironmentVariables(); Microsoft.Extensions.Configuration.IConfiguration Configuration = builder.Build(); Console.WriteLine("Hello World!"); int PathToUse12or3 = Configuration.GetValue <int>("PathToUse12or3"); string DefaultPath = ""; switch (PathToUse12or3) { case 1: DefaultPath = Configuration.GetValue <string>("PathToRepository"); break; case 2: DefaultPath = Configuration.GetValue <string>("PathToRepositoryAlt"); break; case 3: DefaultPath = Configuration.GetValue <string>("PathToRepositoryWithinServer"); break; case 4: DefaultPath = Configuration.GetValue <string>("PathToRepositoryCopy"); break; } string GenerateTextPath = Configuration.GetValue <string>("GenerateTextPath"); var rootFolder = GetSamples.GetSamplesProjects.GetFolders(DefaultPath); System.Diagnostics.Debug.WriteLine(Project.AllProjects.Count); foreach (var p in Project.AllProjects) { Console.WriteLine("{0} {2} {4} {6} {8} {10}", p.Root, " - ", p.Sub, " - ", p.Sub1, " - ", p.Sub2, " - ", p.ProjectName, " - ", p.ProjectFileName); } Console.WriteLine("=================="); foreach (var t in FolderTree.AllFolderTrees) { Console.WriteLine("{0} \tId:{1} \tParent:{2} \tNumChildren:{3} \tNumProjects:{4}", t.FolderName, t.Id, t.Parent, t.NumChildren, t.NumProjects); } Console.WriteLine("=================="); foreach (var t in FolderTree.AllFolderTrees) { if (t.HasProjects) { Console.WriteLine("{0} \tId:{1} \tParent:{2} \tNumChildren:{3} \tNumProjects:{4}", t.FolderName, t.Id, t.Parent, t.NumChildren, t.NumProjects); } } Console.WriteLine("=================="); foreach (var t in FolderTree.AllFolderTrees) { if (t.HasSolutions) { Console.WriteLine("{0} \tId:{1} \tParent:{2} \tNumSolutions:{3} \tSolution{4}", t.FolderName, t.Id, t.Parent, t.NumSolutions, t.Solutions[0]); } } var projIds = (from p in Project.AllProjects select p.Id).ToList(); var treeIds = (from t in FolderTree.AllFolderTrees select t.Projects).ToList(); var ll = treeIds.SelectMany(d => d).ToList(); var sdf = ll.Except(projIds).ToList(); var sdf2 = projIds.Except(ll).ToList(); }
public ApiClientController(IConfiguration configuration) { _configuration = configuration; ApplicationSettings.ApiUrl = _configuration.GetValue <string>("BaseUrl:root"); }