Esempio n. 1
0
        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);
        }
        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());
        }
        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 Agreement FindById(string id)
 {
     try {
         return(AgreementORM.GetById(id));
     } catch (Exception e) {
         Logging.LogError("Missing");
         throw e;
     }
 }
Esempio n. 5
0
        public async Task <List <IEProfile> > SearchByName(bool female, string username, int maxProfiles = 50)
        {
            List <IEProfile> resultList = new List <IEProfile>();

            List <KeyValuePair <string, string> > rawContent = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("UserName", username),
                new KeyValuePair <string, string>("search_submit", "1")
            };
            var content = new FormUrlEncodedContent(rawContent);

            int currentPage = 1;

            do
            {
                var reply = await _httpClient.PostAsync(NAMESEARCH_URL + currentPage, content).ConfigureAwait(false);

                if (reply.StatusCode == HttpStatusCode.OK)
                {
                    var replyPage = await reply.Content.ReadAsStringAsync();

                    HtmlDocument htmlDoc = new HtmlDocument();
                    htmlDoc.LoadHtml(replyPage);

                    try
                    {
                        ParseResults(htmlDoc, resultList, female, maxProfiles);
                    } catch (Exception e) {
                        _logger.LogError("SearchByName: Failed to parse results correctly" + e.Message);
                        _logger.LogError(e.StackTrace);
                    }
                    var nextPage = htmlDoc.DocumentNode.Descendants("a").Where(x => x.Attributes.Contains("title") && x.Attributes["title"].Value == "next");
                    if ((nextPage == null) || (nextPage.Any() == false))
                    {
                        maxProfiles = -1;                                               // Force an end as we can't find next button...
                    }
                    else
                    {
                        // We have found the next button....incremenet our page
                        currentPage++;
                    }
                }
                else
                {
                    _logger.LogError("Unexpected status code during search returned " + reply.StatusCode);
                    maxProfiles = -1;
                }
            } while (resultList.Count() < maxProfiles);

            return(resultList);
        }
Esempio n. 6
0
        public void CheckIfOpAndTryToGetOpIfNotLoop()
        {
            while (true)
            {
                try
                {
                    CheckIfOpAndTryToGetOpIfNotOnce();

                    Thread.Sleep(_sleepTimeBetweenChecks);
                }
                catch (Exception ex)
                {
                    _logging.LogError("TopicBot", "TopicBot->CheckIfOpAndTryToGetOpIfNotLoop:" + ex.Message + " -- " + ex.StackTrace + (ex.InnerException != null ? " Inner: " + ex.Message + " -- " + ex.StackTrace : string.Empty));
                }
            }
        }
