Exemplo n.º 1
0
        public GossipController(IPublisher publisher, IPublisher networkSendQueue, TimeSpan gossipTimeout, Func <X509Certificate, X509Chain, SslPolicyErrors, ValueTuple <bool, string> > serverCertValidator, X509Certificate clientCertificate)
            : base(publisher)
        {
            _networkSendQueue = networkSendQueue;
            _gossipTimeout    = gossipTimeout;

            var socketsHttpHandler = new SocketsHttpHandler {
                SslOptions =
                {
                    RemoteCertificateValidationCallback = (sender,                         certificate, chain, errors) => {
                        var(isValid, error)             = serverCertValidator(certificate, chain,       errors);
                        if (!isValid && error != null)
                        {
                            Log.Error("Server certificate validation error: {e}", error);
                        }
                        return(isValid);
                    },
                    ClientCertificates                  = new X509CertificateCollection()
                }
            };

            if (clientCertificate != null)
            {
                socketsHttpHandler.SslOptions.ClientCertificates.Add(clientCertificate);
            }

            _client = new HttpAsyncClient(_gossipTimeout, socketsHttpHandler);
        }
Exemplo n.º 2
0
        public LoadOperationsFromFile(IConfigurationSection cfg, bool enableWatcher)
        {
            mazakPath = cfg.GetValue <string>("Load CSV Path");
            if (string.IsNullOrEmpty(mazakPath))
            {
                mazakPath = "c:\\mazak\\FMS\\LDS\\";
            }

            if (!Directory.Exists(mazakPath))
            {
                mazakPath = "c:\\mazak\\LDS\\";

                if (!Directory.Exists(mazakPath))
                {
                    Log.Error("Unable to determine the path to the mazak load CSV files.  Please add/update a setting" +
                              " called 'Load CSV Path' in config file");
                    return;
                }
            }

            if (enableWatcher)
            {
                _watcher = new FileSystemWatcher(mazakPath, "*.csv");
                //_watcher.Created += watcher_Changed;
                _watcher.Changed            += watcher_Changed;
                _watcher.EnableRaisingEvents = true;
            }
        }
Exemplo n.º 3
0
        public ActionResult <ResultModel> List()
        {
            //api/Customers
            try
            {
                _logger.Debug("取得客戶列表");

                //List相當於mvc的index  api/Customers
                var result = new ResultModel
                {
                    Data      = _ICustomerService.GetAll().Result,
                    IsSuccess = true
                };

                return(Ok(result));
            }
            catch (Exception e)
            {
                _logger.Error(e, "");
                return(BadRequest(new ResultModel {
                    IsSuccess = false, Message = ""
                }));

                throw;
            }
        }
Exemplo n.º 4
0
        private Task NotifyNewAssigneeAsync(Workflow wf, string userId, int emailTemplateId)
        {
            var u = Cacher.FindOrCreateValWithSimpleKey(
                userId,
                () => DB.AspNetUsers.Select(z => new { UserId = z.Id, UserType = z.UserType, UserName = z.UserName, Email = z.Email }).FirstOrDefault(z => z.UserId == userId),
                UloHelpers.MediumCacheTimeout);

            if (u == null)
            {
                Log.Error($"Cannot find {userId}", userId);
            }
            else if (u.UserType == AspNetUser.UserTypes.Person && RegexHelpers.Common.EmailAddress.IsMatch(u.Email))
            {
                var emailTemplate = PortalHelpers.GetEmailTemplate(emailTemplateId);
                if (emailTemplate == null)
                {
                    Log.Error($"Cannot find emailTemplateId={emailTemplateId}");
                }
                else
                {
                    var emailModel = new EmailViewModel(u.UserName)
                    {
                        PDN        = wf.UnliquidatedObligation.PegasysDocumentNumber,
                        WorkflowId = wf.WorkflowId,
                        UloId      = wf.UnliquidatedObligation.UloId
                    };
                    BackgroundJobClient.Enqueue <IBackgroundTasks>(bt => bt.Email(u.Email, emailTemplate.EmailSubject, emailTemplate.EmailBody, emailTemplate.EmailHtmlBody, emailModel));
                }
            }
            else
            {
                Log.Information($"Will not send email to {u}");
            }
            return(Task.CompletedTask);
        }
