Exemple #1
0
        public static void Initialize()
        {
            log = Serilog.Log.ForContext <Scheduler>();

            JobManager.JobException += msg => log.Error(msg.Exception, "Scheduling error with job {jobname}:", msg.Name);
            JobManager.JobStart     += info => log.Debug("Started job: {jobname}", info.Name);
            JobManager.JobEnd       += info => log.Debug("Ended job: {jobname}", info.Name);

            JobManager.Initialize(new RealmJobRegistry());
        }
        public static void SetRegistryValue(this RegistryHive registryHive, string key, string valueName, string value)
        {
            Log.Debug("Setting registry value '{0}\\{1}' => '{2}' = '{3}'", registryHive, key, valueName, value);

            using (var registry = RegistryKey.OpenBaseKey(registryHive, RegistryView.Default))
            {
                using (var registryKey = registry.CreateSubKey(key))
                {
                    registryKey.SetValue(valueName, value);
                }
            }
        }
        public void Handle(SystemMessage.StateChangeMessage message)
        {
            _state = message.State;

            if (message.State == VNodeState.Leader)
            {
                return;
            }
            Log.Debug("Persistent subscriptions received state change to {state}. Stopping listening", _state);
            ShutdownSubscriptions();
            Stop();
        }
Exemple #4
0
        ////must be "" rather than null...
        private void ExecuteCommand(string commandName, string commandArgs = "")
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            Log.Verbose("ExecuteCommand={CommandName} CommandArgs={commandArgs}", commandName, commandArgs);
            var dte = _serviceProvider.GetService(typeof(DTE)) as DTE;

            if (dte == null)
            {
                throw new ArgumentNullException(nameof(dte));
            }
            dte.ExecuteCommand(commandName, commandArgs);
            Log.Debug("ExecuteCommand={CommandName} CommandArgs={commandArgs} Success", commandName, commandArgs);
        }
Exemple #5
0
        public List <string> CheckValidRoutes(IEnumerable <JobPlan> jobs)
        {
            var          logMessages = new List <string>();
            MazakAllData mazakData;

            if (!OpenDatabaseKitDB.MazakTransactionLock.WaitOne(TimeSpan.FromMinutes(2), true))
            {
                throw new Exception("Unable to obtain mazak database lock");
            }
            try
            {
                mazakData = readDatabase.LoadAllData();
            }
            finally
            {
                OpenDatabaseKitDB.MazakTransactionLock.ReleaseMutex();
            }

            try
            {
                Log.Debug("Check valid routing info");


                //The reason we create the clsPalletPartMapping is to see if it throws any exceptions.  We therefore
                //need to ignore the warning that palletPartMap is not used.
#pragma warning disable 168, 219
                var mazakJobs = ConvertJobsToMazakParts.JobsToMazak(
                    jobs,
                    1,
                    mazakData,
                    new HashSet <string>(),
                    writeDb.MazakType,
                    CheckPalletsUsedOnce,
                    fmsSettings,
                    logMessages);
#pragma warning restore 168, 219
            }
            catch (Exception ex)
            {
                if (ex.Message.StartsWith("Invalid pallet->part mapping"))
                {
                    logMessages.Add(ex.Message);
                }
                else
                {
                    throw;
                }
            }

            return(logMessages);
        }
Exemple #6
0
 public LogDataWeb(string path,
                   BlackMaple.MachineFramework.JobLogDB log,
                   BlackMaple.MachineFramework.JobDB jobDB,
                   BlackMaple.MachineFramework.ISendMaterialToExternalQueue sendToExternal,
                   IReadDataAccess readDB,
                   MazakQueues queues,
                   BlackMaple.MachineFramework.FMSSettings settings)
 {
     _path           = path;
     _log            = log;
     _jobDB          = jobDB;
     _readDB         = readDB;
     _queues         = queues;
     _settings       = settings;
     _sendToExternal = sendToExternal;
     _shutdown       = new AutoResetEvent(false);
     _newLogFile     = new AutoResetEvent(false);
     _recheckQueues  = new AutoResetEvent(false);
     if (System.IO.Directory.Exists(path))
     {
         _thread = new Thread(new ThreadStart(ThreadFunc));
         _thread.Start();
         _watcher          = new FileSystemWatcher(_path);
         _watcher.Filter   = "*.csv";
         _watcher.Created += (sender, evt) =>
                             _newLogFile.Set();
         //_watcher.Changed += (sender, evt) => _newLogFile.Set();
         _watcher.EnableRaisingEvents = true;
         Log.Debug("Watching {path} for new CSV files", _path);
     }
 }
