Here are the examples of the csharp api System.Action.Invoke(System.Exception) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
667 Examples
19
View Source File : Store.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
internal void Dispose(Action<Exception> logException)
{
var values = Values.UnderlyingArray;
for (int i = 0; i < values.Length; i++)
{
if (!(values[i] is IDisposable disposable))
continue;
try
{
disposable.Dispose();
}
catch (Exception e)
{
// Eh.
logException(e);
}
}
}
19
View Source File : RedirectionObserver.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public void OnError(Exception error) => ErrorAction?.Invoke(error);
19
View Source File : SimService.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public void Launch(Action<Exception> done) {
if (_task != null && !_task.IsCompleted) {
throw new InvalidOperationException($"Can't launch {Id} while previous instance is {_task.Status}");
}
var procID = _machine.NextProcID();
var env = new SimProc(Id, _machine, procID, _factory);
_task = _factory.StartNew(async () => {
try {
var engine = _launcher(env);
try {
await engine.Run();
} finally {
await engine.Dispose();
}
} catch (AggregateException ex) {
done(ex.InnerException);
return;
}
catch (Exception ex) {
done(ex);
return;
}
done(null);
}).Unwrap();
_proc = env;
}
19
View Source File : IObservable.Fuse.cs
License : MIT License
Project Creator : AdamRamberg
License : MIT License
Project Creator : AdamRamberg
public void OnError(Exception error)
{
_onError(error);
}
19
View Source File : APNode.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
public void StartServer(string address) {
if (CurrentMode == Mode.Idle) {
tmpAddress = address;
network.StartServer(address);
}
else if (CurrentMode == Mode.Server) {
var e = new Exception($"Already hosting address {Address}");
OnServerStartFailure?.Invoke(e);
}
else {
var e = new Exception($"Already connected to addr {Address}");
OnServerStartFailure?.Invoke(e);
}
}
19
View Source File : APNode.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
public void Connect(string address) {
if (CurrentMode == Mode.Idle) {
tmpAddress = address;
network.Connect(address);
}
else if (CurrentMode == Mode.Client) {
var e = new Exception("Already connected to addr " + Address);
OnConnectionFailed?.Invoke(e);
}
else {
var e = new Exception("Already connected to addr " + Address);
OnConnectionFailed?.Invoke(e);
}
}
19
View Source File : APNode.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
void Network_OnServerStartFailure(NetworkEvent e) {
Reset();
OnServerStartFailure?.Invoke(
new Exception(e.GetDatareplacedtring() + e.Info)
);
}
19
View Source File : APNode.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
void Network_OnConnectionFailed(NetworkEvent e) {
Reset();
var ex = new Exception(e.GetDatareplacedtring() + e.Info);
OnConnectionFailed?.Invoke(ex);
}
19
View Source File : WebSocketSharpExtensions.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
public static void ConnectAsync(this WebSocket socket, Action OnConnect, Action<Exception> OnError) {
Action onDone = () => { };
EventHandler onConnect = (sender, e) => {
if (OnConnect != null) OnConnect();
onDone();
};
EventHandler<CloseEventArgs> onClose = (sender, e) => {
if (OnError != null) OnError(new Exception(e.Reason));
onDone();
};
onDone = () => {
socket.OnOpen -= onConnect;
socket.OnClose -= onClose;
};
socket.OnOpen += onConnect;
socket.OnClose += onClose;
socket.ConnectAsync();
}
19
View Source File : AirPeerUniVoiceNetwork.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
void Init() {
node.OnServerStartSuccess += () => OnCreatedChatroom?.Invoke();
node.OnServerStartFailure += e =>
OnChatroomCreationFailed?.Invoke(e);
node.OnServerStop += () => OnlosedChatroom?.Invoke();
node.OnConnectionFailed += ex => OnChatroomJoinFailed?.Invoke(ex);
node.OnReceiveID += id => {
if (id != 0) {
OnJoinedChatroom?.Invoke(id);
OnPeerJoinedChatroom?.Invoke(0); // server joins instantly
}
};
node.OnDisconnected += () => OnLeftChatroom?.Invoke();
node.OnRemoteServerClosed += () => OnLeftChatroom?.Invoke();
node.OnClientJoined += id => OnPeerJoinedChatroom?.Invoke(id);
node.OnClientLeft += id => OnPeerLeftChatroom?.Invoke(id);
node.OnPacketReceived += (sender, packet) => {
if (packet.Tag.Equals("audio")) {
var reader = new BytesReader(packet.Payload);
var index = reader.ReadInt();
var frequency = reader.ReadInt();
var channels = reader.ReadInt();
var samples = reader.ReadFloatArray();
OnAudioReceived?.Invoke(new ChatroomAudioDTO {
id = sender,
segmentIndex = index,
frequency = frequency,
channelCount = channels,
samples = samples
});
}
};
}
19
View Source File : BaseCommand.cs
License : MIT License
Project Creator : aimore
License : MIT License
Project Creator : aimore
public void Execute(object parameter)
{
var nowTime = DateTime.UtcNow;
if (_actionFrequency == TimeSpan.Zero
|| Math.Abs((nowTime - _lastActionTime).TotalMilliseconds) >= _actionFrequency.TotalMilliseconds)
{
_lastActionTime = nowTime;
try
{
_action.Invoke(parameter);
}
catch (Exception ex)
{
_onExceptionAction?.Invoke(ex);
if (_shouldSuppressExceptions)
{
return;
}
throw ex;
}
}
}
19
View Source File : AsyncHelper.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public static async Task<T> Try<T>(Func<Task<T>> taskFactory, int times, Action<Exception> onError = null)
{
for (var i = 1; i <= times; i++)
{
try
{
var response = await taskFactory();
return response;
}
catch (Exception e)
{
onError?.Invoke(e);
if (i >= times)
{
throw;
}
await Task.Delay(ExponentialBackoffTimeSlot(i) * 1000);
}
}
throw new NotImplementedException("Code shall not reach here.");
}
19
View Source File : CannonService.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public void Fire<T>(Action<T> bullet, Action<Exception> handler = null)
{
_logger.LogInformation("Fired a new action.");
Task.Run(() =>
{
using var scope = _scopeFactory.CreateScope();
var dependency = scope.ServiceProvider.GetRequiredService<T>();
try
{
bullet(dependency);
}
catch (Exception e)
{
_logger.LogError(e,"Cannon crashed!");
handler?.Invoke(e);
}
finally
{
(dependency as IDisposable)?.Dispose();
}
});
}
19
View Source File : CannonService.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public void FireAsync<T>(Func<T, Task> bullet, Action<Exception> handler = null)
{
_logger.LogInformation("Fired a new async action.");
Task.Run(async () =>
{
using var scope = _scopeFactory.CreateScope();
var dependency = scope.ServiceProvider.GetRequiredService<T>();
try
{
await bullet(dependency);
}
catch (Exception e)
{
_logger.LogError(e,"Cannon crashed!");
handler?.Invoke(e);
}
finally
{
(dependency as IDisposable)?.Dispose();
}
});
}
19
View Source File : TaskQueue.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
private async Task RunTasksInQueue()
{
var tasksInFlight = Task.CompletedTask;
while (_pendingTaskFactories.Any())
{
while (tasksInFlight.IsCompleted && _pendingTaskFactories.Any())
{
var taskFactory = _pendingTaskFactories.Dequeue();
tasksInFlight = taskFactory();
}
try
{
await tasksInFlight;
}
catch (Exception e)
{
OnError?.Invoke(e);
}
}
}
19
View Source File : ForEach.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static async ValueTask ForEachAction<T>(IAsyncEnumerable<T> source, Action<T> onNext, Action<Exception> onError, Action onComplete)
{
var enumerator = source.GetAsyncEnumerator(default);
try
{
for (; ; )
{
bool b;
try
{
b = await enumerator.MoveNextAsync();
if (b)
{
onNext?.Invoke(enumerator.Current);
}
}
catch (Exception ex)
{
onError?.Invoke(ex);
break;
}
if (!b)
{
onComplete?.Invoke();
break;
}
}
}
finally
{
await enumerator.DisposeAsync();
}
}
19
View Source File : CompletableLambdaObserver.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public void OnError(Exception error)
{
DisposableHelper.WeakDispose(ref upstream);
try
{
onError?.Invoke(error);
}
catch (Exception)
{
// FIXME nowhere to put these
}
}
19
View Source File : CompletablePeek.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
void Error(Exception error, bool callTerminate)
{
upstream = DisposableHelper.DISPOSED;
try
{
onError?.Invoke(error);
}
catch (Exception ex)
{
error = new AggregateException(error, ex);
}
if (callTerminate)
{
try
{
onTerminate?.Invoke();
}
catch (Exception ex)
{
error = new AggregateException(error, ex);
}
}
downstream.OnError(error);
try
{
onAfterTerminate?.Invoke();
}
catch (Exception)
{
// FIXME what should happen with the exception
}
Finally();
}
19
View Source File : CompletableBlockingConsumer.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal void Run()
{
if (CurrentCount != 0)
{
try
{
Wait();
}
catch (ObjectDisposedException)
{
return;
}
}
var ex = error;
if (ex != ExceptionHelper.TERMINATED)
{
onError?.Invoke(ex);
}
else
{
onCompleted?.Invoke();
}
}
19
View Source File : MaybeBlockingConsumer.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal void Run()
{
if (CurrentCount != 0)
{
try
{
Wait();
}
catch (ObjectDisposedException)
{
return;
}
}
var ex = error;
if (ex != ExceptionHelper.TERMINATED)
{
onError?.Invoke(ex);
}
else
{
if (hasValue)
{
onSuccess?.Invoke(value);
}
else
{
onCompleted?.Invoke();
}
}
}
19
View Source File : BlockingObserver.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
protected override void Error(Exception ex)
{
onError.Invoke(ex);
}
19
View Source File : ObservableSourcePeek.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
void OnErrorCore(Exception ex, bool callOnTerminate)
{
if (done)
{
return;
}
done = true;
try
{
onError?.Invoke(ex);
}
catch (Exception exc)
{
ex = new AggregateException(ex, exc);
}
if (callOnTerminate)
{
try
{
onTerminate?.Invoke();
}
catch (Exception exc)
{
ex = new AggregateException(ex, exc);
}
}
downstream.OnError(ex);
try
{
onAfterTerminate?.Invoke();
}
catch (Exception)
{
// TODO where to put these?
}
DoFinally();
}
19
View Source File : SingleBlockingConsumer.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal void Run()
{
if (CurrentCount != 0)
{
try
{
Wait();
}
catch (ObjectDisposedException)
{
return;
}
}
var ex = error;
if (ex != ExceptionHelper.TERMINATED)
{
onError?.Invoke(ex);
}
else
{
onSuccess?.Invoke(value);
}
}
19
View Source File : LambdaSignalObserver.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public void OnError(Exception ex)
{
if (!DisposableHelper.IsDisposed(ref upstream))
{
DisposableHelper.WeakDispose(ref upstream);
try
{
onError?.Invoke(ex);
}
catch (Exception)
{
// TODO where to put these?
}
}
}
19
View Source File : FlowablePeek.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public override void OnError(Exception cause)
{
if (done)
{
return;
}
done = true;
try
{
parent.onError?.Invoke(cause);
parent.onTerminated?.Invoke();
}
catch (Exception ex)
{
cause = new AggregateException(cause, ex);
}
actual.OnError(cause);
AfterTerminated();
}
19
View Source File : ParallelFlowablePeek.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public void OnError(Exception cause)
{
if (done)
{
return;
}
done = true;
try
{
parent.onError?.Invoke(cause);
parent.onTerminated?.Invoke();
}
catch (Exception ex)
{
cause = new AggregateException(cause, ex);
}
actual.OnError(cause);
OnAfterTerminate();
}
19
View Source File : BlockingLambdaSubscriber.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public void Run()
{
for (;;)
{
if (SubscriptionHelper.IsCancelled(ref upstream))
{
return;
}
if (Volatile.Read(ref wip) == 0)
{
Monitor.Enter(this);
try
{
for (;;)
{
if (SubscriptionHelper.IsCancelled(ref upstream))
{
return;
}
if (Volatile.Read(ref wip) != 0)
{
break;
}
Monitor.Wait(this);
}
}
finally
{
Monitor.Exit(this);
}
}
if (queue.Poll(out T current))
{
int c = consumed + 1;
if (c == limit)
{
consumed = 0;
upstream.Request(c);
}
else
{
consumed = c;
}
onNext(current);
Interlocked.Decrement(ref wip);
continue;
}
var ex = error;
if (ex != null)
{
onError(ex);
}
else
{
onComplete();
}
return;
}
}
19
View Source File : ActionSubscriber.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public void OnError(Exception cause)
{
if (SubscriptionHelper.IsCancelled(ref upstream))
{
return;
}
Volatile.Write(ref upstream, SubscriptionHelper.Cancelled);
try
{
onError(cause);
}
catch
{
// TODO what should happen?
}
}
19
View Source File : ActionSubscriber.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public void OnNext(T element)
{
if (SubscriptionHelper.IsCancelled(ref upstream))
{
return;
}
try
{
onNext(element);
}
catch (Exception ex)
{
upstream.Cancel();
onError(ex);
}
}
19
View Source File : DefaultProducerStage.cs
License : Apache License 2.0
Project Creator : akkadotnet
License : Apache License 2.0
Project Creator : akkadotnet
private Action<DeliveryReport<K, V>> BuildSendCallback<TResult>(
TaskCompletionSource<TResult> completion,
Action<DeliveryReport<K, V>> onSuccess,
Action<Exception> onFailure)
{
return report =>
{
var error = report.Error;
if (error.IsError)
{
onFailure(new ProduceException<K, V>(error, report));
}
else
{
onSuccess(report);
ConfirmAndCheckForCompletion();
}
};
}
19
View Source File : SqlProvider.cs
License : MIT License
Project Creator : alfa-laboratory
License : MIT License
Project Creator : alfa-laboratory
public void UsingTransaction(Action<SqlTransaction> onExecute, Action<Exception> onError, Action onSuccess = null!)
{
var transaction = Connection.BeginTransaction(IsolationLevel.ReadUncommitted);
try
{
onExecute(transaction);
transaction.Commit();
}
catch (Exception ex)
{
Log.Logger().LogError($"Transaction failed: {transaction} {Environment.NewLine} {ex.Message}");
transaction.Rollback();
onError(ex.GetBaseException());
}
finally
{
transaction.Dispose();
}
}
19
View Source File : CPU.cs
License : MIT License
Project Creator : ancientproject
License : MIT License
Project Creator : ancientproject
public void Step()
{
try
{
State.Accept(State.fetch());
State.Eval();
}
catch (Exception e)
{
OnError?.Invoke(e);
halt(0xFFFF, e.Message.ToLowerInvariant());
if(State.ec)
WriteLine(e.ToString());
Trace.TraceError(e.ToString());
}
}
19
View Source File : TaskExtensions.cs
License : MIT License
Project Creator : AngelGarcia13
License : MIT License
Project Creator : AngelGarcia13
public static async void Await(this Task task, Action completedCallback, Action<Exception> errorCallBack)
{
try
{
await task;
completedCallback?.Invoke();
}
catch (Exception exception)
{
errorCallBack?.Invoke(exception);
}
}
19
View Source File : BlogLogAOP.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static async Task<T> AwaitTaskWithPostActionAndFinallyAndGetResult<T>(Task<T> actualReturnValue, Func<object, Task> postAction, Action<Exception> finalAction)
{
Exception exception = null;
try
{
var result = await actualReturnValue;
await postAction(result);
return result;
}
catch (Exception ex)
{
exception = ex;
throw;
}
finally
{
finalAction(exception);
}
}
19
View Source File : BlogLogAOP.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static async Task AwaitTaskWithPostActionAndFinally(Task actualReturnValue, Func<Task> postAction, Action<Exception> finalAction)
{
Exception exception = null;
try
{
await actualReturnValue;
await postAction();
}
catch (Exception ex)
{
exception = ex;
}
finally
{
finalAction(exception);
}
}
19
View Source File : BlogLogAOP.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static async Task<T> AwaitTaskWithPostActionAndFinallyAndGetResult<T>(Task<T> actualReturnValue, Func<Task> postAction, Action<Exception> finalAction)
{
Exception exception = null;
try
{
var result = await actualReturnValue;
await postAction();
return result;
}
catch (Exception ex)
{
exception = ex;
throw;
}
finally
{
finalAction(exception);
}
}
19
View Source File : TaskHelper.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal
License : GNU Affero General Public License v3.0
Project Creator : asmejkal
public static void FireForget(Func<Task> action, Action<Exception> handler = null)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
var task = Task.Run(action);
if (handler == null)
{
task.ContinueWith(
DefaultErrorContinuation,
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
}
else
{
task.ContinueWith(
t => handler(t.Exception.GetBaseException()),
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
}
}
19
View Source File : Retry.cs
License : Apache License 2.0
Project Creator : asynkron
License : Apache License 2.0
Project Creator : asynkron
public static async Task<T> TryUntil<T>(Func<Task<T>> body, Func<T?,bool> condition, int retryCount = 10, int backoffMilliSeconds = 100, int maxBackoffMilliseconds = 5000, Action<int,Exception>? onError=null, Action<Exception>? onFailed=null)
{
for (var i = 0; retryCount == 0 || i < retryCount; i++)
{
try
{
var res = await body();
if (condition(res))
{
return res;
}
}
catch (Exception x)
{
onError?.Invoke(i, x);
if (i == retryCount - 1)
{
onFailed?.Invoke(x);
throw new RetriesExhaustedException("Retried but failed", x);
}
var backoff = Math.Min(i * backoffMilliSeconds, maxBackoffMilliseconds);
await Task.Delay(backoff);
}
}
throw new RetriesExhaustedException("Retry condition was never met");
}
19
View Source File : Retry.cs
License : Apache License 2.0
Project Creator : asynkron
License : Apache License 2.0
Project Creator : asynkron
public static async Task<T> Try<T>(Func<Task<T>> body, int retryCount = 10, int backoffMilliSeconds = 100, int maxBackoffMilliseconds = 5000, Action<int,Exception>? onError=null, Action<Exception>? onFailed=null)
{
for (var i = 0; retryCount == 0 || i < retryCount; i++)
{
try
{
var res = await body();
return res;
}
catch(Exception x)
{
onError?.Invoke(i,x);
if (i == retryCount - 1)
{
onFailed?.Invoke(x);
throw new RetriesExhaustedException("Retried but failed", x);
}
var backoff = Math.Min(i * backoffMilliSeconds, maxBackoffMilliseconds);
await Task.Delay(backoff);
}
}
throw new RetriesExhaustedException("This should never happen...");
}
19
View Source File : Retry.cs
License : Apache License 2.0
Project Creator : asynkron
License : Apache License 2.0
Project Creator : asynkron
public static async Task Try(
Func<Task> body,
int retryCount = 10,
int backoffMilliSeconds = 100,
int maxBackoffMilliseconds = 5000,
Action<int, Exception>? onError = null,
Action<Exception>? onFailed = null,
bool ignoreFailure = false
)
{
for (var i = 0; retryCount == 0 || i < retryCount; i++)
{
try
{
await body();
return;
}
catch (Exception x)
{
onError?.Invoke(i, x);
if (i == retryCount - 1)
{
onFailed?.Invoke(x);
if (ignoreFailure)
return;
throw new RetriesExhaustedException("Retried but failed", x);
}
var backoff = Math.Min(i * backoffMilliSeconds, maxBackoffMilliseconds);
await Task.Delay(backoff);
}
}
throw new RetriesExhaustedException("This should never happen...");
}
19
View Source File : Rx.cs
License : Apache License 2.0
Project Creator : atifaziz
License : Apache License 2.0
Project Creator : atifaziz
public static IDisposable Subscribe<T>(this IObservable<T> source,
Action<T> onNext, Action<Exception> onError, Action onCompleted)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (onNext == null) throw new ArgumentNullException(nameof(onNext));
if (onError == null) throw new ArgumentNullException(nameof(onError));
if (onCompleted == null) throw new ArgumentNullException(nameof(onCompleted));
try
{
return source.Subscribe(Observer.Create(onNext, onError, onCompleted));
}
catch (Exception e)
{
onError(e);
return Disposable.Nop;
}
}
19
View Source File : Rx.cs
License : Apache License 2.0
Project Creator : atifaziz
License : Apache License 2.0
Project Creator : atifaziz
public void OnError(Exception error) => _onError?.Invoke(error);
19
View Source File : ActorFactoryRegistration.cs
License : MIT License
Project Creator : autofac
License : MIT License
Project Creator : autofac
public void RegisterActorFactory<TActor>(
ILifetimeScope container,
Type actorServiceType,
Func<ActorBase, IActorStateProvider, IActorStateManager> stateManagerFactory = null,
IActorStateProvider stateProvider = null,
ActorServiceSettings settings = null,
object lifetimeScopeTag = null)
where TActor : ActorBase
{
ActorRuntime.RegisterActorAsync<TActor>((context, actorTypeInfo) =>
{
ActorBase ActorFactory(ActorService actorService, ActorId actorId)
{
var tag = lifetimeScopeTag ?? Constants.DefaultLifetimeScopeTag;
var lifetimeScope = container.BeginLifetimeScope(tag, builder =>
{
builder.RegisterInstance(context)
.As<StatefulServiceContext>()
.As<ServiceContext>();
builder.RegisterInstance(actorService)
.As<ActorService>();
builder.RegisterInstance(actorId)
.As<ActorId>();
ConfigurationAction(builder);
});
try
{
var actor = lifetimeScope.Resolve<TActor>();
return actor;
}
catch (Exception ex)
{
// Proactively dispose lifetime scope as interceptor will not be called.
lifetimeScope.Dispose();
ConstructorExceptionCallback(ex);
throw;
}
}
return (ActorService)container.Resolve(
actorServiceType,
new TypedParameter(typeof(StatefulServiceContext), context),
new TypedParameter(typeof(ActorTypeInformation), actorTypeInfo),
new TypedParameter(typeof(Func<ActorService, ActorId, ActorBase>), (Func<ActorService, ActorId, ActorBase>)ActorFactory),
new TypedParameter(typeof(Func<ActorBase, IActorStateProvider, IActorStateManager>), stateManagerFactory),
new TypedParameter(typeof(IStateProvider), stateProvider),
new TypedParameter(typeof(ActorServiceSettings), settings));
}).GetAwaiter().GetResult();
}
19
View Source File : StatefulServiceFactoryRegistration.cs
License : MIT License
Project Creator : autofac
License : MIT License
Project Creator : autofac
public void RegisterStatefulServiceFactory<TService>(
ILifetimeScope container, string serviceTypeName, object lifetimeScopeTag = null)
where TService : StatefulServiceBase
{
ServiceRuntime.RegisterServiceAsync(serviceTypeName, context =>
{
var tag = lifetimeScopeTag ?? Constants.DefaultLifetimeScopeTag;
var lifetimeScope = container.BeginLifetimeScope(tag, builder =>
{
builder.RegisterInstance(context)
.As<StatefulServiceContext>()
.As<ServiceContext>();
ConfigurationAction(builder);
});
try
{
var service = lifetimeScope.Resolve<TService>();
return service;
}
catch (Exception ex)
{
// Proactively dispose lifetime scope as interceptor will not be called.
lifetimeScope.Dispose();
ConstructorExceptionCallback(ex);
throw;
}
}).GetAwaiter().GetResult();
}
19
View Source File : StatelessServiceFactoryRegistration.cs
License : MIT License
Project Creator : autofac
License : MIT License
Project Creator : autofac
public void RegisterStatelessServiceFactory<TService>(
ILifetimeScope container, string serviceTypeName, object lifetimeScopeTag = null)
where TService : StatelessService
{
ServiceRuntime.RegisterServiceAsync(serviceTypeName, context =>
{
var tag = lifetimeScopeTag ?? Constants.DefaultLifetimeScopeTag;
var lifetimeScope = container.BeginLifetimeScope(tag, builder =>
{
builder.RegisterInstance(context)
.As<StatelessServiceContext>()
.As<ServiceContext>();
ConfigurationAction(builder);
});
try
{
var service = lifetimeScope.Resolve<TService>();
return service;
}
catch (Exception ex)
{
// Proactively dispose lifetime scope as interceptor will not be called.
lifetimeScope.Dispose();
ConstructorExceptionCallback(ex);
throw;
}
}).GetAwaiter().GetResult();
}
19
View Source File : SourceInjectedQuery.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public IEnumerator<TDestination> GetEnumerator()
{
try
{
var results = Provider.Execute<IEnumerable<TDestination>>(Expression).Cast<object>().ToArray();
EnumerationHandler(results);
return results.Cast<TDestination>().GetEnumerator();
}
catch (Exception x)
{
_exceptionHandler(x);
throw;
}
}
19
View Source File : SourceInjectedQueryProvider.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public object Execute(Expression expression)
{
try
{
Inspector.StartQueryExecuteInterceptor(null, expression);
var sourceExpression = ConvertDestinationExpressionToSourceExpression(expression);
var sourceResult = InvokeSourceQuery(null, sourceExpression);
Inspector.SourceResult(sourceExpression, sourceResult);
return sourceResult;
}
catch (Exception x)
{
_exceptionHandler(x);
throw;
}
}
19
View Source File : SourceInjectedQueryProvider.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public TResult Execute<TResult>(Expression expression)
{
try
{
var resultType = typeof(TResult);
Inspector.StartQueryExecuteInterceptor(resultType, expression);
var sourceExpression = ConvertDestinationExpressionToSourceExpression(expression);
var destResultType = typeof(TResult);
var sourceResultType = CreateSourceResultType(destResultType);
object destResult = null;
// case #1: query is a projection from complex Source to complex Destination
// example: users.UseAsDataSource().For<UserDto>().Where(x => x.Age > 20).ToList()
if (IsProjection<TDestination>(resultType))
{
// in case of a projection, we need an IQueryable
var sourceResult = _dataSource.Provider.CreateQuery(sourceExpression);
Inspector.SourceResult(sourceExpression, sourceResult);
var queryExpressions = _mapper.ConfigurationProvider.Internal().ProjectionBuilder.GetProjection
(
sourceResult.ElementType,
typeof(TDestination),
_parameters,
_membersToExpand.Select
(
m => new MemberPath
(
m.Distinct().ToArray()
)
).ToArray()
);
destResult = (IQueryable<TDestination>)GetMapExpressions(queryExpressions).Aggregate(sourceResult, Select);
}
// case #2: query is arbitrary ("manual") projection
// exaple: users.UseAsDataSource().For<UserDto>().Select(user => user.Age).ToList()
// in case an arbitrary select-statement is enumerated, we do not need to map the expression at all
// and cann safely return it
else if (IsProjection(resultType, sourceExpression))
{
var sourceResult = _dataSource.Provider.CreateQuery(sourceExpression);
var enumerator = sourceResult.GetEnumerator();
var elementType = ElementTypeHelper.GetElementType(typeof(TResult));
var constructorInfo = typeof(List<>).MakeGenericType(elementType).GetDeclaredConstructor(new Type[0]);
if (constructorInfo != null)
{
var listInstance = (IList)constructorInfo.Invoke(null);
while (enumerator.MoveNext())
{
listInstance.Add(enumerator.Current);
}
destResult = listInstance;
}
}
// case #2: projection to simple type
// example: users.UseAsDataSource().For<UserDto>().FirstOrDefault(user => user.Age > 20)
else
{
/*
in case of an element result (so instead of IQueryable<TResult>, just TResult)
we still want to support parameters.
This is e.g. the case, when the developer writes "UseAsDataSource().For<TResult>().FirstOrDefault(x => ...)
To still be able to support parameters, we need to create a query from it.
That said, we need to replace the "element" operator "FirstOrDefault" with a "Where" operator, then apply our "Select"
to map from TSource to TResult and finally re-apply the "element" operator ("FirstOrDefault" in our case) so only
one element is returned by our "Execute<TResult>" method. Otherwise we'd get an InvalidCastException
* So first we visit the sourceExpression and replace "element operators" with "where"
* then we create our mapping expression from TSource to TDestination (select) and apply it
* finally, we search for the element expression overload of our replaced "element operator" that has no expression as parameter
this expression is not needed anymore as it has already been applied to the "Where" operation and can be safely omitted
* when we're done creating our new expression, we call the underlying provider to execute it
*/
// as we need to replace the innermost element of the expression,
// we need to traverse it first in order to find the node to replace or potential caveats
// e.g. .UseAsDataSource().For<Dto>().Select(e => e.Name).First()
// in the above case we cannot map anymore as the "select" operator overrides our mapping.
var searcher = new ReplaceableMethodNodeFinder<TSource>();
searcher.Visit(sourceExpression);
// provide the replacer with our found MethodNode or <null>
var replacer = new MethodNodeReplacer<TSource>(searcher.MethodNode);
// default back to simple mapping of object instance for backwards compatibility (e.g. mapping non-nullable to nullable fields)
sourceExpression = replacer.Visit(sourceExpression);
if (replacer.FoundElementOperator)
{
/* in case of primitive element operators (e.g. Any(), Sum()...)
we need to map the originating types (e.g. Enreplacedy to Dto) in this query
as the final value will be projected automatically
== example 1 ==
UseAsDataSource().For<Dto>().Any(enreplacedy => enreplacedy.Name == "thename")
..in that case sourceResultType and destResultType would both be "Boolean" which is not mappable for AutoMapper
== example 2 ==
UseAsDataSource().For<Dto>().FirstOrDefault(enreplacedy => enreplacedy.Name == "thename")
..in this case the sourceResultType would be Enreplacedy and the destResultType Dto, so we can map the query directly
*/
if (sourceResultType == destResultType)// && destResultType.IsPrimitive)
{
sourceResultType = typeof(TSource);
destResultType = typeof(TDestination);
}
var queryExpressions = _mapper.ConfigurationProvider.Internal().ProjectionBuilder.GetProjection
(
sourceResultType,
destResultType,
_parameters,
_membersToExpand.Select
(
m => new MemberPath
(
m.Distinct().ToArray()
)
).ToArray()
);
// add projection via "select" operator
var expr = GetMapExpressions(queryExpressions).Aggregate(sourceExpression, (source, lambda) => Select(source, lambda));
// in case an element operator without predicate expression was found (and thus not replaced)
var replacementMethod = replacer.ElementOperator;
// in case an element operator with predicate expression was replaced
if (replacer.ReplacedMethod != null)
{
// find replacement method that has no more predicates
replacementMethod = typeof(Queryable).GetAllMethods()
.Single(m => m.Name == replacer.ReplacedMethod.Name
#if NET45
&& m.GetParameters().All(p => typeof(Queryable).IsreplacedignableFrom(p.Member.ReflectedType))
#endif
&& m.GetParameters().Length == replacer.ReplacedMethod.GetParameters().Length - 1);
}
// reintroduce element operator that was replaced with a "where" operator to make it queryable
expr = Call(null,
replacementMethod.MakeGenericMethod(destResultType), expr);
destResult = _dataSource.Provider.Execute(expr);
}
// If there was no element operator that needed to be replaced by "where", just map the result
else
{
var sourceResult = _dataSource.Provider.Execute(sourceExpression);
Inspector.SourceResult(sourceExpression, sourceResult);
destResult = _mapper.Map(sourceResult, sourceResultType, destResultType);
}
}
Inspector.DestResult(destResult);
// implicitly convert types in case of valuetypes which cannot be casted explicitly
if (typeof(TResult).IsValueType() && destResult?.GetType() != typeof(TResult))
return (TResult)System.Convert.ChangeType(destResult, typeof(TResult));
// if it is not a valuetype, we can safely cast it
return (TResult)destResult;
}
catch (Exception x)
{
_exceptionHandler(x);
throw;
}
}
19
View Source File : BusinessInvokerBase.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
protected override void WrapInvoke(object caller, Action action, BusinessInvokerArgs? param = null, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0)
{
Check.NotNull(action, nameof(action));
BusinessInvokerArgs bia = param ?? BusinessInvokerArgs.Default;
TransactionScope? txn = null;
OperationType ot = ExecutionContext.Current.OperationType;
if (bia.OperationType.HasValue)
ExecutionContext.Current.OperationType = bia.OperationType.Value;
try
{
if (bia.IncludeTransactionScope)
txn = new TransactionScope(bia.TransactionScopeOption, TransactionScopeAsyncFlowOption.Enabled);
action();
txn?.Complete();
}
catch (Exception ex)
{
bia.ExceptionHandler?.Invoke(ex);
throw;
}
finally
{
txn?.Dispose();
ExecutionContext.Current.OperationType = ot;
}
}
19
View Source File : BusinessInvokerBase.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
protected async override Task WrapInvokeAsync(object caller, Func<Task> func, BusinessInvokerArgs? param = null, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0)
{
Check.NotNull(func, nameof(func));
BusinessInvokerArgs bia = param ?? BusinessInvokerArgs.Default;
TransactionScope? txn = null;
OperationType ot = ExecutionContext.Current.OperationType;
if (bia.OperationType.HasValue)
ExecutionContext.Current.OperationType = bia.OperationType.Value;
try
{
if (bia.IncludeTransactionScope)
txn = new TransactionScope(bia.TransactionScopeOption, TransactionScopeAsyncFlowOption.Enabled);
await func().ConfigureAwait(false);
txn?.Complete();
}
catch (Exception ex)
{
bia.ExceptionHandler?.Invoke(ex);
throw;
}
finally
{
txn?.Dispose();
ExecutionContext.Current.OperationType = ot;
}
}
See More Examples