Esempio n. 7
0
        public static void Run()
        {
            ILogging logging = null;

            while (true)
            {
                try
                {
                    Action <SimpleInjector.Container>[] botSpecificRegistrations = new Action <SimpleInjector.Container>[]
                    {
                        (simpleInjectorContainer) => simpleInjectorContainer.Register <IBehaviour, TopicBotBehaviour.Behaviour>()        // damit legen wir fest, dass sich unser Bot wie ein TopicBot verhalten soll
                    };

                    var container = DIMappings.Container.Init(botSpecificRegistrations);

                    var client        = container.GetInstance <IMessagingClient>();
                    var configuration = container.GetInstance <IConfiguration>();
                    var behaviour     = container.GetInstance <IBehaviour>();
                    logging = container.GetInstance <ILogging>();

                    RegisterBehaviours(behaviour, client);

                    client.Connect();

                    StartOpGetterThread(client, configuration, logging);

                    client.StartToListen(); // blockierender Aufruf, der dann nur noch Events handled

                    client.Disconnect();    // IRC-Session wurde beendet - hier kommen wir im Normalfall nie an
                }
                catch (Exception ex)
                {
                    logging.LogError("TopicBot", "TopicBot->Run:" + ex.Message + " -- " + ex.StackTrace + (ex.InnerException != null ? " Inner: " + ex.Message + " -- " + ex.StackTrace : string.Empty));
                    Thread.Sleep(300000); // 5 Minuten auf bessere Zeiten warten
                }
            }
        }
        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));
        }
        // Initializes global state.
        // 'webApiSegmentsTreeMeasuresUri' must specify the Web API URI that returns information about the requestable
        // measures from the Segments Tree Node resource.
        // 'exportCultureNames' must specify the names (e.g. "en-US") of the cultures that can be used when
        // exporting data (e.g. CSV data); can be null/empty.  The culture names must be separated by spaces.
        // Throws an exception and logs an error in the event of error.
        public async static void Init(Uri webApiSegmentsTreeMeasuresUri, String exportCultureNames,
            ILogging logging)
        {
            if (webApiSegmentsTreeMeasuresUri == null)
                throw new ArgumentNullException("webApiSegmentsTreeMeasuresUri");


            // Get information about the Segments Tree Node measures.
            // NOTE: the Segments Tree Node measures (as opposed to the Time Series measures) can grow from time
            // to time (from sprint to sprint), so we pull down the latest list whenever the app starts up.
            String measuresXml = String.Empty;
            HttpClient httpClient = null;
            try
            {
                httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
                var response = await httpClient.GetAsync(webApiSegmentsTreeMeasuresUri);
                response.EnsureSuccessStatusCode();
                measuresXml = await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                // Log the error.
                var errorMessage = "Failed to get information about the Segments Tree Node measures from " +
                                   "the Web API.  " + ex.ToString();
                System.Diagnostics.Debug.WriteLine(errorMessage);
                if (logging != null)
                    logging.LogError(errorMessage);

                throw;
            }
            finally
            {
                if (httpClient != null)
                    httpClient.Dispose();
            }


            // Parse the measures info XML, and store the resulting collection in '_segmentsTreeMeasures'.
            try
            {
                var doc = XDocument.Parse(measuresXml);
                XNamespace ns = "http://statpro.com/2012/Revolution";
                _segmentsTreeMeasures = doc.Root
                                           .Element(ns + "measures").Elements(ns + "measure")
                                           .Select(me => new MeasureInfo(me, ns))
                                           .ToList().AsReadOnly();
            }
            catch (Exception ex)
            {
                // Log the error.
                var errorMessage = "Failed to parse the information about the Segments Tree Node measures that " +
                                   "was returned by the Web API.  " + ex.ToString();
                System.Diagnostics.Debug.WriteLine(errorMessage);
                if (logging != null)
                    logging.LogError(errorMessage);

                throw;
            }


            // Derive a separate collection of the named categories into which the Segments Tree Node measures
            // fall.
            _segmentsTreeMeasureCategories = _segmentsTreeMeasures.Select(mi => mi.Category)
                                                                  .Distinct()
                                                                  .OrderBy(c => c)
                                                                  .ToList().AsReadOnly();


            // Set up the collection of export cultures.  Unrecognised culture names are ignored.
            if (String.IsNullOrWhiteSpace(exportCultureNames))
            {
                _exportCultures = new List<CultureInfo>().AsReadOnly();
                return;
            }

            Func<String, CultureInfo> getCultureOrNull = name => 
                { try { return new CultureInfo(name); } catch (CultureNotFoundException) { return null; } };

            _exportCultures = exportCultureNames.Split(' ')
                                                .Select(name => getCultureOrNull(name))
                                                .Where(ci => ci != null)
                                                .OrderBy(ci => ci.DisplayName)
                                                .ToList().AsReadOnly();
        }
Esempio n. 10
0
 public void errorMessage(string message)
 {
     _logService.LogError(message);
 }
Esempio n. 11
0
        private void LogError(ILogging log, string message)
        {
            log.LogError(message);

            Response.Write(message);
            Response.StatusCode = 404;
            Response.StatusDescription = message;
        }
Esempio n. 12
0
        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));
            }
        }