Exemple #7
0
        public void Save(MazakWriteData data, string prefix)
        {
            CheckReadyForConnect();

            int checkInterval = data.Schedules.Count() + data.Pallets.Count() + 2 * data.Parts.Count() + data.Fixtures.Count() + data.Programs.Count();

            Log.Debug("Writing {@data} to transaction db", data);

            foreach (var prog in data.Programs)
            {
                if (prog.Command == MazakWriteCommand.Add)
                {
                    System.IO.File.WriteAllText(prog.MainProgram, prog.ProgramContent);
                }
            }

            try
            {
                using (var conn = CreateConnection())
                {
                    var trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);
                    try
                    {
                        ClearTransactionDatabase(conn, trans);
                        SaveData(data, conn, trans);
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }

                    for (int i = 0; i <= WaitCount; i++)
                    {
                        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(checkInterval));
                        if (CheckTransactionErrors(conn, prefix))
                        {
                            return;
                        }
                    }
                    throw new Exception("Timeout during download: open database kit is not running or responding");
                }
#if USE_OLEDB
            } catch (OleDbException ex) {
                throw new Exception(ex.ToString());
#endif
            }
            finally { }
        }
Exemple #8
0
        public void AddFolder(string folderPath)
        {
            log.Debug("Using package versions from folder: {FolderPath:l}", folderPath);
            foreach (var file in Directory.GetFiles(folderPath, "*.nupkg", SearchOption.AllDirectories))
            {
                log.Debug("Package file: {File:l}", file);

                PackageIdentity packageIdentity;
                if (TryReadPackageIdentity(file, out packageIdentity))
                {
                    Add(packageIdentity.Id, packageIdentity.Version.ToString());
                }
            }
        }
        private void EnsureRootPartitionIsWritten()
        {
            // below code only takes into account offline truncation
            if (!RootTypeId.HasValue)
            {
                RootTypeId = Guid.NewGuid();
                long pos = _writer.Checkpoint.ReadNonFlushed();
                var  rootPartitionType = _recordFactory.CreatePartitionTypeRecord(
                    timeStamp: DateTime.UtcNow,
                    logPosition: pos,
                    partitionTypeId: RootTypeId.Value,
                    partitionId: Guid.Empty,
                    name: RootPartitionTypeName);

                if (!_writer.Write(rootPartitionType, out pos))
                {
                    throw new Exception($"Failed to write root partition type!");
                }

                _writer.Flush();

                _log.Debug("Root partition type created, id: {id}", RootTypeId);
            }

            if (!RootId.HasValue)
            {
                RootId = Guid.NewGuid();
                long pos           = _writer.Checkpoint.ReadNonFlushed();
                var  rootPartition = _recordFactory.CreatePartitionRecord(
                    timeStamp: DateTime.UtcNow,
                    logPosition: pos,
                    partitionId: RootId.Value,
                    partitionTypeId: RootTypeId.Value,
                    parentPartitionId: Guid.Empty,
                    flags: 0,
                    referenceNumber: 0,
                    name: RootPartitionName);

                if (!_writer.Write(rootPartition, out pos))
                {
                    throw new Exception($"Failed to write root partition!");
                }

                _writer.Flush();

                _recordFactory.SetRootPartitionId(RootId.Value);

                _log.Debug("Root partition created, id: {id}", RootId);
            }
        }