Exemplo n.º 5
0
        public async Task Handle(InitiativeCreatedDomainEvent notification, CancellationToken cancellationToken)
        {
            _logger.Debug("New Initiative Created, will post message to service bus");
            try
            {
                var initiative = await _initiativeRepository.GetInitiativeAsync(notification.InitiativeId);

                if (initiative == null)
                {
                    _logger.Error("Received new initiave event but couldn't get initiative with id {InitiativeUid}", notification.InitiativeId);
                    throw new Exception($"Received new initiave event but couldn't get initiative with id {notification.InitiativeId}");
                }
                else
                {
                    _logger.Information("Posting NewInitiativeCreated event to service bus for Initiative {InitiativeId}", initiative.Id);
                }

                await _initiativeMessageSender.SendInitiativeCreatedAsync(new InitiativeCreatedEventArgs()
                {
                    Initiative            = initiative,
                    Owner                 = _currentUserAccessor.User,
                    SkipEmailNotification = notification.SkipEmailNotification
                });
            }
            catch (Exception err)
            {
                _logger.Error(err, "Error posting Initative Created event to Service Bus: {ErrorMessage}", err.Message);
            }
        }
        private async Task <IPStackResponseModel> GetIPInfo(string remoteIp)
        {
            return(await _memoryCache.GetOrCreateAsync(remoteIp, async entry =>
            {
                entry.SlidingExpiration = TimeSpan.FromMinutes(1);

                _logger.Information("IP country unknown and not present in cache, performing external lookup...");

                var ipStackBaseUrl =
                    $"{_ipStackConfig.Value.BaseUrl}/{remoteIp}?access_key={_ipStackConfig.Value.API_Key}";

                using (var client = new HttpClient())
                {
                    var response = await client.GetAsync(ipStackBaseUrl);
                    if (response.IsSuccessStatusCode)
                    {
                        return await response.Content.ReadAsAsync <IPStackResponseModel>();
                    }

                    _logger.Error("Got error from IPStack: {HttpStatus}/{ErrorMessage}", response.StatusCode,
                                  response.ReasonPhrase);
                    return null;
                }
            }));
        }
        private void TryReadLastPollTime()
        {
            bool success = false;

            if (Directory.Exists(_options.TempDirectory))
            {
                // get the latest file starting with "RemedyCheckerLog"
                var latest = new DirectoryInfo(_options.TempDirectory)
                             .GetFiles("RemedyCheckerLog*", SearchOption.TopDirectoryOnly)
                             .OrderByDescending(x => x.LastWriteTimeUtc)
                             .FirstOrDefault();
                if (latest != null)
                {
                    try
                    {
                        using (StreamReader file = File.OpenText(latest.FullName))
                        {
                            var lastPollResult = (RemedyPollResult)(new JsonSerializer()
                                                                    .Deserialize(file, typeof(RemedyPollResult)));
                            lastPollTimeUtc = lastPollResult.EndTimeUtc;
                            success         = true;
                        }
                    }
                    catch (Exception err)
                    {
                        // TODO: keep going through files until we find a good one?
                        _logger.Error($"Unable to get last time we polled remedy for work item changes: { err.Message }");
                    }
                }
            }
            if (!success)
            {
                lastPollTimeUtc = new DateTime(2018, 1, 1); //DateTime.Now.AddDays(-3);
            }
        }
        private ISafeguardConnection GetSgConnection()
        {
            var sppAddress      = _configDb.SafeguardAddress;
            var userCertificate = _configDb.UserCertificateBase64Data;
            var passPhrase      = _configDb.UserCertificatePassphrase?.ToSecureString();
            var apiVersion      = _configDb.ApiVersion ?? WellKnownData.DefaultApiVersion;
            var ignoreSsl       = _configDb.IgnoreSsl ?? true;

            if (sppAddress != null && userCertificate != null)
            {
                try
                {
                    _logger.Debug("Connecting to Safeguard: {address}", sppAddress);
                    var connection = ignoreSsl
                        ? Safeguard.Connect(sppAddress, Convert.FromBase64String(userCertificate), passPhrase, apiVersion, true)
                        : Safeguard.Connect(sppAddress, Convert.FromBase64String(userCertificate), passPhrase, CertificateValidationCallback, apiVersion);

                    return(connection);
                }
                catch (SafeguardDotNetException ex)
                {
                    _logger.Error(ex, $"Failed to connect to Safeguard at '{sppAddress}': {ex.Message}");
                }
            }

            return(null);
        }
