private async Task <TimeSpan> LoadFromExternalDatabase() { var table = await _externalDb.FetchAllMembers(Settings.UserName); _logger.LogInfo("Found " + table.Count + " members in databse"); foreach (var member in table) { Members.Add(member.ProfileId, member); switch (member.Status) { case IEMember.MEMBER_NEW: NewItems.Add(member); break; case IEMember.MEMBER_REJECTED: RejectedItems.Add(member); break; default: ActiveItems.Add(member); break; } } NewItems.Sort(); RejectedItems.Sort(); ActiveItems.Sort(); TimeScheduler.GetTimeScheduler().AddTask(DS_TASK_NAME, TimeSpan.FromSeconds(INITIAL_DELAY), () => OnTimedEvent()); return(TimeScheduler.STOP_TIMER); // This stops us being re-scheduled }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogging logg) { _log = logg; _log.LogInfo("Using authorization service."); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseAuthentication(); app.UseCors("CorsPolicy"); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("../swagger/v1/swagger.json", "EHospital"); }); }
public IEnumerable <WeatherForecast> Get() { _logging.LogDebug($"[{typeof(WeatherForecastController).FullName} - {MethodBase.GetCurrentMethod().Name}] - (Se realiza loggeo " + $"satisfactoriamente)"); _logging.LogError($"[{typeof(WeatherForecastController).FullName} - {MethodBase.GetCurrentMethod().Name}] - (Se realiza loggeo " + $"satisfactoriamente)"); _logging.LogFatal($"[{typeof(WeatherForecastController).FullName} - {MethodBase.GetCurrentMethod().Name}] - (Se realiza loggeo " + $"satisfactoriamente)"); _logging.LogInfo($"[{typeof(WeatherForecastController).FullName} - {MethodBase.GetCurrentMethod().Name}] - (Se realiza loggeo " + $"satisfactoriamente)"); _logging.LogWarn($"[{typeof(WeatherForecastController).FullName} - {MethodBase.GetCurrentMethod().Name}] - (Se realiza loggeo " + $"satisfactoriamente)"); var rng = new Random(); return(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray()); }
private void DeleteFilesInEssence(Essence essence) { if (!Directory.Exists(essence.Path)) { Logging.LogWarning(essence.Path + " already deleted."); return; } var sb = new StringBuilder("Deleting Tempory files and directory:\n"); foreach (var file in essence.Files) { var absFineName = Path.Combine(essence.Path, file.Value); if (File.Exists(absFineName)) { File.Delete(absFineName); sb.AppendLine(absFineName); } } if (!Directory.EnumerateFiles(essence.Path).Any()) //temp dir is empty, safe to delete { Directory.Delete(essence.Path); sb.AppendLine(essence.Path); } Logging.LogInfo(sb.ToString()); }
public async Task <IEMember> ModifyMember(string myUsername, IEMember member) { ExternalDBCommand cmd = new ExternalDBCommand(); cmd.requestingUsername = myUsername; cmd.member = member; var dateTimeConverter = new IsoDateTimeConverter(); string json = JsonConvert.SerializeObject(cmd, dateTimeConverter); var httpClient = new HttpClient(); HttpContent contents = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage resp = await httpClient.PostAsync(MODIFY_MEMBER_URL, contents); if ((resp != null) && (resp.IsSuccessStatusCode)) { // // We need to parse the results - somehow convert back into an array of IEMembers.... // string jsonReply = await resp.Content.ReadAsStringAsync(); _logger.LogInfo("ModifyMember reply= " + jsonReply); try { IEMember replyMember = JsonConvert.DeserializeObject <IEMember>(jsonReply, dateTimeConverter); return(replyMember); } catch (Exception e) { _logger.LogError("ModifyMember error=" + e.Message); _logger.LogError("Stack=" + e.StackTrace); } } return(null); }
private async Task <TimeSpan> LoadFromExternalDatabase() { ActiveContacts.Clear(); var table = await _externalDb.FetchAllContacts(); _logger.LogInfo("Found " + table.Count + " contacts in databse"); foreach (var contact in table) { ActiveContacts.Add(contact); } ActiveContacts.Sort(); //TimeScheduler.GetTimeScheduler().AddTask(DS_TASK_NAME, TimeSpan.FromSeconds(INITIAL_DELAY), () => OnTimedEvent()); return(TimeScheduler.STOP_TIMER); // This stops us being re-scheduled }
public JobStatus Order(Order order) { try { order.Validate(_mediaInfoFacade, _timeProvider); } catch { _logging.LogWarning("Failed to validate order", order); throw; } var job = Mapper.Map <Job>(order); if (order.Format == StateFormat.custom) { _logging.LogWarning($"Custom format received : {order.CustomFormat}", job.Urn); } _jobRepository.Add(job); _logging.LogInfo($"Received valid order.", job); return(Mapper.Map <JobStatus>(job)); }
private IEDataSource() { _logger = DependencyService.Get <ILogging>(); RejectedItems = new ObservableCollection <IEMember>(); ActiveItems = new ObservableCollection <IEMember>(); NewItems = new ObservableCollection <IEMember>(); SearchResults = new ObservableCollection <IEMember>(); Members = new Dictionary <string, IEMember>(); //string dbPath = DependencyService.Get<IFileHelper>().GetLocalFilePath("iedb.db3"); //_database = new SQLiteAsyncConnection(dbPath); //_database.CreateTableAsync<IEMember>( CreateFlags.None ).Wait(); _externalDb = new ExternalDBService(); _logger.LogInfo("Reading database table for existing members"); /* * var table = _database.Table<IEMember>().ToListAsync(); * table.Wait(); */ /* * var table = _externalDb.FetchAllMembers(Settings.UserName); * table.Wait(); * * _logger.LogInfo("Found " + table.Result.Count + " members in databse"); * foreach( var member in table.Result) * { * Members.Add(member.ProfileId, member); * switch(member.Status) * { * case IEMember.MEMBER_NEW: * NewItems.Add(member); * break; * case IEMember.MEMBER_REJECTED: * RejectedItems.Add(member); * break; * default: * ActiveItems.Add(member); * break; * } * } * * NewItems.Sort(); * RejectedItems.Sort(); * ActiveItems.Sort(); */ _session = new IESession(_logger); Running = false; }
public async Task <IActionResult> ChangeRole([FromBody] Roles roles) { string role = await _appDbContext.GetRoleByToken(Request.Headers["Authorization"]); if (role.ToLower() == "admin") { _log.LogInfo("Get new role."); if (!ModelState.IsValid) { _log.LogError("Incorrect input."); return(BadRequest(ModelState)); } if (await _appDbContext.ChangeRole(roles) == null) { _log.LogError("Incorrect role."); return(BadRequest(Errors.AddErrorToModelState("rolesFailure", "Invalid role.", ModelState))); } _log.LogInfo("Changing role."); await _appDbContext.ChangeRole(roles); string roleChangeText; using (StreamReader streamreader = new StreamReader(@"..\EHospital.Authorization.WebAPI\Letters\roleChange.txt")) { roleChangeText = streamreader.ReadToEnd(); } string email = await _appDbContext.GetEmail(roles); await emailSender.SendEmail(email, "Free access", roleChangeText); return(Ok()); } return(BadRequest(role)); }
public async Task <IActionResult> LogIn(CredentialsViewModel credentials) { _log.LogInfo("Set credentials for authorization."); if (!ModelState.IsValid) { _log.LogError("Incorrect format of input."); return(BadRequest(ModelState)); } _authorizationManager = new AuthorizationManager(_appDbContext); _log.LogInfo("Check the user."); Task <System.Security.Claims.ClaimsIdentity> identity = _authorizationManager.GetClaimsIdentity(credentials.UserLogin, credentials.Password); if (identity.Result == null) { _log.LogError("Invalid username or password."); return(BadRequest(Errors.AddErrorToModelState("loginFailure", "Invalid username or password.", ModelState))); } if (await _appDbContext.IsConfirmed(credentials.UserLogin)) { string jwt = await _appDbContext.IsAuthorized(credentials.UserLogin); if (jwt == null) { _log.LogInfo("Set an access token."); jwt = await GetToken(credentials.UserLogin); } else { _log.LogInfo("User is already authorized. Get an access token from current session."); } _log.LogInfo("Successful authorize."); var result = new { token = jwt }; return(Ok(result)); } else { return(BadRequest("Please, first confirm you email, then login.")); } }
public async Task <bool> GetProfile(IEMember member) { var reply = await _httpClient.GetAsync(PROFILE_URL + member.ProfileId); if (reply.StatusCode == HttpStatusCode.OK) { var replyPage = await reply.Content.ReadAsStringAsync(); HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(replyPage); var tables = htmlDoc.DocumentNode.Descendants("table").ToList(); // // Table 1 holds info including 'Race', 'Location' and 'Marital Status' // if ((tables != null) && (tables.Count() > 5)) { var tds = tables[1].Descendants("td").ToList(); if ((tds != null) && (tds.Count() > 16)) { int fieldOffset = 14; if (tds.Count() > 19) { // This means we have a 'Message History' shown as well...we need to step over it... fieldOffset += 2; // Message History adds 2 new fields before the ones we want. } _logger.LogInfo("Found " + tds.Count() + " tds"); var race = tds[fieldOffset++].InnerText.Split(':')[1].Trim(); // var loc = tds[fieldOffset++].InnerText.Split(':')[1].Trim();; // Location (often includes town) var mStatus = tds[fieldOffset++].InnerText.Split(':')[1].Trim();; // Marital Status _logger.LogInfo("Race = " + race); _logger.LogInfo("Location = " + loc); _logger.LogInfo("Marital Status = " + mStatus); member.Race = race; member.Region = loc; member.MaritalStatus = mStatus; } // // Table 3 holds 'Personal Info' such as Religion, Eye Colour, Hair colour etc // tds = tables[3].Descendants("td").ToList(); if ((tds != null) && (tds.Count() > 22)) { var religion = tds[2].InnerText.Trim(); var eyeColour = tds[4].InnerText.Trim(); var drinking = tds[6].InnerText.Trim(); var hairColour = tds[8].InnerText.Trim(); var smoking = tds[10].InnerText.Trim(); var build = tds[12].InnerText.Trim(); var height = tds[14].InnerText.Trim(); var education = tds[16].InnerText.Trim(); var job = tds[18].InnerText.Trim(); var interests = tds[22].InnerText.Trim(); var subInterests = interests.Split(','); interests = ""; foreach (var sub in subInterests) { if (interests.Length > 0) { interests += ","; } interests += sub.Trim(); } _logger.LogInfo("religon = " + religion); _logger.LogInfo("eyeColour = " + eyeColour); _logger.LogInfo("drinking = " + drinking); _logger.LogInfo("hairColour = " + hairColour); _logger.LogInfo("smoking = " + smoking); _logger.LogInfo("build = " + build); _logger.LogInfo("height = " + height); _logger.LogInfo("education = " + education); _logger.LogInfo("job = " + job); _logger.LogInfo("interests = " + interests); member.Religion = religion; member.EyeColour = eyeColour; member.Drinking = drinking; member.Smoking = smoking; member.HairColour = hairColour; member.Build = build; member.Height = height; member.Education = education; member.Occupation = job; member.Interests = interests; } // // Table 4 is the 'Ideal partner' info. // tds = tables[4].Descendants("td").ToList(); if ((tds != null) && (tds.Count() > 3)) { var lookingFor = tds[1].InnerText.Trim(); var ideal = tds[2].InnerText.Trim(); var relationshipType = tds[3].InnerText.Trim(); _logger.LogInfo("orig-relationshipType = '" + relationshipType + "'"); const string RELATION_TYPE = "Type of Relationship"; if (relationshipType.StartsWith(RELATION_TYPE, StringComparison.CurrentCulture)) { relationshipType = relationshipType.Substring(RELATION_TYPE.Length).Trim(); } var relationShipSub = relationshipType.Split(','); if (relationShipSub.Count() > 0) { relationshipType = ""; foreach (var sub in relationShipSub) { if (relationshipType.Length > 0) { relationshipType += ","; } relationshipType += sub.Trim(); } } const string LOOKING_FOR = "I'm looking for someone who is:"; if (lookingFor.StartsWith(LOOKING_FOR, StringComparison.CurrentCulture)) { lookingFor = lookingFor.Substring(LOOKING_FOR.Length).Trim(); } _logger.LogInfo("lookingFor = " + lookingFor); _logger.LogInfo("ideal = " + ideal); _logger.LogInfo("relationshipType = " + relationshipType); member.LookingFor = lookingFor; member.IdealPartner = ideal; member.RelationshipType = relationshipType; } // // Table 5 is the About me info // tds = tables[5].Descendants("td").ToList(); if ((tds != null) && (tds.Count() > 2)) { var about = tds[1].InnerText.Trim(); _logger.LogInfo("about = " + about); member.About = about; } member.FetchedExtraData = DateTime.Now; } return(true); } return(false); }
public void Pulse() { lock (_jobRepository) { #region semaphore string currentOwner; var firstCallAfterSemaphore = _firstPulse || !_wasMaster; if (!_semaphoreRepository.Get(nameof(Executor), Utilities.GetCallerId(), out currentOwner)) { if (_firstPulse) { _logging.LogInfo($"Did not get semaphore, current owner : {currentOwner}. Will stand by as slave."); _firstPulse = false; } else if (_wasMaster) { _logging.LogWarning($"Lost semaphore to : {currentOwner}. Will stand by as slave."); _wasMaster = false; } return; } if (_firstPulse) { _logging.LogInfo($"Got semaphore, as : {currentOwner}. Will work as master."); _firstPulse = false; } else if (!_wasMaster) { _logging.LogInfo($"Slave woken, {currentOwner} is now owner. Will work as master."); foreach (var plugin in _plugins) { plugin.Reset(); } } _wasMaster = true; #endregion #region command foreach (var command in _commandRepository.GetAll()) { // ReSharper disable once SwitchStatementMissingSomeCases switch (command.Type) { case CommandType.Cancel: CancelJob(command.Urn, command.Username); break; default: _logging.LogWarning($"Command state {command.Type} is not implemented.", command.Urn); break; } _commandRepository.Remove(command); } #endregion #region planner // TODO: modify existing plans ? :hamburger: :+1: if (!firstCallAfterSemaphore) // skip first pulse to reassign in-progress tasks to plugins. { _planner.Calculate(); } #endregion #region jobs, task and plugins foreach (var job in _jobRepository.ActiveJobs().ToList()) { //TODO: Add support for cancel var plan = job.Plan; startOfJobLoop: var executionTask = plan.GetCurrentTask(); var targetPlugin = _plugins.First(p => p.Urn == executionTask.PluginUrn); switch (executionTask.State) { case ExecutionState.Queued: if (targetPlugin.Busy) { // TODO: log planning warning break; } _logging.LogDebug($"Task {executionTask.Urn} assigned to {targetPlugin.Urn}.", job.Urn); targetPlugin.Assign(executionTask); goto case ExecutionState.Running; case ExecutionState.Running: targetPlugin.Pulse(executionTask); if (executionTask.State == ExecutionState.Done) { goto case ExecutionState.Done; } if (executionTask.State == ExecutionState.Failed) { goto case ExecutionState.Failed; } plan.Tasks[plan.ActiveTaskIndex.Value] = executionTask; break; case ExecutionState.Done: _logging.LogDebug($"Task {executionTask.Urn} done, released from {targetPlugin.Urn}.", job.Urn); targetPlugin.Release(executionTask); plan.Tasks[plan.ActiveTaskIndex.Value] = executionTask; plan.MoveToNextTask(); if (plan.ActiveTaskIndex.HasValue) // has more tasks { _jobRepository.Update(job); // save and... goto startOfJobLoop; //start next task at once } break; case ExecutionState.Failed: if (targetPlugin.CanRetry && executionTask.NumberOfRetries < targetPlugin.RetryMax) { targetPlugin.Retry(executionTask); } break; default: throw new ArgumentOutOfRangeException(); } if (plan.GetState() == ExecutionState.Done) { job.Destination = plan.GetCurrentEssence(); job.EndTime = _timeProvider.GetUtcNow(); _logging.LogInfo("Job done", job.Urn); } if (plan.GetState() == ExecutionState.Failed) { _logging.LogWarning("Job failed", job.Urn); } if ((plan.GetState() == ExecutionState.Failed || plan.GetState() == ExecutionState.Done) && !string.IsNullOrEmpty(job.CallbackUrl)) { MakeCallback(job); } _jobRepository.Update(job); } } #endregion }
private void ExecutePluginName(DictionaryNVR scopeData, SPSite site, ILogging log) { try { // TODO - config could be filtered based on plugin name and referrer // now it's up to the plugin itself to load what it needs PluginHost.Init(site); string pluginName = Request["PluginName"]; IPlugin plugin = ExecutePagePluginHost.Get(site, pluginName); if (plugin == null) { log.LogError(string.Format("ExecuteScriptPlugin named {0} was not found in loaded plugins, skipping execution", pluginName)); return; } try { using (new SPMonitoredScope("Executing ExecuteScriptPlugin " + pluginName)) { var res = plugin.Execute(null, scopeData); log.LogInfo("Executed " + pluginName + " with result:\n", res ?? "NULL"); } } catch (Exception e) { log.LogError(string.Format("ExecuteScriptPlugin named {0} has thrown {1}", pluginName, e), e.InnerException, e.StackTrace, e.Source); } } catch (Exception exc) { log.LogException("Exception in Execute.aspx, Script " + Request["ScriptPath"], exc); Response.Write("Exception in script\n" + exc); Response.StatusCode = 500; Response.StatusDescription = "Exception in script"; return; } }
public async Task <IActionResult> Registration(UsersData userData, Secrets userSecrets) { _log.LogInfo("Get userData for registration."); if (!ModelState.IsValid) { _log.LogError("Incorrect input."); return(BadRequest(ModelState)); } _log.LogInfo("Check is password safe."); try { if (PasswordManager.ValidatePassword(userSecrets.Password)) { _log.LogInfo("Safety of password is good."); _log.LogInfo("Check is it a new user."); if (!await _appDbContext.IsUserExist(userData.Email)) { using (SqlConnection connection = new SqlConnection("Data Source=JULIKROP\\SQLEXPRESS;Initial Catalog=EHospital;Integrated Security=True")) { connection.Open(); using (var transaction = connection.BeginTransaction()) { try { _log.LogInfo("Add default role."); await _appDbContext.AddRoles(new Roles { Id = (int)UsersRoles.NoRole, Title = UsersRoles.NoRole.ToString() }); _log.LogInfo("Add login."); await _appDbContext.AddLogin(new Logins { Login = userData.Email, RegisterKey = emailSender.GenerateKey(), Status = "New" }); _log.LogInfo("Add user's userData"); await _appDbContext.AddUserData(new UsersData { FirstName = userData.FirstName, LastName = userData.LastName, BirthDate = userData.BirthDate, PhoneNumber = userData.PhoneNumber, Country = userData.Country, City = userData.City, Adress = userData.Adress, Gender = userData.Gender, Email = userData.Email }); _log.LogInfo("Add password."); await _appDbContext.AddSecrets(new Secrets { Password = userSecrets.Password }); transaction.Commit(); } catch (Exception ex) { _log.LogError("Account is not created." + ex.Message); transaction.Rollback(); return(new BadRequestObjectResult("Creation of account was failed." + ex.Message)); } finally { transaction.Dispose(); } } } } else { _log.LogError("Account is not created."); return(new BadRequestObjectResult("Creation of account was failed.")); } string greetingText; using (StreamReader streamreader = new StreamReader(@"..\EHospital.Authorization.WebAPI\Letters\greetings.txt")) { greetingText = streamreader.ReadToEnd(); } _log.LogInfo("Send greetings."); await emailSender.SendEmail(userData.Email, "Welcome to EHospital", greetingText); int id = await _appDbContext.FindByLogin(userData.Email); string key = await _appDbContext.GetRegisterKey(userData.Email); var callbackUrl = $"{Request.Scheme}://{Request.Host}/authorization/api/Registration/Confirmation?userId={id}&token={key}"; _log.LogInfo("Send confirmation"); await emailSender.SendEmail(userData.Email, "Confirm the registration", $"Confirm the registration by clicking the following link: <a href='{callbackUrl}'>confirm</a>"); _log.LogInfo("Account created"); Task.WaitAll(); return(new OkObjectResult("Account created. We sent letter on your email.Confirm it. If you don`t see the letter, please, check the spam.")); } _log.LogError("Account is not created."); return(new BadRequestObjectResult("Creation of account was failed.")); } catch (ArgumentException ex) { _log.LogError("Account is not created." + ex.Message); return(new BadRequestObjectResult("Creation of account was failed." + ex.Message)); } }