Exemple #10
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);
            }
        }
        public void Execute()
        {
            _log = Serilog.Log.ForContext <LocationInventoryDecay>();

            using (var session = Db.DocStore.OpenSession())
            {
                var locs = session.Query <Location>()
                           .Where(l => l.LocationInventory.Count > 0)
                           .ToList();

                foreach (var loc in locs)
                {
                    int removed = loc.LocationInventory.RemoveAll(i => i.DecaysOn < DateTime.Now);
                    if (removed > 0)
                    {
                        _log.Debug("Removed {nr} decayed inventory from {locname}", removed, loc.Id);
                    }
                }

                if (session.Advanced.HasChanges)
                {
                    session.SaveChanges();
                }
            }
        }
        /// <summary>
        /// Logs the specified log event.
        /// </summary>
        /// <param name="logEvent">The <see cref="T:Swan.LogMessageReceivedEventArgs" /> instance containing the event data.</param>
        public void Log(LogMessageReceivedEventArgs logEvent)
        {
            switch (logEvent.MessageType)
            {
            case LogLevel.None:
                break;

            case LogLevel.Info:
                _logger.Information("{@logEvent}", logEvent);
                break;

            case LogLevel.Trace:
                _logger.Verbose("{@logEvent}", logEvent);
                break;

            case LogLevel.Debug:
                _logger.Debug("{@logEvent}", logEvent);
                break;

            case LogLevel.Warning:
                _logger.Warning("{@logEvent}", logEvent);
                break;

            case LogLevel.Error:
                _logger.Error("{@logEvent}", logEvent);
                break;

            case LogLevel.Fatal:
                _logger.Fatal("{@logEvent}", logEvent);
                break;
            }
        }
Exemple #13
0
        private static EsDriveInfo GetEsDriveInfoUnix(string directory, ILogger log)
        {
            // http://unix.stackexchange.com/questions/11311/how-do-i-find-on-which-physical-device-a-folder-is-located

            // example

            // Filesystem     1K-blocks      Used Available Use% Mounted on
            // /dev/sda1      153599996 118777100  34822896  78% /media/CC88FD3288FD1C20

            try {
                if (!Directory.Exists(directory))
                {
                    return(null);
                }
                var driveInfo      = ShellExecutor.GetOutput("df", string.Format("-P {0}", directory));
                var driveInfoLines =
                    driveInfo.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                if (driveInfoLines.Length == 0)
                {
                    return(null);
                }
                var ourline     = driveInfoLines[1];
                var trimmedLine = SystemStatsHelper.SpacesRegex.Replace(ourline, " ");
                var info        = trimmedLine.Split(' ');

                var totalBytes     = long.Parse(info[1].Trim()) * 1024; // the '1024-blocks' column
                var availableBytes = long.Parse(info[3].Trim()) * 1024; // the 'Available' column
                var mountPoint     = info[5];                           // the 'Mounted on' column

                return(new EsDriveInfo(mountPoint, totalBytes, availableBytes));
            } catch (Exception ex) {
                log.Debug(ex, "Could not get drive name for directory '{directory}' on Unix.", directory);
                return(null);
            }
        }
Exemple #14
0
        /// <summary>
        /// Creates a new segment, makes buffers available
        /// </summary>
        private void CreateNewSegment(bool forceCreation)
        {
            if (!_allowedToCreateMemory)
            {
                throw new UnableToCreateMemoryException();
            }
            lock (_creatingNewSegmentLock) {
                if (!forceCreation && _buffers.Count > _segmentChunks / 2)
                {
                    return;
                }

                var bytes = new byte[_segmentSize];
                _segments.Add(bytes);
                for (int i = 0; i < _segmentChunks; i++)
                {
                    var chunk = new ArraySegment <byte>(bytes, i * _chunkSize, _chunkSize);
                    _buffers.Push(chunk);
                }

                Log.Debug("Segments count: {segments}, buffers count: {buffers}, should be when full: {full}",
                          _segments.Count,
                          _buffers.Count,
                          _segments.Count * _segmentChunks);
            }
        }
