internal async Task <RegisterResult> Register(string emailAdress, string password) { if (CredentialUtil.GetCredential("BalanceKeeper.Desktop" + emailAdress) != null) { return(await Task <RegisterResult> .FromResult(new RegisterResult() { Succes = false, IsError = true, ErrorType = RegisterErrorType.ModelError, Errors = new List <IdentityError>() { new IdentityError() { Code = "UE", Description = "Gebruikersnaam bestaat al" } } })); } CredentialUtil.SetCredentials("BalanceKeeper.Desktop" + emailAdress, emailAdress, password, CredentialManagement.PersistanceType.LocalComputer); return(await Task <RegisterResult> .FromResult(new RegisterResult() { Succes = true })); }
private static async Task CreateSession() { var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false }; _downloadProgressTrackingHandler = new ProgressMessageHandler(httpClientHandler); SessionClient = new HttpClient(_downloadProgressTrackingHandler) { BaseAddress = new Uri("http://courses.finki.ukim.mk/"), }; SessionClient.DefaultRequestHeaders.UserAgent.ParseAdd("CoursesDownloader-C# Console App"); HttpResponseMessage login = null; while (true) { Console.WriteLine("Establishing connection with courses"); try { login = await SessionClient.GetAsyncHttp("http://courses.finki.ukim.mk/login/index.php"); if (!login.IsSuccessStatusCode) { throw new HttpRequestException(); } } catch (HttpRequestException) { Console.WriteLine("Connection cannot be established"); var shouldRetry = MenuChooseItem.AskYesNoQuestion("Do you want to try again? [Y/N] ", Console.Clear, () => { Environment.Exit(0); }); if (shouldRetry) // onYes { continue; } } break; } Console.WriteLine("Preparing CAS login"); var text = await login.Content.ReadAsStringAsync(); login.Dispose(); var doc = new HtmlDocument(); doc.LoadHtml(text); var hiddenInput = doc.DocumentNode.SelectNodes("//form//input[@type=\"hidden\"]"); var loginData = new Dictionary <string, string>(); foreach (var x in hiddenInput) { loginData[x.Attributes.First(t => t.Name == "name").Value] = x.Attributes.First(t => t.Name == "value").Value; } EnterCredentialsAgain: var(username, password) = CredentialUtil.GetCredential(CASTarget); while (username.IsNullOrEmpty() || password.IsNullOrEmpty()) { username = ConsoleUtils.ReadLine("Please enter your CAS username >>> ", ConsoleIOType.Question); password = ConsoleUtils.ReadLine("Please enter your CAS password >>> ", ConsoleIOType.Question, true); CredentialUtil.SetCredentials(CASTarget, username, password); } loginData["username"] = username; loginData["password"] = password; using (var loginDataContent = new FormUrlEncodedContent(loginData.ToArray())) { Console.WriteLine("Logging into CAS"); using (var response = await SessionClient.PostAsyncHttp(login.RequestMessage.RequestUri, loginDataContent)) { // if redirected to CAS, wrong password or username if (response.RequestMessage.RequestUri.Host == new Uri(CASTarget).Host) { ConsoleUtils.WriteLine("The username or password you entered is incorrect. Please try again"); CredentialUtil.RemoveCredentials(CASTarget); // remove incorrect credentials goto EnterCredentialsAgain; } FindSessKey(await response.Content.ReadAsStringAsync()); } } LoginTime = DateTime.Now; }
static void Main(string[] args) { // Add support for JSON Config File IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("AppSettings.json", optional: false, reloadOnChange: true) .Build(); // Read hostname from credential manager first var hostnameTarget = config.GetSection("CredentialManager:Targets:MetasysServer").Value; // Hostname is stored in the Credential Manager using password field var secureHostname = CredentialUtil.GetCredential(hostnameTarget); MetasysClient metasysClient = new MetasysClient(CredentialUtil.convertToUnSecureString(secureHostname.Password)); // Retrieve Metasys Credentials to login var credTarget = config.GetSection("CredentialManager:Targets:MetasysCredentials").Value; // Use TryLogin overload that accepts Credential Manager Target metasysClient.TryLogin(credTarget); // Forecast container target is securely stored in Credential manager var containerTarget = config.GetSection("CredentialManager:Targets:ForecastContainer").Value; var secureContainer = CredentialUtil.GetCredential(containerTarget); // Get parent object of Weather Forecast to retrieve related children (securely stored in Credential Manager) Guid parentObjectId = metasysClient.GetObjectIdentifier(CredentialUtil.convertToUnSecureString(secureContainer.Password)); IEnumerable <MetasysObject> weatherForecast = metasysClient.GetObjects(parentObjectId, 1); // Retrieve latitude and longitude to get weather forecast MetasysObject latitudePoint = weatherForecast.FindByName("Latitude"); MetasysObject longitudePoint = weatherForecast.FindByName("Longitude"); double latitude = metasysClient.ReadProperty(latitudePoint.Id, "presentValue").NumericValue; double longitude = metasysClient.ReadProperty(longitudePoint.Id, "presentValue").NumericValue; // Forecast API key is securely stored in Credential manager var apiKeyTarget = config.GetSection("CredentialManager:Targets:OpenWeather").Value; var secureApiKey = CredentialUtil.GetCredential(apiKeyTarget); // Get Next Five Days forecast every 3 hours OpenWeatherMapClient weatherMapclient = new OpenWeatherMapClient(CredentialUtil.convertToUnSecureString(secureApiKey.Password)); ForecastResult forecastResult = weatherMapclient.GetForecast(latitude, longitude).GetAwaiter().GetResult(); // Get the closest forecast to be written Forecast forecast = forecastResult.list.First(); // Read Metasys points to write the response back MetasysObject Day = weatherForecast.FindByName("Day"); MetasysObject Month = weatherForecast.FindByName("Month"); MetasysObject Year = weatherForecast.FindByName("Year"); MetasysObject Hour = weatherForecast.FindByName("Hour"); MetasysObject Minute = weatherForecast.FindByName("Minute"); MetasysObject Temperature = weatherForecast.FindByName("Temperature"); MetasysObject Humidity = weatherForecast.FindByName("Humidity"); MetasysObject Rain = weatherForecast.FindByName("Rain"); MetasysObject Snow = weatherForecast.FindByName("Snow"); // Use commands to write the results string adjustCommand = "Adjust"; var date = OpenWeatherMapClient.UnixTimeStampToDateTime(forecast.dt); metasysClient.SendCommand(Day.Id, adjustCommand, new List <object> { date.Day }); metasysClient.SendCommand(Month.Id, adjustCommand, new List <object> { date.Month }); metasysClient.SendCommand(Year.Id, adjustCommand, new List <object> { date.Year }); metasysClient.SendCommand(Hour.Id, adjustCommand, new List <object> { date.Hour }); metasysClient.SendCommand(Minute.Id, adjustCommand, new List <object> { date.Minute }); metasysClient.SendCommand(Temperature.Id, adjustCommand, new List <object> { forecast.main.temp }); metasysClient.SendCommand(Humidity.Id, adjustCommand, new List <object> { forecast.main.humidity }); if (forecast.rain != null) { metasysClient.SendCommand(Rain.Id, adjustCommand, new List <object> { forecast.rain.ThreeHours }); } else { // Reset values in case there is no rain metasysClient.SendCommand(Rain.Id, adjustCommand, new List <object> { 0 }); } if (forecast.snow != null) { metasysClient.SendCommand(Snow.Id, adjustCommand, new List <object> { forecast.snow.ThreeHours }); } else { // Reset values in case there is no snow metasysClient.SendCommand(Rain.Id, adjustCommand, new List <object> { 0 }); } }