Exemplo n.º 9
0
        private void RefreshDev()
        {
            if (_checkedForDevPackage)
            {
                return;
            }

            var pkg = _devPluginInstaller.GetPackage();

            if (pkg != null)
            {
                // If we have a package with this ID installed, uninstall it.
                var existing = _packageManager.LocalRepository.FindPackage(pkg.Id);
                if (existing != null)
                {
                    _logger.Information("Uninstalling old development package {PackageId}.", pkg.Id);
                    _packageManager.UninstallPackage(existing, true, true);
                }

                try
                {
                    _packageManager.InstallPackage(pkg, false, true);
                }
                catch (InvalidOperationException exception)
                {
                    _logger.Error(exception, "Error when installing plugin {PluginId}", pkg.Id);
                }
            }

            _checkedForDevPackage = true;
        }
Exemplo n.º 10
0
 public IActionResult Get()
 {
     _logger.Error("Data Critical Added Successfully");
     _logger.Fatal("Data Error Added Successfully");
     _logger.Error("Data saved as information {@DateTime}", DateTime.Now);
     return(Ok("Success"));
 }
Exemplo n.º 11
0
        public ActionResult <IEnumerable <JObject> > Get()
        {
            try
            {
                string    accountInfo = string.Empty;
                JObject[] result      = null;
                int       count       = 0;

                var cachedAccount = Startup.container.GetInstance <CachedAccountRepository>();
                var allAccounts   = cachedAccount.GetAll();
                result = new JObject[allAccounts.Count()];

                foreach (var conta in allAccounts.ToList())
                {
                    result[count] = JObject.Parse("{\"AccountNumber\": \"" + conta.AccountId.ToString() + "\", \"Person Name\": \"" + conta.PersonName + "\"}");
                    count++;
                }

                return(result);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Unable to show result.");
                throw;
            }
        }
Exemplo n.º 12
0
        private void CollectRegularStats()
        {
            try {
                var stats = CollectStats();
                if (stats != null)
                {
                    var rawStats = stats.GetStats(useGrouping: false, useMetadata: false);

                    if ((_statsStorage & StatsStorage.File) != 0)
                    {
                        SaveStatsToFile(StatsContainer.Group(rawStats));
                    }

                    if ((_statsStorage & StatsStorage.Stream) != 0)
                    {
                        if (_statsStreamCreated)
                        {
                            SaveStatsToStream(rawStats);
                        }
                    }
                }
            } catch (Exception ex) {
                Log.Error(ex, "Error on regular stats collection.");
            }
        }
Exemplo n.º 13
0
 private void PurgeTimedOutRequests()
 {
     if (_doNotTimeout)
     {
         return;
     }
     try {
         while (_pending.Count > 0)
         {
             var req = _pending.FindMin();
             if (req.Item1 <= DateTime.UtcNow || req.Item2.IsProcessing)
             {
                 req = _pending.DeleteMin();
                 req.Item2.ReplyStatus(HttpStatusCode.RequestTimeout,
                                       "Server was unable to handle request in time",
                                       e => Log.Debug(
                                           "Error occurred while closing timed out connection (HTTP service core): {e}.",
                                           e.Message));
             }
             else
             {
                 break;
             }
         }
     } catch (Exception exc) {
         Log.Error(exc, "Error purging timed out requests in HTTP request processor.");
     }
 }