Exemple #15
0
        public void Publish(Message message)
        {
            //if (message == null) throw new ArgumentNullException("message");

            var handlers = _handlers[message.MsgTypeId];

            for (int i = 0, n = handlers.Count; i < n; ++i)
            {
                var handler = handlers[i];
                if (_watchSlowMsg)
                {
                    var start = DateTime.UtcNow;

                    handler.TryHandle(message);

                    var elapsed = DateTime.UtcNow - start;
                    if (elapsed > _slowMsgThreshold)
                    {
                        Log.Debug("SLOW BUS MSG [{bus}]: {message} - {elapsed}ms. Handler: {handler}.",
                                  Name, message.GetType().Name, (int)elapsed.TotalMilliseconds, handler.HandlerName);
                        if (elapsed > QueuedHandler.VerySlowMsgThreshold && !(message is SystemMessage.SystemInit))
                        {
                            Log.Error("---!!! VERY SLOW BUS MSG [{bus}]: {message} - {elapsed}ms. Handler: {handler}.",
                                      Name, message.GetType().Name, (int)elapsed.TotalMilliseconds, handler.HandlerName);
                        }
                    }
                }
                else
                {
                    handler.TryHandle(message);
                }
            }
        }
Exemple #16
0
        /// <summary>
        /// Write a message with the given severity to the logs. Takes a StringBuilder to allow for minimal allocation.
        /// </summary>
        /// <param name="logLevel">The severity level of the log message.</param>
        /// <param name="logMessage">The log message itself in StringBuilder form for manipulation.</param>
        /// <param name="callerName">The name of the calling method.</param>
        /// <param name="callerSourceFile">The name of the source file of the caller.</param>
        /// <param name="callerLineNumber">The line number where the log is being called.</param>
        private void Write(
            LogLevel logLevel,
            StringBuilder logMessage,
            [CallerMemberName] string callerName     = null,
            [CallerFilePath] string callerSourceFile = null,
            [CallerLineNumber] int callerLineNumber  = 0)
        {
            string indentedLogMsg = IndentMsg(logMessage);
            string logLevelName   = logLevel.ToString().ToUpper();

            int threadId = Thread.CurrentThread.ManagedThreadId;

            switch (logLevel)
            {
            case LogLevel.Diagnostic:
                _logger.Verbose(s_logMessageTemplate, logLevelName, threadId, callerName, callerSourceFile, callerLineNumber, indentedLogMsg);
                return;

            case LogLevel.Verbose:
                _logger.Debug(s_logMessageTemplate, logLevelName, threadId, callerName, callerSourceFile, callerLineNumber, indentedLogMsg);
                return;

            case LogLevel.Normal:
                _logger.Information(s_logMessageTemplate, logLevelName, threadId, callerName, callerSourceFile, callerLineNumber, indentedLogMsg);
                return;

            case LogLevel.Warning:
                _logger.Warning(s_logMessageTemplate, logLevelName, threadId, callerName, callerSourceFile, callerLineNumber, indentedLogMsg);
                return;

            case LogLevel.Error:
                _logger.Error(s_logMessageTemplate, logLevelName, threadId, callerName, callerSourceFile, callerLineNumber, indentedLogMsg);
                return;
            }
        }
Exemple #17
0
        private Task Log(LogMessage logMessage)
        {
            switch (logMessage.Severity)
            {
            case LogSeverity.Critical:
                _logger.Fatal(logMessage.ToString());
                break;

            case LogSeverity.Error:
                _logger.Error(logMessage.ToString());
                break;

            case LogSeverity.Warning:
                _logger.Warning(logMessage.ToString());
                break;

            case LogSeverity.Info:
                _logger.Information(logMessage.ToString());
                break;

            case LogSeverity.Verbose:
            case LogSeverity.Debug:
                _logger.Debug(logMessage.ToString());
                break;

            default:
                _logger.Fatal(logMessage.ToString());
                break;
            }

            return(Task.CompletedTask);
        }
