public SlackBinding(ParameterInfo parameter, SlackAttribute attribute, SlackConfiguration config, INameResolver nameResolver, BindingProviderContext context) { _parameter = parameter; _attribute = attribute; _config = config; _nameResolver = nameResolver; if (!string.IsNullOrEmpty(_attribute.WebHookUrl)) { _webHookUrlBindingTemplate = CreateBindingTemplate(_attribute.WebHookUrl, context.BindingDataContract); } if (!string.IsNullOrEmpty(_attribute.Text)) { _textBindingTemplate = CreateBindingTemplate(_attribute.Text, context.BindingDataContract); } if (!string.IsNullOrEmpty(_attribute.Username)) { _usernameBindingTemplate = CreateBindingTemplate(_attribute.Username, context.BindingDataContract); } if (!string.IsNullOrEmpty(_attribute.IconEmoji)) { _iconEmojiBindingTemplate = CreateBindingTemplate(_attribute.IconEmoji, context.BindingDataContract); } if (!string.IsNullOrEmpty(_attribute.Channel)) { _channelBindingTemplate = CreateBindingTemplate(_attribute.Channel, context.BindingDataContract); } }
public void CreateDefaultMessage_CreatesExpectedMessage(SlackAttribute attribute, SlackConfiguration config, Dictionary<string, object> bindingData, INameResolver nameResolver,SlackMessage targetMessage, String targetUrl) { ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First(); Dictionary<string, Type> contract = new Dictionary<string, Type> { {"ChannelParam", typeof(string) }, {"IconParam", typeof(string) }, {"TextParam", typeof(string) }, {"UsernameParam", typeof(string) }, {"WebHookUrlParam", typeof(string) } }; BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None); SlackBinding binding = new SlackBinding(parameter, attribute, config, nameResolver, context); // Generate message with input data SlackMessage message = binding.CreateDefaultMessage(bindingData); // Check that the right values were used to initialize the funtion Assert.Equal(targetMessage.Channel, message.Channel); Assert.Equal(targetMessage.IconEmoji, message.IconEmoji); Assert.Equal(targetMessage.Text, message.Text); Assert.Equal(targetMessage.Username, message.Username); Assert.Equal(targetMessage.Mrkdwn, message.Mrkdwn); Assert.Equal(targetUrl, binding._client.BaseUrl); }
// Please set the following connection strings in app.config for this WebJob to run: // AzureWebJobsDashboard and AzureWebJobsStorage static void Main() { var config = new JobHostConfiguration(); var slackConfig = new SlackConfiguration(); WebHooksConfiguration webhookConfig; if (config.IsDevelopment) { config.UseDevelopmentSettings(); webhookConfig = new WebHooksConfiguration(3000); } else { webhookConfig = new WebHooksConfiguration(); } // These are optional and will be applied if no other value is specified. /* * slackConfig.WebHookUrl = ""; * // IT IS A BAD THING TO HARDCODE YOUR WEBHOOKURL, USE THE APP SETTING "AzureWebJobsSlackWebHookKeyName" * slackConfig.IconEmoji = ""; * slackConfig.Username = ""; * slackConfig.Channel = ""; */ config.UseSlack(slackConfig); config.UseWebHooks(webhookConfig); var host = new JobHost(config); // The following code ensures that the WebJob will be running continuously host.RunAndBlock(); }
private static void AddConfigurationServices(IServiceCollection services) { services.AddSingleton(configuration); services.AddSingleton <TeamsConfiguration>(ctx => { var t = new TeamsConfiguration(); configuration.Bind("Teams", t); return(t); }); services.AddSingleton <BackupOptions>(ctx => { var t = new BackupOptions(); configuration.Bind("Backup", t); return(t); }); services.AddSingleton <MySqlOptions>(ctx => { var t = new MySqlOptions(); configuration.Bind("MySql", t); return(t); }); services.AddSingleton <RetentionOptions>(ctx => { var t = new RetentionOptions(); configuration.Bind("Retention", t); return(t); }); services.AddSingleton <SlackConfiguration>(ctx => { var t = new SlackConfiguration(); configuration.Bind("Slack", t); return(t); }); services.AddSingleton <AzureConfiguration>(ctx => { var t = new AzureConfiguration(); configuration.Bind("Azure", t); return(t); }); services.AddSingleton <S3Configuration>(ctx => { var t = new S3Configuration(); configuration.Bind("S3", t); return(t); }); services.AddSingleton <PhysicalConfiguration>(ctx => { var t = new PhysicalConfiguration(); configuration.Bind("Physical", t); return(t); }); }
public IDictionary <string, string> CreateQueryString(SlackConfiguration slackConfiguration, string userId) { var queryString = CreateQueryString(slackConfiguration); queryString.Add("user", userId); return(queryString); }
public SlackApiClient(ResilientHttpClient httpClient, ILogger logger, SlackConfiguration configuration) { _configuration = configuration; _logger = logger; _httpClient = httpClient; InitializeChannelId(_configuration.PostChannel); }
public IDictionary <string, string> CreateQueryString(SlackConfiguration slackConfiguration) { var queryString = new Dictionary <string, string> { { "token", slackConfiguration.BotToken } }; return(queryString); }
private static async Task ReportToSlack(SlackConfiguration config, ILogger logger, IEnumerable <ValidationReport> reports) { var slackClient = new SlackClient(config); using var response = await slackClient.SendMessageAsync(reports); var isValid = response.IsSuccessStatusCode ? "valid" : "invalid"; logger.LogInformation("Received {isValid} response.", isValid); }
public SlackClient(SlackConfiguration configuration) { _configuration = configuration; InitializeMessageBufferFromDisk(); var httpClient = new ResilientHttpClient(); _messageClient = new SlackMessageClient(httpClient, configuration); var logger = new ConsoleLogger("SlackClient", (name, level) => true, includeScopes: true); _apiClient = new SlackApiClient(httpClient, logger, configuration); }
internal SlackMessageHandlersConfiguration(SlackConfiguration slack) { if (slack == null) { throw new ArgumentNullException(nameof(slack)); } _installer = new MessageHandlersInstaller(); Slack = slack.Change(s => s .Application.Services(services => services .Advanced(advanced => advanced .Install(_installer)))); }
public SlackMessageBuilderTests() { _exception = new Exception("This is an exception!"); _notifierOptions = new NotifierOptions { ProjectName = "Fried Chicken", Environment = "Development" }; _slackConfiguration = new SlackConfiguration { Channel = "the chicken channel", Username = "******", WebhookUri = "http://chicken-channel.slack.com/services/hooks/incomig-webhook?token=123" }; }
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup <Startup>() .UseSerilog( (hostingContext, loggerConfiguration) => { var slackConfiguration = new SlackConfiguration(); hostingContext.Configuration.GetSection("Slack").Bind(slackConfiguration); loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration); if (!string.IsNullOrWhiteSpace(slackConfiguration.AlertingWebHook)) { loggerConfiguration.WriteTo .Conditional( x => (x.Level >= LogEventLevel.Error) || (x.Level == LogEventLevel.Warning && x.Exception != null) || (x.Properties.GetValueOrDefault("SourceContext")?.ToString() ?.Contains(nameof(OperatorStartup)) ?? false), configuration => configuration.Sink(new SlackLogEventSink(slackConfiguration.AlertingWebHook)) ); } if (hostingContext.HostingEnvironment.IsDevelopment()) { loggerConfiguration .WriteTo.Console( outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj} {Properties:j}{NewLine}{Exception}" ); } else { loggerConfiguration.WriteTo.Console( formatter: new JsonFormatter(renderMessage: true) ); } }) .UseShutdownTimeout(TimeSpan.FromSeconds(10));
public LoginModel(SlackConfiguration slackConfiguration) { this.slackConfiguration = slackConfiguration; }
private bool IsValid(SlackConfiguration options) { return(!string.IsNullOrEmpty(options.WebHookUrl)); }
public SlackMessageClient(ResilientHttpClient httpClient, SlackConfiguration configuration) { _configuration = configuration; _httpClient = httpClient; }
public UsersController(IOptions <SlackConfiguration> slackConfiguration, IRestClient restClient, IQueryStringFactory queryStringFactory) { _slackConfiguration = slackConfiguration.Value; _restClient = restClient; _queryStringFactory = queryStringFactory; }
public SlackClient(SlackConfiguration configuration, HttpClient httpclient) { _httpClient = httpclient; _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {configuration.OAuthToken}"); }
public void CreateDefaultMessage_CreatesExpectedMessage(SlackAttribute attribute, SlackConfiguration config, Dictionary <string, object> bindingData, INameResolver nameResolver, SlackMessage targetMessage, String targetUrl) { ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First(); Dictionary <string, Type> contract = new Dictionary <string, Type> { { "ChannelParam", typeof(string) }, { "IconParam", typeof(string) }, { "TextParam", typeof(string) }, { "UsernameParam", typeof(string) }, { "WebHookUrlParam", typeof(string) } }; BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None); SlackBinding binding = new SlackBinding(parameter, attribute, config, nameResolver, context); // Generate message with input data SlackMessage message = binding.CreateDefaultMessage(bindingData); // Check that the right values were used to initialize the funtion Assert.Equal(targetMessage.Channel, message.Channel); Assert.Equal(targetMessage.IconEmoji, message.IconEmoji); Assert.Equal(targetMessage.Text, message.Text); Assert.Equal(targetMessage.Username, message.Username); Assert.Equal(targetMessage.Mrkdwn, message.Mrkdwn); Assert.Equal(targetUrl, binding._client.BaseUrl); }
private void ReadAndMapAllSettings() { SlackConfiguration.Initialize(m_appSettings, this); TeamConfiguration.Initialize(m_appSettings, this); ZoomConfiguration.Initialize(m_appSettings, this); }
public AuthenticationController(IUserService userService, SlackConfiguration slackConfiguration) { this.userService = userService; this.slackConfiguration = slackConfiguration; }
public static async Task Main(string[] args) { IConfiguration config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false) .AddJsonFile("appsettings.Development.json", optional: true) .Build(); using var di = BuildDependencyInjection(config); async Task Scanner(IEnumerable <string> repositories, Options options, IGitHubClient ghClient, GitHubConfiguration githubConfig) { var logger = di.GetService <ILogger <Program> >(); var client = di.GetService <ValidationClient>(); await client.Init(); var start = DateTime.UtcNow; var results = new List <ValidationReport>(); foreach (var repo in repositories) { await Task.Delay(TimeSpan.FromSeconds(3)); var result = await client.ValidateRepository(githubConfig.Organization, repo, options.IgnoreRepositoryRules).ConfigureAwait(false); results.Add(result); } ReportToConsole(logger, results); if (options.AutoFix) { await PerformAutofixes(ghClient, results); } if (!string.IsNullOrWhiteSpace(options.CsvFile)) { ReportToCsv(di.GetService <ILogger <CsvReporter> >(), options.CsvFile, results); } if (options.ReportToGithub) { await ReportToGitHub(ghClient, _gitHubReporterConfig, di.GetService <ILogger <GitHubReporter> >(), results); } if (options.ReportToSlack) { var slackSection = config.GetSection("Slack"); if (slackSection.Exists()) { var slackConfig = new SlackConfiguration(); slackSection.Bind(slackConfig); await ReportToSlack(slackConfig, logger, results); } } logger.LogInformation("Duration {duration}", (DateTime.UtcNow - start).TotalSeconds); } await Parser.Default .ParseArguments <ScanSelectedOptions, ScanAllOptions, GenerateDocumentationOptions>(args) .MapResult( async(ScanSelectedOptions options) => await Scanner(options.Repositories, options, di.GetService <IGitHubClient>(), di.GetService <GitHubConfiguration>()), async(ScanAllOptions options) => { var githubConfig = di.GetService <GitHubConfiguration>(); var ghClient = di.GetService <IGitHubClient>(); var allNonArchivedRepositories = ghClient .Repository .GetAllForOrg(githubConfig.Organization) .Result .Where(repository => !repository.Archived); await Scanner(allNonArchivedRepositories.Select(r => r.Name).ToArray(), options, ghClient, githubConfig); }, async(GenerateDocumentationOptions options) => { var documentCreator = di.GetService <DocumentationFileCreator>(); documentCreator.GenerateDocumentation(options.OutputFolder); await Task.CompletedTask; }, async errors => await Task.CompletedTask); }
private static void Main() { // Map from Ebay Service Models to DB Models using AutoMapper Mapper.Initialize(cfg => { cfg.CreateMap <SearchItem, SearchItemDbObject>() .ForMember(dest => dest.ItemId, opt => opt.MapFrom(source => long.Parse(source.itemId))) .ForMember(dest => dest.CategoryName, opt => opt.MapFrom(source => source.primaryCategory.categoryName)) .ForMember(dest => dest.CategoryId, opt => opt.MapFrom(source => source.primaryCategory.categoryId)) .ForMember(dest => dest.ShippingCurrency, opt => opt.MapFrom(source => source.shippingInfo.shippingServiceCost.currencyId)) .ForMember(dest => dest.ShippingCost, opt => opt.MapFrom(source => source.shippingInfo.shippingServiceCost.Value)) .ForMember(dest => dest.ShipToLocations, opt => opt.MapFrom(source => string.Join(",", source.shippingInfo.shipToLocations))); cfg.CreateMap <ListingInfo, ListingInfoDbModel>() .ForMember(dest => dest.BuyItNowPrice, opt => opt.MapFrom(source => source.buyItNowPrice.Value)) .ForMember(dest => dest.ConvertedBuyItNowPrice, opt => opt.MapFrom(source => source.convertedBuyItNowPrice.Value)); cfg.CreateMap <Condition, ConditionDbModel>(); cfg.CreateMap <SellingStatus, SellingStatusDbModel>() .ForMember(dest => dest.BidCount, opt => opt.MapFrom(source => source.bidCountSpecified ? source.bidCount : -1)) .ForMember(dest => dest.CurrentPrice, opt => opt.MapFrom(source => source.currentPrice.Value)) .ForMember(dest => dest.SellingState, opt => opt.MapFrom(source => source.sellingState)); } ); //Setup Logging var slackConfig = new SlackConfiguration() { WebhookUrl = new Uri("https://hooks.slack.com/services/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"), MinLevel = LogLevel.Information }; var loggerFactory = new LoggerFactory(); loggerFactory.AddSlack(slackConfig, "Ebay Fetcher", "Production"); var logger = loggerFactory.CreateLogger("Ebay Fetcher"); // // Fetch Items try { var ebayFetcher = new FetcherService.EbayFetcher(); var results = ebayFetcher.FetchResults().ToList(); // Get Numbers of interested people only from auctions and aren't finished yet var interestedsOfSearchItem = new Dictionary <string, int>(); foreach (var item in results.Where(i => (i.listingInfo.listingType == "Auction" || i.listingInfo.listingType == "AuctionWithBIN") && i.sellingStatus.sellingState == "Active")) { var web = new HtmlWeb(); var document = web.Load(item.viewItemURL); var interestedNode = document.DocumentNode.SelectSingleNode("//span[@class='vi-buybox-watchcount']"); if (interestedNode == null) { continue; } var interested = string.IsNullOrEmpty(interestedNode.InnerText) ? -1 : Int32.Parse(interestedNode.InnerText); interestedsOfSearchItem.Add(item.itemId, interested); } // DB Output using (var context = new EbayFetcherDbContext()) { context.Database.EnsureCreated(); var mappedSearchItems = Mapper.Map <IEnumerable <SearchItem>, IEnumerable <SearchItemDbObject> >(results).ToList(); // Set number of interested in model, where existing foreach (var searchItem in mappedSearchItems.Where(si => interestedsOfSearchItem.ContainsKey(si.ItemId.ToString()))) { searchItem.SellingStatus.InterestCount = interestedsOfSearchItem[searchItem.ItemId.ToString()]; } //Get current entries from DB var updateCount = 0; var newCount = 0; foreach (var searchItem in mappedSearchItems) { var itemToUpdate = context.SearchItems.FirstOrDefault(i => i.ItemId == searchItem.ItemId); if (itemToUpdate != null) { var updatedItem = Mapper.Map(itemToUpdate, searchItem); context.SearchItems.Update(updatedItem); updateCount++; } else { context.Add(searchItem); newCount++; } } // Save fields context.SaveChanges(); logger.LogInformation($"Created {newCount} new entries. / Updated {updateCount} entries in the db..."); } } catch (Exception e) { Console.WriteLine(e.Message); logger.LogError("Error Fetching items... please investigate."); Console.ReadKey(); } List <SearchItemDbObject> itemsToFetchGpsLocations; using (var context = new EbayFetcherDbContext()) { itemsToFetchGpsLocations = context.SearchItems.Where(s => s.Longitude == null && s.Latitude == null && s.PostalCode != null).ToList(); } var locCount = 0; foreach (var item in itemsToFetchGpsLocations) { using (var wc = new WebClient()) { if (locCount % 10 == 0) { Console.WriteLine(locCount); } try { using (var context = new EbayFetcherDbContext()) { var json = wc.DownloadString($"https://maps.googleapis.com/maps/api/geocode/json?address={item.PostalCode}+{item.Location}+{item.Country}&key=AIzaSyDlVUkkbAyjj_Xxr9OoLtD8uflgJVGyJ98"); var deserializedLocation = JsonConvert.DeserializeObject <RootLocationObject>(json); var lat = deserializedLocation.results.FirstOrDefault(); item.Latitude = lat?.geometry.location.lat.ToString(CultureInfo.InvariantCulture) ?? ""; var lng = deserializedLocation.results.FirstOrDefault(); item.Longitude = lng?.geometry.location.lng.ToString(CultureInfo.InvariantCulture) ?? ""; locCount++; context.SearchItems.Update(item); context.SaveChanges(); } } catch (Exception e) { Console.WriteLine("Error fetching locations: " + e.Message); } } } // Save Location Updates Console.WriteLine($"Updated Longitude / Latitude on {itemsToFetchGpsLocations.Count()} items."); logger.LogInformation($"Updated Longitude / Latitude on {locCount} items."); }
public SlackAttributeBindingProvider(SlackConfiguration config, INameResolver nameResolver) { _config = config; _nameResolver = nameResolver; }
public SlackAlert(SlackConfiguration slackConfiguration) { this.SlackConfiguration = slackConfiguration; }
public SlackAttributeBindingProvider(SlackConfiguration config, INameResolver nameResolver) { _config = config; _nameResolver = nameResolver; }