Exemplo n.º 14
0
        public CincronBackend(IConfigurationSection config, FMSSettings cfg)
        {
            try
            {
                string msgFile;
#if DEBUG
                var path = System.Reflection.Assembly.GetExecutingAssembly().Location;
                msgFile = System.IO.Path.Combine(
                    System.IO.Path.GetDirectoryName(path), "..\\..\\..\\test\\Cincron\\parker-example-messages");
#else
                msgFile = config.GetValue <string>("Message File");
#endif

                Log.Information("Starting cincron backend with message file {file}", msgFile);

                if (!System.IO.File.Exists(msgFile))
                {
                    Log.Error("Message file {file} does not exist", msgFile);
                }

                _log = new JobLogDB(cfg);

                _log.Open(
                    System.IO.Path.Combine(cfg.DataDirectory, "log.db"),
                    startingSerial: cfg.StartingSerial
                    );
                _msgWatcher = new MessageWatcher(msgFile, _log, cfg);
                _msgWatcher.Start();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Unhandled exception when initializing cincron backend");
            }
        }
        private ResolvedEvent ResolveLinkToEvent(EventRecord eventRecord, long commitPosition)
        {
            if (eventRecord.EventType == SystemEventTypes.LinkTo)
            {
                try {
                    string[] parts       = Helper.UTF8NoBom.GetString(eventRecord.Data).Split('@');
                    long     eventNumber = long.Parse(parts[0]);
                    string   streamId    = parts[1];

                    var res = _readIndex.ReadEvent(streamId, eventNumber);
                    if (res.Result == ReadEventResult.Success)
                    {
                        return(ResolvedEvent.ForResolvedLink(res.Record, eventRecord, commitPosition));
                    }

                    return(ResolvedEvent.ForFailedResolvedLink(eventRecord, res.Result, commitPosition));
                } catch (Exception exc) {
                    Log.Error(exc, "Error while resolving link for event record: {eventRecord}",
                              eventRecord.ToString());
                }

                return(ResolvedEvent.ForFailedResolvedLink(eventRecord, ReadEventResult.Error, commitPosition));
            }

            return(ResolvedEvent.ForUnresolvedEvent(eventRecord, commitPosition));
        }
Exemplo n.º 16
0
 public T From <T>(string text)
 {
     try {
         return(JsonConvert.DeserializeObject <T>(text, FromSettings));
     } catch (Exception e) {
         Log.Error(e, "'{text}' is not a valid serialized {type}", text, typeof(T).FullName);
         return(default(T));
     }
 }
Exemplo n.º 17
0
 public void Dispose()
 {
     try {
         _tableIndex.Close(removeFiles: false);
     } catch (TimeoutException exc) {
         Log.Error(exc, "Timeout exception when trying to close TableIndex.");
         throw;
     }
 }
Exemplo n.º 18
0
        private void ReadNotificationsFrom(long fromEventNumber)
        {
            if (_stopped)
            {
                return;
            }
            _ioDispatcher.ReadForward(
                UserManagementService.UserPasswordNotificationsStreamId, fromEventNumber, 100, false,
                SystemAccounts.System, completed => {
                if (_stopped)
                {
                    return;
                }
                switch (completed.Result)
                {
                case ReadStreamResult.AccessDenied:
                case ReadStreamResult.Error:
                case ReadStreamResult.NotModified:
                    _log.Error("Failed to read: {stream} completed.Result={e}",
                               UserManagementService.UserPasswordNotificationsStreamId, completed.Result.ToString());
                    _ioDispatcher.Delay(
                        TimeSpan.FromSeconds(10), () => ReadNotificationsFrom(fromEventNumber));
                    break;

                case ReadStreamResult.NoStream:
                case ReadStreamResult.StreamDeleted:
                    _ioDispatcher.Delay(
                        TimeSpan.FromSeconds(1), () => ReadNotificationsFrom(0));
                    break;

                case ReadStreamResult.Success:
                    foreach (var @event in completed.Events)
                    {
                        PublishPasswordChangeNotificationFrom(@event);
                    }
                    if (completed.IsEndOfStream)
                    {
                        _ioDispatcher.Delay(
                            TimeSpan.FromSeconds(1), () => ReadNotificationsFrom(completed.NextEventNumber));
                    }
                    else
                    {
                        ReadNotificationsFrom(completed.NextEventNumber);
                    }
                    break;

                default:
                    throw new NotSupportedException();
                }
            },
                () => {
                _log.Warning("Timeout reading stream: {stream}. Trying again in 10 seconds.", UserManagementService.UserPasswordNotificationsStreamId);
                _ioDispatcher.Delay(TimeSpan.FromSeconds(10), () => ReadNotificationsFrom(fromEventNumber));
            },
                Guid.NewGuid());
        }