Exemple #18
0
        public void Log(object sender, LogEventArgs e)
        {
            switch (e.Severity)
            {
            case LogSeverity.Debug:
                var debugMsg = CreatetMessage(e.Message);
                _logger.Debug(debugMsg);
                break;

            case LogSeverity.Info:
                var infoMsg = CreatetMessage(e.Message);
                _logger.Information(infoMsg);
                break;

            case LogSeverity.Warning:
                var warningMsg = CreatetMessage(e.Message);
                _logger.Warning(warningMsg);
                break;

            case LogSeverity.Error:
                var errorMsg = CreatetMessage(e.Message, e.Exception);
                _logger.Error(errorMsg);
                break;

            case LogSeverity.Fatal:
                var fatalMsg = CreatetMessage(e.Message);
                _logger.Fatal(fatalMsg);
                break;
            }
        }
Exemple #19
0
        /// <summary>
        ///     Loads and returns an aggregate by id, from the store.
        /// </summary>
        public async Task <T> Load <T>(string aggregateId, CancellationToken cancellationToken = default)
            where T : Aggregate, new()
        {
            if (IsNullOrWhiteSpace(aggregateId))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(aggregateId));
            }

            var stream    = _getStreamName(typeof(T), aggregateId);
            var aggregate = new T();

            var nextPageStart = 0L;

            do
            {
                var page = await _connection.ReadStreamEventsForwardAsync(
                    stream, nextPageStart, MaxReadSize, false, _userCredentials);

                if (page.Events.Length > 0)
                {
                    aggregate.Load(
                        page.Events.Last().Event.EventNumber,
                        page.Events.Select(re => _serializer.Deserialize(
                                               re.Event.Data, _typeMapper.GetType(re.Event.EventType)
                                               )).ToArray());
                }

                nextPageStart = !page.IsEndOfStream ? page.NextEventNumber : -1;
            } while (nextPageStart != -1);

            Log.Debug("Loaded {aggregate} changes from stream {stream}", aggregate, stream);

            return(aggregate);
        }
        private void ConnectToApp()
        {
            Console.Write("/rAttempting to connect to {0}", _pipeName);
            int k = 0;

            while (true)
            {
                if (DoesNamedPipeExist(_pipeName))
                {
                    try
                    {
                        _pipeMessages.Connect(500);
                        break;
                    }
                    catch (TimeoutException) { }
                }
                switch (k++ % 5)
                {
                case 1: Console.Write("\rAttempting to connect to '" + _pipeName + "' /"); break;

                case 2: Console.Write("\rAttempting to connect to '" + _pipeName + "' -"); break;

                case 3: Console.Write("\rAttempting to connect to '" + _pipeName + "' |"); break;

                case 4: Console.Write("\rAttempting to connect to '" + _pipeName + "' \\"); break;
                }

                Thread.Sleep(500);
            }

            Console.Clear();
            _logger.Debug("Connected");
        }
Exemple #21
0
        private async Task <string> GetNextOwnerUserIdAsync(Workflow wf, string proposedOwnerUserName, string nextActivityKey = null)
        {
            Requires.NonNull(wf, nameof(wf));
            nextActivityKey = nextActivityKey ?? wf.CurrentWorkflowActivityKey;

            string proposedOwnerUserId = null;

            if (proposedOwnerUserName != null)
            {
                proposedOwnerUserId = PortalHelpers.GetUserId(proposedOwnerUserName);
                if (proposedOwnerUserId == null)
                {
                    throw new Exception($"Could not find user=[{proposedOwnerUserName}]");
                }
            }

            var output = new ObjectParameter("nextOwnerId", typeof(string));

            DB.Database.Log = s => Log.Debug(s);
            DB.GetNextLevelOwnerId(proposedOwnerUserId, wf.WorkflowId, nextActivityKey, null, output, false);
            Log.Information($"DB.GetNextLevelOwnerId('{proposedOwnerUserId}', {wf.WorkflowId}, '{nextActivityKey}')=>{output.Value}");
            if (output.Value == DBNull.Value)
            {
                return(await Task.FromResult((string)null));
            }
            return(await Task.FromResult(output.Value.ToString()));
        }
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);

            logger.Debug("Request completed: {route} {method} {code} {headers}", request.RequestUri.Host, request.Method, response.StatusCode, request.Headers);
            return(response);
        }
