public void SaveBooks(IEnumerable <Book> books) { if (ReferenceEquals(books, null)) { throw new ArgumentNullException(); } try { using (var writer = new BinaryWriter(File.Open(FilePath, FileMode.OpenOrCreate, FileAccess.Write))) { foreach (var book in books) { writer.Write(book.Title); writer.Write(book.Author); writer.Write(book.ReleaseDate.ToString("d")); writer.Write(book.Price); } } logger.Trace($"Saved {books.Count()} books to {Environment.CurrentDirectory}'\'{FilePath}"); } catch (IOException ex) { logger.Error($"error {ex.GetType()} in\n {ex.StackTrace}\n whith message {ex.Message}"); throw new Exception("Can't save data", ex); } }
static void LogError(Exception ex, string method, string attributeOrElementName) { if (logger == null) { throw ex; } #if DEBUG logger.Error(method + ": Attribute or element: " + attributeOrElementName + ": " + ex.ToString()); #else logger.Error(method + ": Attribute or element: " + attributeOrElementName + ": " + ex.Message); #endif }
public HttpResponseMessage UploadFile() { var statuses = new List <FilesStatus>(); try { //todo can we eliminate the HttpContext here UploadWholeFile(HttpContextSource.Current, statuses); } catch (Exception exc) { Logger.Error(exc); } return(IframeSafeJson(statuses)); }
public virtual void LogException(Exception e) { if (!CanHandle(e)) { throw new ArgumentException("ExceptionHandler has been asked to log exception of a type it does not handle!", e); } _logger.Error($"{_errorShortCode} - {e.Message}", e, _errorShortCode, e.Message); }
/// <summary> Append one or more events to the stream. </summary> /// <remarks> /// Events are assigned consecutive sequence numbers. The FIRST of these /// numbers is returned. /// /// If no events are provided, return null. /// /// If this object's state no longer represents the remote stream (because other /// events have been written from elsewhere), this method will not write any /// events and will return null. The caller should call <see cref="FetchAsync"/> /// until it returns false to have the object catch up with remote state. /// </remarks> public async Task <uint?> WriteAsync(IReadOnlyList <TEvent> events, CancellationToken cancel = default(CancellationToken)) { if (events.Count == 0) { return(null); } if (Position < _minimumWritePosition) { return(null); } if (events.Any(e => e == null)) { throw new ArgumentException(@"No null events allowed", nameof(events)); } var sw = Stopwatch.StartNew(); var rawEvents = events.Select((e, i) => new RawEvent(_lastSequence + (uint)(i + 1), _serializer.Serialize(e))) .ToArray(); try { var result = await Storage.WriteAsync(Position, rawEvents, cancel); _minimumWritePosition = result.NextPosition; if (result.Success) { foreach (var e in rawEvents) { _cache.Enqueue(e); } Position = result.NextPosition; var first = _lastSequence + 1; _lastSequence += (uint)rawEvents.Length; _log?.Debug( $"Wrote {rawEvents.Length} events up to seq {_lastSequence} in {sw.Elapsed.TotalSeconds:F3}s."); return(first); } _log?.Debug($"Collision when writing {rawEvents.Length} events after {sw.Elapsed.TotalSeconds:F3}s."); return(null); } catch (Exception e) { _log?.Error($"When writing {rawEvents.Length} events after seq {_lastSequence}.", e); throw; } }
/// <summary> Loop forever (or at least, until it's done). </summary> /// <remarks> Any exceptions thrown are passed to the exception callback. </remarks> private async Task Loop() { // Wait for initialization to finish and check success. try { await Ready.ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception e) { _log?.Error("While waiting to catch up with event stream.", e); return; } // The auto-refresh process // ======================== // This is a background task that checks periodically whether // a synchronization with the remote stream has occurred. If // it has not, it performs one. #pragma warning disable CS4014 Task.Run(async() => { while (!_cancel.IsCancellationRequested) { var syncStep = Wrapper.SyncStep; // RefreshPeriod/2 because it's possible to have a // syncStep increment happen right before this 'await', // in which case the delay will execute twice before // it detects that no sync is happening. await Task.Delay(TimeSpan.FromSeconds(RefreshPeriod / 2), _cancel); if (syncStep == Wrapper.SyncStep) { await CatchUpAsync(default(CancellationToken)); } } }, _cancel); #pragma warning restore CS4014 // The actual loop // =============== while (!_cancel.IsCancellationRequested) { // This sleeps until an action becomes available in the queue var nextAction = await _pending.Dequeue(_cancel).ConfigureAwait(false); // The action does not throw (is it wrapped properly) await nextAction().ConfigureAwait(false); } }
/// <summary> Append events, constructed from the state, to the stream. </summary> /// <remarks> /// Builder returns array of events to be appended, and additional data /// that will be returned by this method. Builder may be called more than /// once. /// </remarks> public async Task <AppendResult <T> > AppendEventsAsync <T>( Func <TState, Append <TEvent, T> > builder, CancellationToken cancel = default(CancellationToken)) { var thrownByBuilder = false; try { while (true) { thrownByBuilder = true; var tuple = builder(Current); thrownByBuilder = false; // No events to append, just return result if (tuple.Events == null || tuple.Events.Count == 0) { return(new AppendResult <T>(0, 0, tuple.Result)); } // Append the events var done = await Stream.WriteAsync(tuple.Events, cancel).ConfigureAwait(false); if (done == null) { // Append failed. Catch up and try again. await CatchUpAsync(cancel).ConfigureAwait(false); } else { // Append succeeded. Catch up with locally available events (including those // that were just added), then return append information. CatchUpLocal(); SyncStep++; return(new AppendResult <T>(tuple.Events.Count, (uint)done, tuple.Result)); } } } catch (OperationCanceledException) { throw; } catch (Exception e) { if (!thrownByBuilder) { _log.Error("While appending events", e); } throw; } }
public DalFileType GetById(long key) { if (key < 0) { var error = new ArgumentOutOfRangeException(nameof(key), "parametr can't be negative"); logger.Error(error, error.Message); throw error; } return(context.Set <FileTypes>().FirstOrDefault(user => user.id == key).ToDalFileType()); }
public void SaveBooks(IEnumerable <Book> books) { if (ReferenceEquals(books, null)) { throw new ArgumentNullException(); } try { using (var fileStream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write)) { new XmlSerializer(typeof(List <Book>)).Serialize(fileStream, new List <Book>(books)); } logger.Trace($"Saved {books.Count()} books to {Environment.CurrentDirectory}'\'{FilePath}"); } catch (IOException ex) { logger.Error($"error {ex.GetType()} in\n {ex.StackTrace}\n whith message {ex.Message}"); throw new Exception("Can't save data", ex); } }
public BookService(IEnumerable <Book> collection, IComparer <Book> comparer, ILogAdapter logger) { if (ReferenceEquals(collection, null)) { logger.Error($"Faild to create new books storage -> collection is null\n {new StackTrace()}"); throw new ArgumentNullException(); } if (ReferenceEquals(comparer, null)) { comparer = Comparer <Book> .Default; } this.logger = logger; booksStorage = new SortedSet <Book>(collection, comparer); }
/// <summary> Initialize the wrapper and set <see cref="IsReady"/> to true. </summary> /// <remarks> /// Upon failure, logs the exception and tries again after a short delay, forever. /// </remarks> private async Task Initialize() { while (!_cancel.IsCancellationRequested) { try { await Wrapper.InitializeAsync(_cancel).ConfigureAwait(false); _isReady = true; return; } catch (OperationCanceledException) { throw; } catch (Exception e) { _log.Error("Could not initialize EventStreamService", e); _initFailure = e; Wrapper.Reset(); } await Task.Delay(TimeSpan.FromSeconds(5), _cancel).ConfigureAwait(false); } }
private static IEnumerable <IDataSource> GetDataSources() { var typeLocator = new TypeLocator(); IEnumerable <Type> types = typeLocator.GetAllMatchingTypes(IsValidDataSourceProvider); foreach (Type filterType in types) { IDataSource filter; try { filter = Activator.CreateInstance(filterType) as IDataSource; } catch (Exception e) { Logger.Error($"Unable to create {filterType.FullName} while GetDatasources. {e.Message}"); filter = null; } if (filter != null) { yield return(filter); } } }
/// <summary> /// Reifies a group of projections as a <typeparamref name="TState"/> object. /// </summary> public ReifiedProjectionGroup(IEnumerable <IProjection <TEvent> > projections, IProjectionCacheProvider cacheProvider = null, ILogAdapter log = null) { // Dirty reflection work to reify the individual projections and store their // type parameter. var reifiedByType = new Dictionary <Type, IReifiedProjection <TEvent> >(); foreach (var p in projections) { if (reifiedByType.ContainsKey(p.State)) { log?.Error($"Found multiple projections for type {p.State}."); throw new ArgumentException($"Multiple projections for type '{p.State}'", nameof(projections)); } var reifiedProjectionType = typeof(ReifiedProjection <,>) .MakeGenericType(typeof(TEvent), p.State); var projectionType = typeof(IProjection <,>) .MakeGenericType(typeof(TEvent), p.State); var constructor = reifiedProjectionType .GetTypeInfo() .GetConstructor(new [] { projectionType, typeof(IProjectionCacheProvider), typeof(ILogAdapter) }); if (constructor == null) { throw new Exception("No constructor found for '" + reifiedProjectionType + "'"); } IReifiedProjection <TEvent> reified; try { reified = (IReifiedProjection <TEvent>)constructor.Invoke(new object[] { p, cacheProvider, log }); } catch (TargetInvocationException e) { log?.Error($"When creating reified projection for type {p.State}.", e.InnerException); throw e.InnerException; } reifiedByType.Add(p.State, reified); } // Easy case: a projection outputs the state type directly IReifiedProjection <TEvent> direct; if (reifiedByType.TryGetValue(typeof(TState), out direct)) { _reifiedProjections = new[] { direct }; var directCast = (ReifiedProjection <TEvent, TState>)direct; _refresh = () => directCast.Current; InvalidateCurrent(); return; } // Hard case: state is made from the results of multiple independent // projections. Need to write code to combine them. var posByType = new Dictionary <Type, int>(); var reifiedByPos = new List <IReifiedProjection <TEvent> >(); var stateConstructor = typeof(TState) .GetTypeInfo() .GetConstructors() .FirstOrDefault(c => { var p = c.GetParameters(); if (p.Length == 0) { return(false); } return(p.All(info => reifiedByType.ContainsKey(info.ParameterType))); }); if (stateConstructor == null) { throw new ArgumentException($"No compatible constructor found in '{typeof(TState)}'", nameof(projections)); } // Build an expression that will extract the state components from "array" and // pass them to the constructor. var parameters = stateConstructor.GetParameters(); var array = Expression.Parameter(typeof(IReifiedProjection <TEvent>[])); var arguments = new List <Expression>(); foreach (var p in parameters) { int pos; if (!posByType.TryGetValue(p.ParameterType, out pos)) { pos = posByType.Count; posByType.Add(p.ParameterType, pos); reifiedByPos.Add(reifiedByType[p.ParameterType]); } var argReified = Expression.Convert( Expression.ArrayIndex(array, Expression.Constant(pos)), typeof(ReifiedProjection <,>).MakeGenericType(typeof(TEvent), p.ParameterType)); arguments.Add(Expression.Property(argReified, "Current")); } var lambda = Expression.Lambda <Func <IReifiedProjection <TEvent>[], TState> >( Expression.New(stateConstructor, arguments), array); var extract = lambda.Compile(); var reifiedProjections = _reifiedProjections = reifiedByPos.ToArray(); _refresh = () => extract(reifiedProjections); InvalidateCurrent(); }
public void Error(string message, Exception ex = null) { _log.Error(Elapsed + " " + message, ex); }
/// <inheritdoc/> public static void Error(object caller, object message, params object[] replacements) => _log.Error(caller, message, replacements);