Exemplo n.º 19
0
        public IModel CreateModel()
        {
            if (!IsConnected)
            {
                _logger.Error("No RabbitMQ connections are available to perform this action");
                throw new InvalidOperationException("No RabbitMQ connections are available to perform this action");
            }

            return(_connection.CreateModel());
        }
Exemplo n.º 20
0
 private void SetResponseCode(int code)
 {
     try {
         HttpEntity.Response.StatusCode = code;
     } catch (ObjectDisposedException) {
         // ignore
     } catch (ProtocolViolationException e) {
         Log.Error(e, "Attempt to set invalid HTTP status code occurred.");
     }
 }
Exemplo n.º 21
0
        private ClientMessage.ReadEventCompleted ReadEvent(ClientMessage.ReadEvent msg)
        {
            using (HistogramService.Measure(ReaderReadHistogram)) {
                try {
                    var access = _readIndex.CheckStreamAccess(msg.EventStreamId, StreamAccessType.Read, msg.User);
                    if (!access.Granted)
                    {
                        return(NoData(msg, ReadEventResult.AccessDenied));
                    }

                    var result = _readIndex.ReadEvent(msg.EventStreamId, msg.EventNumber);
                    var record = result.Result == ReadEventResult.Success && msg.ResolveLinkTos
                                                ? ResolveLinkToEvent(result.Record, msg.User, null)
                                                : ResolvedEvent.ForUnresolvedEvent(result.Record);
                    if (record == null)
                    {
                        return(NoData(msg, ReadEventResult.AccessDenied));
                    }
                    if ((result.Result == ReadEventResult.NoStream ||
                         result.Result == ReadEventResult.NotFound) &&
                        result.OriginalStreamExists &&
                        SystemStreams.IsSystemStream(msg.EventStreamId))
                    {
                        return(NoData(msg, ReadEventResult.Success));
                    }

                    return(new ClientMessage.ReadEventCompleted(msg.CorrelationId, msg.EventStreamId, result.Result,
                                                                record.Value, result.Metadata, access.Public, null));
                } catch (Exception exc) {
                    Log.Error(exc, "Error during processing ReadEvent request.");
                    return(NoData(msg, ReadEventResult.Error, exc.Message));
                }
            }
        }
Exemplo n.º 22
0
        public void ThreadFunc()
        {
            for (; ;)
            {
                try
                {
                    var sleepTime = TimeSpan.FromMinutes(1);
                    Log.Debug("Sleeping for {mins} minutes", sleepTime.TotalMinutes);
                    var ret = WaitHandle.WaitAny(new WaitHandle[] { _shutdown, _newLogFile, _recheckQueues }, sleepTime, false);
                    if (ret == 0)
                    {
                        Log.Debug("Thread shutdown");
                        return;
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(1));

                    var mazakData = _readDB.LoadSchedulesAndLoadActions();
                    var logs      = LoadLog(_log.MaxForeignID());
                    var trans     = new LogTranslation(_jobDB, _log, mazakData, _settings,
                                                       le => MazakLogEvent?.Invoke(le)
                                                       );
                    var sendToExternal = new List <BlackMaple.MachineFramework.MaterialToSendToExternalQueue>();
                    foreach (var ev in logs)
                    {
                        try
                        {
                            sendToExternal.AddRange(trans.HandleEvent(ev));
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex, "Error translating log event at time " + ev.TimeUTC.ToLocalTime().ToString());
                        }
                    }

                    DeleteLog(_log.MaxForeignID());

                    _queues.CheckQueues(mazakData);

                    if (sendToExternal.Count > 0)
                    {
                        _sendToExternal.Post(sendToExternal).Wait(TimeSpan.FromSeconds(30));
                    }

                    if (logs.Count > 0)
                    {
                        NewEntries?.Invoke();
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error during log data processing");
                }
            }
        }
