public async Task SubToService(string location, TimeSpan notiferTime) { if (Program.CredentialManager.OptionalSettings.Contains("WeatherApiKey")) { return; } if (notiferTime >= new TimeSpan(24, 0, 0)) { await Context.Message.Channel.SendMessageAsync("TimeSpan need to be between 00:00 and 23:59"); return; } dynamic temperature = JsonConvert.DeserializeObject <dynamic>(await ApiRequestService.Request2WeatherApiAsync(location)); if (temperature.cod != 200) { await Context.Message.Channel.SendMessageAsync((string)temperature.message); return; } User currentUser = DatabaseAccess.Instance.Users.Find(u => u.Id == Context.Message.Author.Id); currentUser.WeatherLocation = location; currentUser.NotifierTime = notiferTime; await Context.Message.Channel.SendMessageAsync($"{Context.Message.Author}, you successfully subbed to weather notifications."); }
public async Task CheckCurrentWeather(string location) { if (Program.CredentialManager.OptionalSettings.Contains("WeatherApiKey")) { return; } dynamic temperature = JsonConvert.DeserializeObject <dynamic>(await ApiRequestService.Request2WeatherApiAsync(location)); if (temperature.cod != 200) { await Context.Message.Channel.SendMessageAsync((string)temperature.message); return; } EmbedBuilder weatherEmbed = new EmbedBuilder() .WithTitle("Weather Info") .WithDescription("Current Weather Informations") .AddField(location, $"{temperature.main.temp} °C") .AddField("Current Max. Temp", $"{temperature.main.temp_max} °C") .AddField("Current Min. Temp", $"{temperature.main.temp_min} °C") .AddField("Current Weather Condition", (string)temperature.weather[0].main) .WithColor(new Color((uint)Convert.ToInt32(CommandHandlerService.MessageAuthor.EmbedColor, 16))) .WithTimestamp(DateTime.Now) .WithFooter(NET.DataAccess.File.FileAccess.GENERIC_FOOTER, NET.DataAccess.File.FileAccess.GENERIC_THUMBNAIL_URL); await Context.Message.Channel.SendMessageAsync(embed : weatherEmbed.Build()).ConfigureAwait(false); }
protected override async Task OnInitializedAsync() { Status = APIOperationStatus.Initial; Consultants = new List <ConsultantViewModel>(); var requestUrl = Env.IsDevelopment() ? "https://localhost:5009/client-gw/consultant" : "https://localhost:8088/client-gw/consultant"; try { Consultants = await ApiRequestService.HandleGetRequest <IEnumerable <ConsultantViewModel> >(requestUrl); Status = APIOperationStatus.GET_Success; } catch (Exception e) { Console.WriteLine(e); Status = APIOperationStatus.GET_Error; } StateHasChanged(); await base.OnInitializedAsync(); }
public async Task SendPicture() { //search for image without tags and rating string response = await ApiRequestService.Request2KonachanApiAsync(); await generateImageEmbed(response); }
public async Task SendPicture(params String[] tags) { string[] lowerTags = tags.Select(s => s.ToLowerInvariant()).ToArray(); string tagUrl = String.Empty; Rating rating; //generalize rating input, so misstyping isnt so bad string lowerRating = tags[0].ToLower(); string ratingElement = lowerRating.First().ToString().ToUpper() + lowerRating.Substring(1); //try to parse as enum //check if first tag is equal to a rating if (Enum.TryParse <Rating>(ratingElement, out rating)) { //get rest of the tags string[] tagCollection = lowerTags.Skip(1).ToArray(); foreach (string tag in tagCollection) { tagUrl = tagUrl + $"{tag} "; } string response = await ApiRequestService.Request2KonachanApiAsync(tagCollection, rating); await generateImageEmbed(response, tagUrl); } else { //first arg isn't an enum foreach (string tag in lowerTags) { tagUrl = tagUrl + $"{tag} "; } string response = await ApiRequestService.Request2KonachanApiAsync(lowerTags); await generateImageEmbed(response, tagUrl); } }
public ApplicationUpdaterService() { _apiRequestService = new ApiRequestService(); _fileVersion = GetActualAppVersion(); var tempPath = AppData.TempPath; _filePath = Path.Combine(tempPath, "EasyMessenger.zip"); _extractPath = Path.Combine(tempPath, "EasyMessenger"); }
private void SetUpClient() { _server = new TestServer(new WebHostBuilder() .UseStartup <Startup>()) { BaseAddress = new Uri(PathObjectMother.TestServerBaseUrl) }; Client = _server.CreateClient(); ApiService = new ApiRequestService(PathObjectMother.TestServerBaseUrl); }
public UpdaterService() { _apiRequestService = new ApiRequestService(); _fileVersion = GetActualUpdaterVersion(); var tempPath = AppData.TempPath; _filePath = Path.Combine(tempPath, "Updater.zip"); _extractPath = Path.Combine(tempPath, "Updater"); Clean(); Directory.CreateDirectory(tempPath); }
/// <summary> /// Fetch information/options from the API services. /// </summary> /// <returns></returns> private async Task <BookingViewModel> FetchBookingInfo() { var requestUrl = Env.IsDevelopment() ? "https://localhost:5009/client-gw/aggregate" : "https://localhost:8088/client-gw/aggregate"; var result = await ApiRequestService.HandleGetRequest <BookingViewModel>(requestUrl); return(result); }
private async Task Client_Ready() { AddonLoader.Load(Client); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); List <Type> commandClasses = new List <Type>(); foreach (Assembly assembly in assemblies) { commandClasses.AddRange(assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ModuleBase)) && !t.IsAbstract).ToList()); } checkNewUserEntries(); StatusNotifierService.InitializeService(Me); MusicCommands.Initialize(Client); RoleManagerService.InitializeHandler(Client, BotConfiguration); ApiRequestService.Initialize(BotConfiguration); UserManagerService.InitializeHandler(Client); await CommandHandlerService.InitializeHandler(Client, BotConfiguration, commandClasses, prefixDictionary, !CredentialManager.OptionalSettings.Contains("CleverApi")); CacheService.InitializeHandler(); VoiceRewardService.InitializeHandler(Client, BotConfiguration, !CredentialManager.OptionalSettings.Contains("CleverApi")); switch (startValue) { case 0: //shutdown break; case 1: //restarting await Me.SendMessageAsync("I have restored and restarted successfully."); break; case 2: //updating //check if an update is nessasarry await Me.SendMessageAsync("I at all the new features and restarted successfully."); break; default: break; } if (!CredentialManager.OptionalSettings.Contains("WeatherApiKey")) { if (!CredentialManager.OptionalSettings.Contains("WeatherPlace")) { MoodDictionary.InitializeMoodDictionary(Client, BotConfiguration); await MoodHandlerService.InitializeHandler(Client, BotConfiguration); } WeatherSubscriptionService.InitializeWeatherSub(Client, BotConfiguration); } }
/// <summary> /// Handle form submission. /// </summary> /// <returns></returns> private async Task HandleSubmit() { var requestUrl = Env.IsDevelopment() ? "https://localhost:5009/client-gw/appointment" : "https://localhost:8088/client-gw/appointment"; Status = APIOperationStatus.POST_Pending; StateHasChanged(); if (!PatientInApprovedList()) { ToastService.ShowError( "Patient not found. Please ensure that the personal details entered are correct and try again."); Status = APIOperationStatus.GET_Success; StateHasChanged(); return; } if (AppointmentAlreadySubmitted()) { ToastService.ShowError( "There selected consultant already has an appointment scheduled at the selected time."); Status = APIOperationStatus.GET_Success; StateHasChanged(); return; } try { var dto = CreateDTO(); var result = await ApiRequestService.HandlePostRequest(requestUrl, dto); Status = APIOperationStatus.POST_Success; var consultant = ViewModel.ConsultantList.FirstOrDefault(c => c.Id == result.ConsultantId); var timeSlot = ViewModel.TimeSlotList.FirstOrDefault(ts => ts.Id == result.TimeSlotId); ToastService.ShowSuccess( $"Appointment with Dr. {consultant?.FirstName} {consultant?.LastName} ({consultant?.Specialty}) on {result.Date:dd/MM/yyyy} from {timeSlot?.StartTime:hh:mm} to {timeSlot?.EndTime:hh:mm} successfully scheduled."); NavigationManager.NavigateTo("/"); } catch (Exception e) { ToastService.ShowError( "There was an error submitting your request. Please ensure that the entered is correct data and retry."); } }
static bool UserSearch() { var config = new ConfigurationService(); var console = new ConsoleService(config); var apirequest = new ApiRequestService(console, config); var spotify = new SpotifyService(console, config, apirequest); var analysis = new AnalysisService(); var username = console.PromptForUsername(); // get all public playlists for the provided username var playlists = spotify.GetPlaylists(username, out bool anyFound); // if the provided user has no public playlists, ask for another username if (!anyFound) { return(true); } // get metadata for each public playlist. This will give us a list of tracks. var playlistMetadatum = spotify.GetAllPlaylistMetadatum(playlists.items); // identify unique tracks from the playlist metadataum var tracks = analysis.IdentifyUniqueTracks(playlistMetadatum); // identify unique artists from the tracks. This just gets us artist names / IDs var artists = analysis.IdentifyUniqueArtists(tracks); // get the full artist info, which gets us genres. var fullArtists = spotify.GetAllArtists(artists); // identify unique genres var genres = analysis.IdentifyUniqueGenres(fullArtists); var audioFeatures = spotify.GetAudioFeaturesForAllTracks(tracks); var avgAudioFeatures = analysis.CalculateAverageAudioFeatures(audioFeatures); console.WriteMetrics( artists, genres, audioFeatures, avgAudioFeatures); return(true); }
public UsuariosController(IUsuarioRepository usuarioRepository, ITipoUsuarioRepository tipoUsuarioRepository, IEmpresaRepository empresaRepository, IUsuarioEmpresaRepository usuarioEmpresaRepository, IEnderecoRepository enderecoRepository, ITipoEmpresaRepository tipoEmpresaRepository, ITipoAtividadeCnaeRepository tipoAtividadeCnaeRepository, IAlterarCredenciaisRepository alterarCredenciaisRepository, IAlunoRepository alunoRepository, IUsuarioCandidatoAlunoRepository usuarioCandidatoAlunoRepository, IValidacaoUsuarioCandidatoRepository validacaoUsuarioCandidatoRepository, IUsuarioAdministradorRepository usuarioAdministradorRepository, IHistoricoStatusUsuarioRepository historicoStatusUsuarioRepository, IStatusUsuarioRepository statusUsuarioRepository) { _usuarioRepository = usuarioRepository; _tipoUsuarioRepository = tipoUsuarioRepository; _empresaRepository = empresaRepository; _usuarioEmpresaRepository = usuarioEmpresaRepository; _enderecoRepository = enderecoRepository; _tipoEmpresaRepository = tipoEmpresaRepository; _tipoAtividadeCnaeRepository = tipoAtividadeCnaeRepository; _alterarCredenciaisRepository = alterarCredenciaisRepository; _alunoRepository = alunoRepository; _usuarioCandidatoAlunoRepository = usuarioCandidatoAlunoRepository; _validacaoUsuarioCandidatoRepository = validacaoUsuarioCandidatoRepository; _usuarioAdministradorRepository = usuarioAdministradorRepository; _historicoStatusUsuarioRepository = historicoStatusUsuarioRepository; _statusUsuarioRepository = statusUsuarioRepository; apiRequestService = new ApiRequestService(); sendEmailService = new SendEmailService(); }
public async Task AskWikipedia(string searchTerm) { dynamic searchResult = JsonConvert.DeserializeObject <dynamic>(await ApiRequestService.Request2WikipediaApiAsync(searchTerm)); EmbedBuilder searchEmbed = new EmbedBuilder() .WithTitle($"What is \"{searchTerm}\"?") .WithDescription($"Results for {searchTerm}") .WithFooter(NET.DataAccess.File.FileAccess.GENERIC_FOOTER, NET.DataAccess.File.FileAccess.GENERIC_THUMBNAIL_URL) .WithTimestamp(DateTime.Now) .WithColor(new Color((uint)Convert.ToInt32(CommandHandlerService.MessageAuthor.EmbedColor, 16))); for (int i = 0; i < 5; i++) { if (searchResult[1][i] == null || searchResult[2][i] == null) { break; } searchEmbed.AddField((searchResult[1][i]).ToString(), (searchResult[2][i]).ToString()); } await Context.Message.Channel.SendMessageAsync(null, embed : searchEmbed.Build()).ConfigureAwait(false); }
public MainWindow() { _configService = new ConfigService(); _jiraApiService = new JiraApiService(); _apiRequestService = new ApiRequestService(); InitializeComponent(); AppHeartbeatTimer.Start(); var files = Directory.GetFiles(".", "appsettings*.json"); var applicationConfig = _configService.GetConfig <ApplicationConfig>(files.First()); var windowViewModel = new WindowViewModel { Windows = new ObservableCollection <ViewModelBase>(), IsDebugMode = applicationConfig.IsDebugMode }; DataContext = windowViewModel; Dispatcher.InvokeAsync(() => { return(InitialLoad(windowViewModel, applicationConfig)); }); }
/// <summary> /// Скачивание новой версии приложения /// и сохранение во временной папке /// </summary> private void DownloadFile() { var url = AppData.WebApiUrl + GetLastApplicationMethod; var apiRequestService = new ApiRequestService(); var result = apiRequestService.ReceiveFile(url, new JavaScriptSerializer() .Serialize(new { version = _fileVersion })); using (var fileStream = new FileStream(_filePath, FileMode.Create)) { fileStream.Write(result, 0, result.Length); } }
public JiraIconImageSourceService(ApiRequestService apiRequestService) { _apiRequestService = apiRequestService; }
public PaymentController() { _request = new ApiRequestService(); this._appDbContext = new AppDbContext(); }
public ApplicationUploader() { _apiRequestService = new ApiRequestService(); }
public UpdaterUploader() { _apiRequestService = new ApiRequestService(); }
public DashboardController() { request = new ApiRequestService(); }
public TransactionsController() { _request = new ApiRequestService(); }
public async Task SetEmbedColor(string color) { if (color.StartsWith('#')) { color = color.Substring(1, color.Length - 1); } int hexColor; if (Int32.TryParse(color, System.Globalization.NumberStyles.HexNumber, null, out hexColor)) { string result = "0x" + color.PadRight(6, '0'); if (hexColor < 16777216 && hexColor >= 0) { string previousColorCode = CommandHandlerService.MessageAuthor.EmbedColor; string previousColor; if (previousColorCode.Length != 6) { previousColor = previousColorCode.Substring(2, previousColorCode.Length - 2); } else { previousColor = previousColorCode; } string oldColorName = await ApiRequestService.Request2ColorNamesApiAsync(previousColor); if (oldColorName == null) { oldColorName = "Color has no name yet."; } string newColorName = await ApiRequestService.Request2ColorNamesApiAsync(color); if (newColorName == null) { newColorName = "Color has no name yet."; } //hex value is in range User user = DatabaseAccess.Instance.Users.Find(u => u.Id == Context.Message.Author.Id); user.EmbedColor = result; EmbedBuilder embed = new EmbedBuilder() .WithTitle("Custom embed color changed successfully") .WithFooter(Sally.NET.DataAccess.File.FileAccess.GENERIC_FOOTER, Sally.NET.DataAccess.File.FileAccess.GENERIC_THUMBNAIL_URL) .AddField("Previous color name", oldColorName) .AddField("Previous color hexcode", previousColor) .AddField("New color name", newColorName) .AddField("New color hexcode", color) .AddField("All color names are provided by colornames.org", "https://colornames.org") .WithDescription("New color preview on the left side") .WithColor(new Discord.Color((uint)Convert.ToInt32(color, 16))); await Context.Message.Channel.SendMessageAsync(embed : embed.Build()); } else { await Context.Message.Channel.SendMessageAsync("wrong hex value"); } } else { //error await Context.Message.Channel.SendMessageAsync("Something went wrong"); } }
public HomeController() { _request = new ApiRequestService(); _appDbContext = new AppDbContext(); }