Exemple #23
0
        public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo)
        {
            var intercept = Once.Has(methodInfo);

            Logger.Debug("{method}: {intercept}", methodInfo, intercept);
            return(intercept);
        }
Exemple #24
0
        public void Log(LogEntry entry)
        {
            switch (entry.Severity)
            {
            case LoggingEventType.Verbose:
                _logger.Verbose(entry.Exception, entry.Message, entry.Args);
                break;

            case LoggingEventType.Debug:
                _logger.Debug(entry.Exception, entry.Message, entry.Args);
                break;

            case LoggingEventType.Information:
                _logger.Information(entry.Exception, entry.Message, entry.Args);
                break;

            case LoggingEventType.Warning:
                _logger.Warning(entry.Exception, entry.Message, entry.Args);
                break;

            case LoggingEventType.Error:
                _logger.Error(entry.Exception, entry.Message, entry.Args);
                break;

            case LoggingEventType.Fatal:
                _logger.Fatal(entry.Exception, entry.Message, entry.Args);
                break;

            default:
                throw new ArgumentException($"Severity {entry.Severity} is not supported by SerilogAdapter", "Severity");
            }
        }
Exemple #25
0
        private static List <string> GetSubjectAlternativeName(X509Certificate2 cert, Serilog.ILogger logger)
        {
            var result = new List <string>();

            var subjectAlternativeName = cert.Extensions.Cast <X509Extension>()
                                         .Where(n => n.Oid.Value == "2.5.29.17") //n.Oid.FriendlyName=="Subject Alternative Name")
                                         .Select(n => new AsnEncodedData(n.Oid, n.RawData))
                                         .Select(n => n.Format(true))
                                         .FirstOrDefault();


            if (subjectAlternativeName != null)
            {
                var alternativeNames = subjectAlternativeName.Split(new[] { "\r\n", "\r", "\n", "," }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var alternativeName in alternativeNames)
                {
                    logger.Debug($"Found subject alternative name: {alternativeName}");
                    var groups = Regex.Match(alternativeName, @"^(.*)[=,:](.*)").Groups; // @"^DNS Name=(.*)").Groups;

                    if (groups.Count > 0 && !String.IsNullOrEmpty(groups[2].Value))
                    {
                        result.Add(groups[2].Value);
                    }
                }
            }

            return(result);
        }
        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);
        }
        public async Task Project(object @event)
        {
            Log.Debug($"Upcasting {{event}} to {StreamName}", @event);

            switch (@event)
            {
            case Events.ClassifiedAdPublished e:
                var photoUrl = await _getUserPhoto(e.OwnerId);

                var newEvent = new ClassifiedAdUpcastedEvents.V1.ClassifiedAdPublished
                {
                    Id              = e.Id,
                    OwnerId         = e.OwnerId,
                    ApprovedBy      = e.ApprovedBy,
                    SellersPhotoUrl = photoUrl
                };

                await _eventStoreConnection.AppendEvents(
                    StreamName,
                    ExpectedVersion.Any,
                    newEvent
                    );

                break;
            }
        }