Exemplo n.º 23
0
        private void ReadCompleted(ClientMessage.ReadStreamEventsForwardCompleted onReadCompleted,
                                   Action onEmittedStreamsDeleted)
        {
            if (onReadCompleted.Result == ReadStreamResult.Success ||
                onReadCompleted.Result == ReadStreamResult.NoStream)
            {
                if (onReadCompleted.Events.Length == 0 && !onReadCompleted.IsEndOfStream)
                {
                    DeleteEmittedStreamsFrom(onReadCompleted.NextEventNumber, onEmittedStreamsDeleted);
                    return;
                }

                if (onReadCompleted.Events.Length == 0)
                {
                    _ioDispatcher.DeleteStream(_emittedStreamsCheckpointStreamId, ExpectedVersion.Any, false,
                                               SystemAccounts.System, x => {
                        if (x.Result == OperationResult.Success || x.Result == OperationResult.StreamDeleted)
                        {
                            Log.Information("PROJECTIONS: Projection Stream '{stream}' deleted",
                                            _emittedStreamsCheckpointStreamId);
                        }
                        else
                        {
                            Log.Error("PROJECTIONS: Failed to delete projection stream '{stream}'. Reason: {e}",
                                      _emittedStreamsCheckpointStreamId, x.Result);
                        }

                        _ioDispatcher.DeleteStream(_emittedStreamsId, ExpectedVersion.Any, false,
                                                   SystemAccounts.System, y => {
                            if (y.Result == OperationResult.Success ||
                                y.Result == OperationResult.StreamDeleted)
                            {
                                Log.Information("PROJECTIONS: Projection Stream '{stream}' deleted",
                                                _emittedStreamsId);
                            }
                            else
                            {
                                Log.Error(
                                    "PROJECTIONS: Failed to delete projection stream '{stream}'. Reason: {e}",
                                    _emittedStreamsId, y.Result);
                            }

                            onEmittedStreamsDeleted();
                        });
                    });
                }
                else
                {
                    var streamId = Helper.UTF8NoBom.GetString(onReadCompleted.Events[0].Event.Data.Span);
                    _ioDispatcher.DeleteStream(streamId, ExpectedVersion.Any, false, SystemAccounts.System,
                                               x => DeleteStreamCompleted(x, onEmittedStreamsDeleted, streamId,
                                                                          onReadCompleted.Events[0].OriginalEventNumber));
                }
            }
        }