Exemple #28
0
        private IEnumerable <LoadAction> LoadActions(SqlConnection conn)
        {
            var qry =
                "SELECT a9_prcnum, a9_ptnam, a9_fixqty, a6_pos, a1_schcom " +
                "FROM A9_FixWork " +
                "LEFT OUTER JOIN M4_PalletData ON M4_PalletData.PalletDataID = a9_PalletDataID_ra " +
                "LEFT OUTER JOIN A6_PositionData ON a6_pltnum = m4_pltnum " +
                "LEFT OUTER JOIN A1_Schedule ON A1_Schedule.ScheduleID = a9_ScheduleID";
            var ret   = new List <LoadAction>();
            var elems = conn.Query(qry);

            foreach (var e in conn.Query <FixWork>(qry))
            {
                Log.Debug("Received load action {@action}", e);
                if (string.IsNullOrEmpty(e.a9_ptnam) || string.IsNullOrEmpty(e.a6_pos))
                {
                    continue;
                }

                int stat;
                if (e.a6_pos.StartsWith("LS"))
                {
                    if (!int.TryParse(e.a6_pos.Substring(2, 2), out stat))
                    {
                        continue;
                    }
                }
                else
                {
                    continue;
                }

                string part    = e.a9_ptnam;
                string comment = e.a1_schcom;
                int    idx     = part.IndexOf(':');
                if (idx >= 0)
                {
                    part = part.Substring(0, idx);
                }
                int proc = e.a9_prcnum;
                int qty  = e.a9_fixqty;

                ret.Add(new LoadAction(true, stat, part, comment, proc, qty));
            }
            Log.Debug("Parsed load actions to {@actions}", ret);
            return(ret);
        }
        IDocumentStore ConfigureRaven()
        {
            var store = new DocumentStore {
                Urls     = new[] { Configuration["RavenDb:Url"] },
                Database = Configuration["RavenDb:Database"]
            };

            if (Environment.IsDevelopment())
            {
                store.OnBeforeQuery += (_, args)
                                       => args.QueryCustomization
                                       .WaitForNonStaleResults()
                                       .AfterQueryExecuted(result =>
                {
                    Log.ForContext("SourceContext", "Raven").Debug("{index} took {duration}", result.IndexName, result.DurationInMs);
                });
            }

            try
            {
                store.Initialize();
                Log.Information("Connection to {url} document store established.", store.Urls[0]);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                          $"Failed to establish connection to \"{store.Urls[0]}\" document store!" +
                          $"Please check if https is properly configured in order to use the certificate.", ex);
            }

            try
            {
                var record = store.Maintenance.Server.Send(new GetDatabaseRecordOperation(store.Database));
                if (record == null)
                {
                    store.Maintenance.Server
                    .Send(new CreateDatabaseOperation(new DatabaseRecord(store.Database)));

                    Log.Debug("{database} document store database created.", store.Database);
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                          $"Failed to ensure that \"{store.Database}\" document store database exists!", ex);
            }

            try
            {
                IndexCreation.CreateIndexes(Assembly.GetExecutingAssembly(), store);
                Log.Information("{database} document store database indexes created or updated.", store.Database);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Failed to create or update \"{store.Database}\" document store database indexes!", ex);
            }

            return(store);
        }
        public void BuildPackage(string basePath, IList <string> includes, ManifestMetadata metadata, string outFolder, bool overwrite)
        {
            var filename = metadata.Id + "." + metadata.Version + ".zip";
            var output   = fileSystem.GetFullPath(Path.Combine(outFolder, filename));

            if (fileSystem.FileExists(output) && !overwrite)
            {
                throw new CommandException("The package file already exists and --overwrite was not specified");
            }

            log.Information("Saving {Filename} to {OutFolder}...", filename, outFolder);

            fileSystem.EnsureDirectoryExists(outFolder);

            var basePathLength = fileSystem.GetFullPath(basePath).Length;

            using (var stream = fileSystem.OpenFile(output, FileAccess.Write))
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
                {
                    foreach (var pattern in includes)
                    {
                        log.Debug("Adding files from {Path} matching pattern {Pattern}", basePath, pattern);
                        foreach (var file in PathResolver.PerformWildcardSearch(basePath, pattern))
                        {
                            var fullFilePath = fileSystem.GetFullPath(file);
                            if (string.Equals(fullFilePath, output, StringComparison.CurrentCultureIgnoreCase))
                            {
                                continue;
                            }

                            var relativePath = UseCrossPlatformDirectorySeparator(
                                fullFilePath.Substring(basePathLength).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
                            log.Debug("Adding file: {Path}", relativePath);

                            var entry = archive.CreateEntry(relativePath, CompressionLevel.Optimal);
                            entry.LastWriteTime = new DateTimeOffset(new FileInfo(file).LastWriteTime);

                            using (var entryStream = entry.Open())
                                using (var sourceStream = File.OpenRead(file))
                                {
                                    sourceStream.CopyTo(entryStream);
                                }
                        }
                    }
                }
        }