Exemplo n.º 24
0
        private void BuildOutputLogger_OnErrorRaised(BuildProjectContextEntry projectEntry, object e, ErrorLevel errorLevel)
        {
            try
            {
                var projectItem = projectEntry.ProjectItem;
                if (projectItem == null)
                {
                    if (!TryGetProjectItem(projectEntry, out projectItem))
                    {
                        projectEntry.IsInvalid = true;
                        return;
                    }
                }

                var errorItem = new ErrorItem(errorLevel);
                switch (errorLevel)
                {
                case ErrorLevel.Message:
                    errorItem.Init((BuildMessageEventArgs)e);
                    break;

                case ErrorLevel.Warning:
                    errorItem.Init((BuildWarningEventArgs)e);
                    break;

                case ErrorLevel.Error:
                    errorItem.Init((BuildErrorEventArgs)e);
                    break;

                default:
                    break;
                }

                errorItem.VerifyValues();
                projectItem.AddErrorItem(errorItem);

                var  args            = new BuildErrorRaisedEventArgs(errorLevel, projectItem);
                bool buildNeedCancel = (args.ErrorLevel == ErrorLevel.Error && _packageSettingsProvider.Settings.GeneralSettings.StopBuildAfterFirstError);
                if (buildNeedCancel)
                {
                    _buildService.CancelBuildSolution();
                }

                bool navigateToBuildFailure = (args.ErrorLevel == ErrorLevel.Error && _packageSettingsProvider.Settings.GeneralSettings.NavigateToBuildFailureReason == NavigateToBuildFailureReasonCondition.OnErrorRaised);
                if (navigateToBuildFailure && !ErrorNavigationService.BuildErrorNavigated)
                {
                    _errorNavigationService.NavigateToErrorItem(errorItem);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Failed to fetch errormessage.");
            }
        }
Exemplo n.º 25
0
 public void Handle(GossipMessage.RetrieveGossipSeedSources message)
 {
     _state = GossipState.RetrievingGossipSeeds;
     try {
         _gossipSeedSource.BeginGetHostEndpoints(OnGotGossipSeedSources, null);
     } catch (Exception ex) {
         Log.Error(ex, "Error while retrieving cluster members through DNS.");
         _bus.Publish(TimerMessage.Schedule.Create(DnsRetryTimeout, _publishEnvelope,
                                                   new GossipMessage.RetrieveGossipSeedSources()));
     }
 }
Exemplo n.º 26
0
        public async Task <IActionResult> GetCurrentUser()
        {
            if (!User.Identity.IsAuthenticated)
            {
                _logger.Warning("GetCurrentUser called for unauthenticated user");
                return(NotFound());
            }
            else
            {
                string email;
                try
                {
                    email = User.GetEmail();
                }
                catch (InvalidOperationException err)
                {
                    _logger.Error(err, "Unable to retrieve email address for current user '{UserName}': {ErrorMessage}", User.Identity.Name, err.Message);
                    return(NotFound($"Unable to retrieve email address for current user '{User.Identity.Name}': {err.Message}"));
                }

                if (string.IsNullOrWhiteSpace(email))
                {
                    _logger.Error("Email address is empty for current user {UserName}", User.Identity.Name);
                    return(NotFound($"Email address is empty for current user '{User.Identity.Name}'"));
                }

                var personId = await _personRepository.GetPersonIdByEmailAsync(email);

                if (personId == null)
                {
                    _logger.Error("Unable to find a user for {EmailAddress}", email);
                    return(NotFound($"Unable to find a user for {email}"));
                }

                var person = await _personRepository.GetPersonAsync(personId.Value);

                if (person == null)
                {
                    _logger.Error("Unable to find a user for {EmailAddress} with id {PersonId}", email, personId);
                    return(NotFound($"Unable to find a user for {email} with id {personId}"));
                }

                // The following is temporary and should be replaced by real logic after our demo on tuesday.
                var permissions = new List <string>();
                if (User.IsAdmin() || User.IsInRole("Octava Business Analyst"))
                {
                    string permissionName = Core.Data.Permissions.EditStatusDescription.ToString();
                    permissionName = permissionName.First().ToString().ToLower() + permissionName.Substring(1);
                    permissions.Add(permissionName);
                }

                return(Ok(new { person.Id, person.Name, person.Email, Roles = User.GetRoles().ToArray(), Permissions = permissions.ToArray() }));
            }
        }
        private void construct_same_midpoint_indexes_for_any_combination_of_params(int maxIndexEntries)
        {
            for (var numIndexEntries = 0; numIndexEntries < maxIndexEntries; numIndexEntries++)
            {
                for (var depth = 0; depth < 20; depth++)
                {
                    var requiredMidpointsCount =
                        PTable.GetRequiredMidpointCountCached(numIndexEntries, _ptableVersion, depth);
                    List <long> requiredMidpoints = new List <long>();
                    for (var k = 0; k < requiredMidpointsCount; k++)
                    {
                        var index = PTable.GetMidpointIndex(k, numIndexEntries, requiredMidpointsCount);
                        requiredMidpoints.Add(index);
                    }

                    List <long> calculatedMidpoints = new List <long>();
                    for (var k = 0; k < numIndexEntries; k++)
                    {
                        if (PTable.IsMidpointIndex(k, numIndexEntries, requiredMidpointsCount))
                        {
                            calculatedMidpoints.Add(k);
                        }
                    }

                    if (numIndexEntries == 1 && calculatedMidpoints.Count == 1)
                    {
                        calculatedMidpoints.Add(calculatedMidpoints[0]);
                    }

                    if (requiredMidpoints.Count != calculatedMidpoints.Count)
                    {
                        Log.Error(
                            "Midpoint count mismatch for numIndexEntries: {0}, depth:{1} - Expected {2}, Found {3}",
                            numIndexEntries, depth, requiredMidpoints.Count, calculatedMidpoints.Count);
                    }

                    Assert.AreEqual(requiredMidpoints.Count, calculatedMidpoints.Count);

                    for (var i = 0; i < requiredMidpoints.Count; i++)
                    {
                        if (requiredMidpoints[i] != calculatedMidpoints[i])
                        {
                            Log.Error(
                                "Midpoint mismatch at index {0} for numIndexEntries: {1}, depth:{2} - Expected {3}, Found {4}",
                                i, numIndexEntries, depth, requiredMidpoints[i], calculatedMidpoints[i]);
                        }

                        Assert.AreEqual(requiredMidpoints[i], calculatedMidpoints[i]);
                    }
                }
            }
        }
Exemplo n.º 28
0
        public void LogException(Exception exception, string message     = "",
                                 [CallerMemberName] string memberName    = "",
                                 [CallerFilePath] string sourceFilePath  = "",
                                 [CallerLineNumber] int sourceLineNumber = 0)
        {
            var customMessage =
                $"CallerMemberName: [{memberName}].{Environment.NewLine}" +
                $"CallerFilePath: [{sourceFilePath}].{Environment.NewLine}" +
                $"CallerLineNumber: [{sourceLineNumber}].{Environment.NewLine}" +
                $"Message: [{message}]";

            logger.Error(exception, customMessage);
        }
Exemplo n.º 29
0
 private void OnGetInfo(HttpEntityManager entity, UriTemplateMatch match)
 {
     entity.ReplyTextContent(Codec.Json.To(new {
         ESVersion       = VersionInfo.Version,
         State           = _currentState.ToString().ToLower(),
         ProjectionsMode = _projectionType
     }),
                             HttpStatusCode.OK,
                             "OK",
                             entity.ResponseCodec.ContentType,
                             null,
                             e => Log.Error(e, "Error while writing HTTP response (info)"));
 }
Exemplo n.º 30
0
        protected virtual async Task OnIssueCreated(IssueCreatedEventArgs args, CancellationToken token)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (string.IsNullOrWhiteSpace(args.ReferenceId))
            {
                throw new ArgumentException("ReferenceId cannot be empty");
            }

            using (LogContext.PushProperty("IssueId", args.ReferenceId))
            {
                int?userId;
                try
                {
                    userId = string.IsNullOrWhiteSpace(args.RequestorEmail)
                    ? null : await GetOrCreateUserIdAsync(args.RequestorEmail, args.RequestorGivenName, args.RequestorSurnName, args.RequestorTelephone);
                }
                catch (Exception err)
                {
                    userId = null;
                    _logger.Warning(err, "Error retrieving user details for {EmailAddress}", args.RequestorEmail);
                }

                int ownerPersonId = userId.GetValueOrDefault();

                Issue oldIssue = null;
                oldIssue = await GetIssueByIncidentId(args.ReferenceId);

                if (oldIssue != null)
                {
                    _logger.Information("Found Issue {IssueId} in database, old status {IssueStatus}, new status {newIssueStatus}", args.ReferenceId, oldIssue.RemedyStatus, args.RemedyStatus);
                    await _issueRepository.DeleteIssueAsync(oldIssue, token);
                }

                try
                {
                    var issue = Issue.Create(args.Title, args.Description, args.ReferenceId, args.RemedyStatus, args.RequestorDisplayName, args.AssigneeEmail, args.AssigneeGroup, args.CreatedDate, args.Urgency, ownerPersonId);
                    _logger.Information("Saving Issue {IssueId} to database", args.ReferenceId);
                    await _issueRepository.AddIssueAsync(issue, token);
                }
                catch (Exception err)
                {
                    _logger.Error(err, "Unable to set work item id to Issue. Will retry later. Error was: {ErrorMessage}",
                                  err.Message);
                    throw;
                }
            }
        }