Here are the examples of the csharp api System.Threading.Tasks.TaskCompletionSource.TrySetResult(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
611 Examples
19
Source : LifetimeManager.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
public void Signal()
{
lock (ThisLock)
{
if (_closed)
{
return;
}
_tcs.TrySetResult(true);
}
}
19
Source : LifetimeManager.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
internal static void WaiterTimeout(object state)
{
var tcs = state as TaskCompletionSource<bool>;
tcs?.TrySetResult(false);
}
19
Source : TaskHelpers.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
private static void OnAsyncCompletion(object state)
{
var tcs = state as TaskCompletionSource<bool>;
Fx.replacedert(tcs != null, "Async state should be of type TaskCompletionSource<bool>");
tcs.TrySetResult(true);
}
19
Source : AsyncManualResetEvent.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
private static void TokenCancelledCallback(object obj)
{
var localTcs = obj as TaskCompletionSource<bool>;
localTcs?.TrySetResult(false);
}
19
Source : AsyncManualResetEvent.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
public void Set()
{
CheckDisposed();
_tcs?.TrySetResult(true);
}
19
Source : AsyncManualResetEvent.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
public void Dispose()
{
TaskCompletionSource<bool> tcs = Interlocked.Exchange(ref _tcs, null);
tcs?.TrySetResult(false);
}
19
Source : FixedChannelPool.cs
with MIT License
from cuteant
with MIT License
from cuteant
async void Release0(object channel, object promise)
{
var tsc = promise as TaskCompletionSource<bool>;
try
{
var result = await DoReleaseAsync((IChannel)channel);
_ = tsc.TrySetResult(result);
}
catch (Exception ex)
{
_ = tsc.TrySetException(ex);
}
}
19
Source : AbstractChannelPoolMap.cs
with MIT License
from cuteant
with MIT License
from cuteant
private Task<bool> RemoveAsyncIfSupported(TKey key)
{
if (key is null) { return ThrowHelper.FromArgumentNullException<bool>(ExceptionArgument.key); }
if (_map.TryRemove(key, out TPool pool))
{
var removePromise = new TaskCompletionSource<bool>();
PoolCloseAsyncIfSupported(pool).ContinueWith((t, s) =>
{
if (t.IsSuccess())
{
((TaskCompletionSource<bool>)s).TrySetResult(true);
}
else
{
((TaskCompletionSource<bool>)s).TrySetException(TaskUtil.Unwrap(t.Exception));
}
},
removePromise
#if !NET451
, TaskContinuationOptions.RunContinuationsAsynchronously
#endif
);
return removePromise.Task;
}
return TaskUtil.False;
}
19
Source : SimpleChannelPool.cs
with MIT License
from cuteant
with MIT License
from cuteant
async void DoReleaseChannel(object channel, object state)
{
var promise = state as TaskCompletionSource<bool>;
try
{
var result = await DoReleaseChannel((IChannel)channel);
_ = promise.TrySetResult(result);
}
catch (Exception ex)
{
_ = promise.TrySetException(ex);
}
}
19
Source : ChannelListenerTest.cs
with MIT License
from CyAScott
with MIT License
from CyAScott
public async void ThreadTest(
CancellationToken cancel,
DummyClreplaced remoteInstance,
ConcurrentBag<Guid> values,
TaskCompletionSource<bool> onFinish)
{
try
{
await Task.Yield();
var cancelTask = new TaskCompletionSource<bool>();
var ids = Enumerable.Range(0, 1000).Select(_ => Guid.NewGuid()).ToArray();
var rnd = new Random();
cancel.Register(() => cancelTask.TrySetResult(true));
foreach (var value in ids.TakeWhile(_ => !cancel.IsCancellationRequested))
{
await Task.Yield();
Thread.SpinWait(rnd.Next(1, 1000));
if (cancel.IsCancellationRequested)
{
break;
}
values.Add(value);
var task = remoteInstance.SetValue(value);
await Task.WhenAny(cancelTask.Task, task).ConfigureAwait(false);
}
onFinish.TrySetResult(true);
}
catch (Exception error)
{
onFinish.TrySetException(error);
}
}
19
Source : ConnectionTests.cs
with MIT License
from CyAScott
with MIT License
from CyAScott
[Test]
public async Task MultipleChannelsTest()
{
var (parent, child) = MakeConnections();
using (var cancel = new CancellationTokenSource(Debugger.IsAttached ? TimeSpan.FromDays(1) : TimeSpan.FromMinutes(1)))
using (child)
using (parent)
{
const int numberOfChannels = 10;
var newChannels = new ConcurrentDictionary<long, MockChannel>();
var newChannel = new TaskCompletionSource<bool>();
cancel.Token.Register(() => newChannel.TrySetCanceled(cancel.Token));
child.NewChannel += (domains, channel) =>
{
newChannels[((IInternalChannel)channel).Id] = (MockChannel)channel;
if (newChannels.Count >= numberOfChannels)
{
newChannel.TrySetResult(true);
}
};
//create new channels
await Task.WhenAll(Enumerable.Range(0, numberOfChannels).Select(_ => parent.CreateInstance(typeof(DummyClreplaced).GetConstructors().First(), true))).ConfigureAwait(false);
//wait for the channels to init on the client
await newChannel.Task.ConfigureAwait(false);
var channelPairs = parent.Cast<MockChannel>()
.Select(parentSideChannel => new
{
childSideChannel = newChannels[parentSideChannel.Id],
parentSideChannel
})
.ToArray();
await Task.WhenAll(channelPairs.Select(async pair =>
{
//validate init data was exchanged
var dataCopy = new byte[16];
replacedert.AreEqual(dataCopy.Length, await pair.childSideChannel.Buffer.ReadAsync(dataCopy, 0, 16, cancel.Token).ConfigureAwait(false));
replacedert.AreEqual(pair.parentSideChannel.InitBytes, new Guid(dataCopy.ToArray()));
await VerifyConnectionIsDuplexed(child, parent, cancel, pair.childSideChannel, pair.parentSideChannel).ConfigureAwait(false);
})).ConfigureAwait(false);
}
}
19
Source : ConnectionTests.cs
with MIT License
from CyAScott
with MIT License
from CyAScott
[Test]
public async Task StressTest()
{
var (parent, child) = MakeConnections();
using (var cancel = new CancellationTokenSource(Debugger.IsAttached ? TimeSpan.FromDays(1) : TimeSpan.FromMinutes(1)))
using (child)
using (parent)
{
const int numberOfChannels = 10;
var newChannels = new ConcurrentDictionary<long, MockChannel>();
var newChannel = new TaskCompletionSource<bool>();
cancel.Token.Register(() => newChannel.TrySetCanceled(cancel.Token));
child.NewChannel += (domains, channel) =>
{
newChannels[((IInternalChannel)channel).Id] = (MockChannel)channel;
if (newChannels.Count >= numberOfChannels)
{
newChannel.TrySetResult(true);
}
};
//create new channels
await Task.WhenAll(Enumerable.Range(0, numberOfChannels).Select(_ => parent.CreateInstance(typeof(DummyClreplaced).GetConstructors().First(), true))).ConfigureAwait(false);
//wait for the channels to init on the client
await newChannel.Task.ConfigureAwait(false);
var channelPairs = parent.Cast<MockChannel>()
.Select(parentSideChannel => new
{
childSideChannel = newChannels[parentSideChannel.Id],
parentSideChannel,
task = new TaskCompletionSource<bool>()
})
.ToArray();
await Task.WhenAll(channelPairs.Select(async pair =>
{
//validate init data was exchanged
var dataCopy = new byte[16];
replacedert.AreEqual(dataCopy.Length, await pair.childSideChannel.Buffer.ReadAsync(dataCopy, 0, 16, cancel.Token).ConfigureAwait(false));
replacedert.AreEqual(pair.parentSideChannel.InitBytes, new Guid(dataCopy.ToArray()));
})).ConfigureAwait(false);
foreach (var pair in channelPairs)
{
VerifyConnectionIsDuplexed(child, parent, cancel, pair.childSideChannel, pair.parentSideChannel, pair.task);
}
await Task.WhenAll(channelPairs.Select(pair => pair.task.Task)).ConfigureAwait(false);
}
}
19
Source : ConnectionTests.cs
with MIT License
from CyAScott
with MIT License
from CyAScott
internal static async void VerifyConnectionIsDuplexed(
IConnection child, IConnection parent,
CancellationTokenSource cancel,
MockChannel childSideChannel, MockChannel parentSideChannel,
TaskCompletionSource<bool> task)
{
await Task.Yield();
try
{
var rnd = new Random();
for (var index = 0; index < 1000 && !cancel.IsCancellationRequested; index++)
{
await Task.Yield();
Thread.SpinWait(rnd.Next(1, 1000));
if (cancel.IsCancellationRequested)
{
break;
}
await VerifyConnectionIsDuplexed(child, parent, cancel, childSideChannel, parentSideChannel).ConfigureAwait(false);
}
task.TrySetResult(true);
}
catch (Exception error)
{
task.TrySetException(error);
}
}
19
Source : TaskCompletion.cs
with Apache License 2.0
from danielmarbach
with Apache License 2.0
from danielmarbach
public async Task Run()
{
var taskCompletionSource = new TaskCompletionSource<bool>();
var simulator = new Simulator();
simulator.Fired += (sender, args) => taskCompletionSource.TrySetResult(true);
this.PrintStart();
simulator.Start();
await taskCompletionSource.Task.ConfigureAwait(false);
this.PrintEnd();
}
19
Source : Helpers.cs
with GNU General Public License v3.0
from Dantes-Dungeon
with GNU General Public License v3.0
from Dantes-Dungeon
public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
{
if (task != await Task.WhenAny(task, tcs.Task))
{
throw new OperationCanceledException(cancellationToken);
}
}
return await task;
}
19
Source : MainController.cs
with MIT License
from dgarage
with MIT License
from dgarage
[Route("cryptos/{cryptoCode}/events")]
public async Task<JArray> GetEvents(string cryptoCode, int lastEventId = 0, int? limit = null, bool longPolling = false, CancellationToken cancellationToken = default)
{
if (limit != null && limit.Value < 1)
throw new NBXplorerError(400, "invalid-limit", "limit should be more than 0").AsException();
var network = GetNetwork(cryptoCode, false);
TaskCompletionSource<bool> waitNextEvent = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
Action<NewEventBase> maySetNextEvent = (NewEventBase ev) =>
{
if (ev.CryptoCode == network.CryptoCode)
waitNextEvent.TrySetResult(true);
};
using (CompositeDisposable subscriptions = new CompositeDisposable())
{
subscriptions.Add(_EventAggregator.Subscribe<NewBlockEvent>(maySetNextEvent));
subscriptions.Add(_EventAggregator.Subscribe<NewTransactionEvent>(maySetNextEvent));
retry:
var repo = RepositoryProvider.GetRepository(network);
var result = await repo.GetEvents(lastEventId, limit);
if (result.Count == 0 && longPolling)
{
try
{
await waitNextEvent.Task.WithCancellation(cancellationToken);
goto retry;
}
catch when (cancellationToken.IsCancellationRequested)
{
}
}
return new JArray(result.Select(o => o.ToJObject(repo.Serializer.Settings)));
}
}
19
Source : AddressPoolService.cs
with MIT License
from dgarage
with MIT License
from dgarage
private async Task Listen(CancellationToken cancellationToken)
{
while (await _Channel.Reader.WaitToReadAsync(cancellationToken))
{
RefillPoolRequest modelItem = null;
try
{
_Channel.Reader.TryRead(out modelItem);
if (modelItem == null)
continue;
var c = await _Repository.GenerateAddresses(modelItem.DerivationStrategy, modelItem.Feature, modelItem.GenerateAddressQuery);
modelItem.Done?.TrySetResult(true);
}
catch (Exception ex)
{
modelItem?.Done.TrySetException(ex);
Logs.Explorer.LogError(ex, $"{_Repository.Network.CryptoCode}: Error in the Listen of the AddressPoolService");
await Task.Delay(1000, cancellationToken);
}
}
}
19
Source : MailDemonExtensionMethods.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
public static async Task<bool> WaitOneAsync(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
{
RegisteredWaitHandle registeredHandle = null;
CancellationTokenRegistration tokenRegistration = default;
try
{
var tcs = new TaskCompletionSource<bool>();
registeredHandle = ThreadPool.RegisterWaitForSingleObject(
handle,
(state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
tcs,
timeout,
true);
tokenRegistration = cancellationToken.Register(
state => ((TaskCompletionSource<bool>)state).TrySetCanceled(),
tcs);
return await tcs.Task;
}
finally
{
if (registeredHandle != null)
{
registeredHandle.Unregister(null);
}
tokenRegistration.Dispose();
}
}
19
Source : WumpusGatewayClient.cs
with MIT License
from discord-net
with MIT License
from discord-net
private void HandleDispatchEvent(GatewayPayload evnt, TaskCompletionSource<bool> readySignal)
{
switch (evnt.DispatchType)
{
case GatewayDispatchType.Ready:
var readyEvent = evnt.Data as ReadyEvent;
SetSession(readyEvent.SessionId);
readySignal.TrySetResult(true);
Ready?.Invoke(readyEvent);
break;
case GatewayDispatchType.Resumed:
readySignal.TrySetResult(true);
Resumed?.Invoke();
break;
case GatewayDispatchType.GuildCreate: GuildCreate?.Invoke(evnt.Data as GatewayGuild); break;
case GatewayDispatchType.GuildUpdate: GuildUpdate?.Invoke(evnt.Data as Guild); break;
case GatewayDispatchType.GuildDelete: GuildDelete?.Invoke(evnt.Data as UnavailableGuild); break;
case GatewayDispatchType.ChannelCreate: ChannelCreate?.Invoke(evnt.Data as Channel); break;
case GatewayDispatchType.ChannelUpdate: ChannelUpdate?.Invoke(evnt.Data as Channel); break;
case GatewayDispatchType.ChannelDelete: ChannelDelete?.Invoke(evnt.Data as Channel); break;
case GatewayDispatchType.ChannelPinsUpdate: ChannelPinsUpdate?.Invoke(evnt.Data as ChannelPinsUpdateEvent); break;
case GatewayDispatchType.GuildMemberAdd: GuildMemberAdd?.Invoke(evnt.Data as GuildMemberAddEvent); break;
case GatewayDispatchType.GuildMemberUpdate: GuildMemberUpdate?.Invoke(evnt.Data as GuildMemberUpdateEvent); break;
case GatewayDispatchType.GuildMemberRemove: GuildMemberRemove?.Invoke(evnt.Data as GuildMemberRemoveEvent); break;
case GatewayDispatchType.GuildMembersChunk: GuildMembersChunk?.Invoke(evnt.Data as GuildMembersChunkEvent); break;
case GatewayDispatchType.GuildRoleCreate: GuildRoleCreate?.Invoke(evnt.Data as GuildRoleCreateEvent); break;
case GatewayDispatchType.GuildRoleUpdate: GuildRoleUpdate?.Invoke(evnt.Data as GuildRoleUpdateEvent); break;
case GatewayDispatchType.GuildRoleDelete: GuildRoleDelete?.Invoke(evnt.Data as GuildRoleDeleteEvent); break;
case GatewayDispatchType.GuildBanAdd: GuildBanAdd?.Invoke(evnt.Data as GuildBanAddEvent); break;
case GatewayDispatchType.GuildBanRemove: GuildBanRemove?.Invoke(evnt.Data as GuildBanRemoveEvent); break;
case GatewayDispatchType.GuildEmojisUpdate: GuildEmojisUpdate?.Invoke(evnt.Data as GuildEmojiUpdateEvent); break;
case GatewayDispatchType.GuildIntegrationsUpdate: GuildIntegrationsUpdate?.Invoke(evnt.Data as GuildIntegrationsUpdateEvent); break;
case GatewayDispatchType.MessageCreate: MessageCreate?.Invoke(evnt.Data as Message); break;
case GatewayDispatchType.MessageUpdate: MessageUpdate?.Invoke(evnt.Data as Message); break;
case GatewayDispatchType.MessageDelete: MessageDelete?.Invoke(evnt.Data as MessageDeleteEvent); break;
case GatewayDispatchType.MessageDeleteBulk: MessageDeleteBulk?.Invoke(evnt.Data as MessageDeleteBulkEvent); break;
case GatewayDispatchType.MessageReactionAdd: MessageReactionAdd?.Invoke(evnt.Data as MessageReactionAddEvent); break;
case GatewayDispatchType.MessageReactionRemove: MessageReactionRemove?.Invoke(evnt.Data as MessageReactionRemoveEvent); break;
case GatewayDispatchType.MessageReactionRemoveAll: MessageReactionRemoveAll?.Invoke(evnt.Data as MessageReactionRemoveAllEvent); break;
case GatewayDispatchType.PresenceUpdate: PresenceUpdate?.Invoke(evnt.Data as Presence); break;
case GatewayDispatchType.UserUpdate: UserUpdate?.Invoke(evnt.Data as User); break;
case GatewayDispatchType.TypingStart: TypingStart?.Invoke(evnt.Data as TypingStartEvent); break;
case GatewayDispatchType.VoiceStateUpdate: VoiceStateUpdate?.Invoke(evnt.Data as VoiceState); break;
case GatewayDispatchType.VoiceServerUpdate: VoiceServerUpdate?.Invoke(evnt.Data as VoiceServerUpdateEvent); break;
case GatewayDispatchType.WebhooksUpdate: WebhooksUpdate?.Invoke(evnt.Data as WebhooksUpdateEvent); break;
}
}
19
Source : WumpusGatewayClient.cs
with MIT License
from discord-net
with MIT License
from discord-net
private void HandleEvent(GatewayPayload evnt, TaskCompletionSource<bool> readySignal)
{
switch (evnt.Operation)
{
case GatewayOperation.Dispatch:
HandleDispatchEvent(evnt, readySignal);
break;
case GatewayOperation.InvalidSession:
if ((bool)evnt.Data != true) // Is resumable
SetSession(null);
readySignal.TrySetResult(false);
GatewayInvalidSession?.Invoke((bool)evnt.Data);
break;
case GatewayOperation.Heartbeat:
SendHeartbeatAck();
GatewayHeartbeat?.Invoke();
break;
case GatewayOperation.HeartbeatAck: GatewayHeartbeatAck?.Invoke(); break;
case GatewayOperation.Hello: GatewayHello?.Invoke(evnt.Data as HelloEvent); break;
case GatewayOperation.Reconnect: GatewayReconnect?.Invoke(); break;
}
}
19
Source : EventWaiter.cs
with MIT License
from dolittle
with MIT License
from dolittle
void RemoveAllAtAndBelowLocking(StreamPosition position)
{
lock (_lock)
{
var keys = _taskCompletionSources.Keys.ToArray();
foreach (var storedPosition in keys)
{
if (storedPosition.Value <= position.Value)
{
_taskCompletionSources[storedPosition].TrySetResult(true);
_taskCompletionSources.Remove(storedPosition);
}
else
{
break;
}
}
}
}
19
Source : GeneralUtils.cs
with MIT License
from dotnet
with MIT License
from dotnet
public static async Task<ProcessExecutionResult> RunProcessAndGetOutputsAsync(string path, string arguments)
{
ProcessStartInfo info = new ProcessStartInfo(path, arguments)
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8
};
Process process = new Process
{
StartInfo = info,
EnableRaisingEvents = true
};
var stdOut = new StringBuilder();
var stdErr = new StringBuilder();
var stdoutCompletion = new TaskCompletionSource<bool>();
var stderrCompletion = new TaskCompletionSource<bool>();
process.OutputDataReceived += (sender, e) =>
{
if (e.Data != null)
{
lock (stdOut)
{
stdOut.AppendLine(e.Data);
}
}
else
{
stdoutCompletion.TrySetResult(true);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data != null)
{
lock (stdErr)
{
stdErr.AppendLine(e.Data);
}
}
else
{
stderrCompletion.TrySetResult(true);
}
};
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
// Creates task to wait for process exit using timeout
await WaitForProcessExitAsync(process);
// Wait for the last outputs to flush before returning
System.Threading.Tasks.Task.WaitAll(new System.Threading.Tasks.Task[] { stderrCompletion.Task, stdoutCompletion.Task }, TimeSpan.FromSeconds(5));
return new ProcessExecutionResult()
{
ExitCode = process.ExitCode,
StandardOut = stdOut.ToString(),
StandardError = stdErr.ToString()
};
}
19
Source : TestHelpers.cs
with MIT License
from dotnet
with MIT License
from dotnet
public static async Task<string> RunExecutableAsyncWithInput(string executable, string input, params string[] args)
{
TestContext.WriteLine(FormatExecutableCall(executable, args));
var output = new StringBuilder();
void WriteOutput(string message)
{
if (message != null)
{
Debug.WriteLine(message);
output.AppendLine(message);
TestContext.WriteLine(message);
}
}
var psi = new ProcessStartInfo(executable)
{
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
};
foreach (string arg in args)
{
// The string append used by Process will accept null params
// and then throw without identifying the param, so we need to handle it here to get logging
if (arg != null)
{
psi.ArgumentList.Add(arg);
}
else
{
WriteOutput("Null parameter encountered while constructing command string.");
}
}
using var process = new Process
{
StartInfo = psi
};
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
process.EnableRaisingEvents = true;
process.Exited += (s, e) => { tcs.TrySetResult(true); };
process.Start();
Task<bool> exitTask = tcs.Task;
Task stdin = Task.Run(() => { process.StandardInput.Write(input); process.StandardInput.Close(); });
Task<string> stdout = process.StandardOutput.ReadLineAsync();
Task<string> stderr = process.StandardError.ReadLineAsync();
var list = new List<Task> { exitTask, stdout, stderr, stdin };
while (list.Count != 0)
{
var done = await Task.WhenAny(list);
list.Remove(done);
if (done == exitTask)
{
continue;
}
if (done == stdout)
{
var data = await stdout;
WriteOutput(data);
if (data != null)
{
list.Add(stdout = process.StandardOutput.ReadLineAsync());
}
continue;
}
if (done == stderr)
{
var data = await stderr;
WriteOutput(data);
if (data != null)
{
list.Add(stderr = process.StandardError.ReadLineAsync());
}
continue;
}
if (done == stdin)
{
await stdin;
continue;
}
throw new InvalidOperationException("Unexpected Task completed.");
}
if (process.ExitCode != 0)
{
MaestroTestException exceptionWithConsoleLog = new MaestroTestException($"{executable} exited with code {process.ExitCode}");
exceptionWithConsoleLog.Data.Add("ConsoleOutput", output.ToString());
throw exceptionWithConsoleLog;
}
return output.ToString();
}
19
Source : TcpSocket.cs
with MIT License
from dotnet
with MIT License
from dotnet
public async Task<bool> Connect(DnsRecord target, TimeSpan connectTimeout)
{
var tcs = new TaskCompletionSource<bool>();
using (var cts = new CancellationTokenSource(connectTimeout))
{
var connectTask = this.client.ConnectAsync(target.Target, target.Port);
using (cts.Token.Register(() => tcs.TrySetResult(true)))
{
if (connectTask != await Task.WhenAny(connectTask, tcs.Task).ConfigureAwait(false))
{
return false;
}
if (connectTask.Exception?.InnerException != null)
{
throw connectTask.Exception.InnerException;
}
}
}
this.TargetName = target.Target;
return true;
}
19
Source : DefaultClientNotifierService.cs
with MIT License
from dotnet
with MIT License
from dotnet
public override Task OnStarted(ILanguageServer server, CancellationToken cancellationToken)
{
_initializedCompletionSource.TrySetResult(true);
return Task.CompletedTask;
}
19
Source : ProcessManager.cs
with MIT License
from dotnet
with MIT License
from dotnet
protected static async Task<ProcessExecutionResult> RunAsyncInternal(
Process process,
ILog log,
ILog stdout,
ILog stderr,
Action<int, int> kill,
Func<ILog, int, IList<int>> getChildProcessIds,
TimeSpan? timeout = null,
Dictionary<string, string>? environmentVariables = null,
CancellationToken? cancellationToken = null,
bool? diagnostics = null)
{
var stdoutCompletion = new TaskCompletionSource<bool>();
var stderrCompletion = new TaskCompletionSource<bool>();
var result = new ProcessExecutionResult();
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
// Make cute emojiis show up as cute emojiis in the output instead of ugly text symbols!
process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
process.StartInfo.StandardErrorEncoding = Encoding.UTF8;
process.StartInfo.UseShellExecute = false;
if (environmentVariables != null)
{
foreach (var kvp in environmentVariables)
{
if (kvp.Value == null)
{
process.StartInfo.EnvironmentVariables.Remove(kvp.Key);
}
else
{
process.StartInfo.EnvironmentVariables[kvp.Key] = kvp.Value;
}
}
}
process.OutputDataReceived += (sender, e) =>
{
if (e.Data != null)
{
lock (stdout)
{
stdout.WriteLine(e.Data);
stdout.Flush();
}
}
else
{
stdoutCompletion.TrySetResult(true);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data != null)
{
lock (stderr)
{
stderr.WriteLine(e.Data);
stderr.Flush();
}
}
else
{
stderrCompletion.TrySetResult(true);
}
};
var sb = new StringBuilder();
sb.Append($"Running {StringUtils.Quote(process.StartInfo.FileName)} {process.StartInfo.Arguments}");
if (process.StartInfo.EnvironmentVariables != null)
{
var currentEnvironment = ToDictionary(Environment.GetEnvironmentVariables());
var processEnvironment = ToDictionary(process.StartInfo.EnvironmentVariables);
var allVariables = currentEnvironment.Keys.Union(processEnvironment.Keys).Distinct();
bool headerShown = false;
foreach (var variable in allVariables)
{
if (variable == null)
{
continue;
}
currentEnvironment.TryGetValue(variable, out var a);
processEnvironment.TryGetValue(variable, out var b);
if (a != b)
{
if (!headerShown)
{
sb.AppendLine().Append("With env vars: ");
headerShown = true;
}
sb.AppendLine().Append($" {variable} = '{StringUtils.Quote(b)}'");
}
}
}
// Separate process calls in logs
log.WriteLine(string.Empty);
log.WriteLine(sb.ToString());
process.Start();
var pid = process.Id;
process.BeginErrorReadLine();
process.BeginOutputReadLine();
cancellationToken?.Register(() =>
{
var hasExited = false;
try
{
hasExited = process.HasExited;
}
catch
{
// Process.HasExited can sometimes throw exceptions, so
// just ignore those and to be safe treat it as the
// process didn't exit (the safe option being to not leave
// processes behind).
}
if (!hasExited)
{
stderr.WriteLine($"Killing process {pid} as it was cancelled");
kill(pid, 9);
}
});
if (timeout.HasValue)
{
if (!await WaitForExitAsync(process, timeout.Value))
{
log.WriteLine($"Process {pid} didn't exit within {timeout} and will be killed");
await KillTreeAsync(pid, log, kill, getChildProcessIds, diagnostics ?? true);
result.TimedOut = true;
lock (stderr)
{
log.WriteLine($"{pid} Execution timed out after {timeout.Value.TotalSeconds} seconds and the process was killed.");
}
}
}
else
{
await WaitForExitAsync(process);
}
if (process.HasExited)
{
// make sure redirected output events are finished
process.WaitForExit();
}
Task.WaitAll(new Task[] { stderrCompletion.Task, stdoutCompletion.Task }, TimeSpan.FromSeconds(1));
try
{
result.ExitCode = process.ExitCode;
log.WriteLine($"Process {Path.GetFileName(process.StartInfo.FileName)} exited with {result.ExitCode}");
}
catch (Exception e)
{
result.ExitCode = 12345678;
log.WriteLine($"Failed to get ExitCode: {e}");
}
return result;
}
19
Source : ProcessManager.cs
with MIT License
from dotnet
with MIT License
from dotnet
private static async Task<bool> WaitForExitAsync(Process process, TimeSpan? timeout = null)
{
if (process.HasExited)
{
return true;
}
var tcs = new TaskCompletionSource<bool>();
void ProcessExited(object? sender, EventArgs ea)
{
process.Exited -= ProcessExited;
tcs.TrySetResult(true);
}
process.Exited += ProcessExited;
process.EnableRaisingEvents = true;
// Check if process exited again, in case it exited after we checked
// the last time, but before we attached the event handler.
if (process.HasExited)
{
process.Exited -= ProcessExited;
tcs.TrySetResult(true);
return true;
}
if (timeout.HasValue)
{
return await tcs.Task.TimeoutAfter(timeout.Value);
}
else
{
await tcs.Task;
return true;
}
}
19
Source : BlockingEnumerableCollection.cs
with MIT License
from dotnet
with MIT License
from dotnet
public void SetCompleted() => _completed.TrySetResult(true);
19
Source : SimpleListener.cs
with MIT License
from dotnet
with MIT License
from dotnet
protected void Connected(string remote)
{
// When app is in some crashing state, it might start connecting and disconnecting in a loop until we end up with an infinite log
// So logging only when the endpoint would change (which it shouldn't but we want to know)
if (_remoteAddress != remote)
{
_remoteAddress = remote;
Log.WriteLine("Connection from {0} saving logs to {1}", remote, TestLog.FullPath);
}
_connected.TrySetResult(true);
}
19
Source : SimpleListener.cs
with MIT License
from dotnet
with MIT License
from dotnet
protected void Finished(bool early_termination = false)
{
if (_stopped.TrySetResult(early_termination))
{
if (early_termination)
{
Log.WriteLine("Tests were terminated before completion");
}
else
{
Log.WriteLine("Tests have finished executing");
}
}
}
19
Source : TcpTunnel.cs
with MIT License
from dotnet
with MIT License
from dotnet
public void Open(string device, ITunnelListener simpleListener, TimeSpan timeout, ILog mainLog)
{
if (device == null)
{
throw new ArgumentNullException(nameof(device));
}
if (simpleListener == null)
{
throw new ArgumentNullException(nameof(simpleListener));
}
if (mainLog == null)
{
throw new ArgumentNullException(nameof(mainLog));
}
lock (_processExecutionLock)
{
// launch app, but do not await for the result, since we need to create the tunnel
var tcpArgs = new MlaunchArguments
{
new TcpTunnelArgument(simpleListener.Port),
new DeviceNameArgument(device),
};
// use a cancelation token, later will be used to kill the tcp tunnel process
_cancellationToken = new CancellationTokenSource();
mainLog.WriteLine($"Starting TCP tunnel between mac port: {simpleListener.Port} and device port {simpleListener.Port}");
Port = simpleListener.Port;
var tunnelbackLog = new CallbackLog((line) =>
{
mainLog.WriteLine($"[TCP tunnel] {line}");
if (line.Contains("Tcp tunnel started on device"))
{
mainLog.Write($"TCP tunnel created on port {simpleListener.Port}");
startedCompletionSource.TrySetResult(true);
simpleListener.TunnelHoleThrough.TrySetResult(true);
}
});
// do not await since we are going to be running the process in parallel
_tcpTunnelExecutionTask = _processManager.ExecuteCommandAsync(tcpArgs, tunnelbackLog, timeout, cancellationToken: _cancellationToken.Token);
_tcpTunnelExecutionTask.ContinueWith(delegate (Task<ProcessExecutionResult> task)
{
// if the task completes, means that we had issues with the creation of the tunnel and the process
// exited, if that is the case, we do not want to make the app wait, therefore, set the hole to false
// which will throw an exception from the listener.
simpleListener.TunnelHoleThrough.TrySetResult(task.Result.Succeeded);
});
}
}
19
Source : LimitedRunningCountTask.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
private async void RunningInner()
{
// ReSharper disable once InconsistentlySynchronizedField
if (_isRunning)
{
return;
}
lock (Locker)
{
if (_isRunning)
{
return;
}
_isRunning = true;
}
List<Task> runningTaskList;
lock (Locker)
{
runningTaskList = Buffer.ToList();
Buffer.Clear();
RunningBreakTask = new TaskCompletionSource<bool>();
runningTaskList.Add(RunningBreakTask.Task);
SetWaitForFreeTask();
}
while (runningTaskList.Count > 0)
{
// 加入等待
await Task.WhenAny(runningTaskList).ConfigureAwait(false);
// 干掉不需要的任务
runningTaskList.RemoveAll(task => task.IsCompleted);
lock (Locker)
{
runningTaskList.AddRange(Buffer);
Buffer.Clear();
RunningCount = runningTaskList.Count;
if (!RunningBreakTask.Task.IsCompleted)
{
runningTaskList.Add(RunningBreakTask.Task);
}
else
{
RunningBreakTask = new TaskCompletionSource<bool>();
runningTaskList.Add(RunningBreakTask.Task);
}
if (runningTaskList.Count < MaxRunningCount)
{
WaitForFreeTask?.TrySetResult(true);
}
else
{
SetWaitForFreeTask();
}
}
}
lock (Locker)
{
_isRunning = false;
}
void SetWaitForFreeTask()
{
if (runningTaskList.Count > MaxRunningCount)
{
if (WaitForFreeTask?.Task.IsCompleted is false)
{
}
else
{
WaitForFreeTask = new TaskCompletionSource<bool>();
}
}
}
}
19
Source : AsyncQueue.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
private void CurrentFinished(object sender, EventArgs e)
{
_currentFinishedTaskCompletionSource.TrySetResult(true);
}
19
Source : AsyncQueue.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
public void Dispose()
{
lock (_asyncQueue)
{
_currentFinishedTaskCompletionSource.TrySetResult(true);
_asyncQueue.CurrentFinished -= CurrentFinished;
}
}
19
Source : LimitedRunningCountTask.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
public void Add(Task task)
{
RunningCount++;
lock (Locker)
{
Buffer.Add(task);
RunningBreakTask?.TrySetResult(true);
}
RunningInner();
}
19
Source : ContactsService.cs
with MIT License
from dotnet9
with MIT License
from dotnet9
public static void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
if (requestCode == RequestContacts)
{
// We have requested multiple permissions for contacts, so all of them need to be
// checked.
if (PermissionUtil.VerifyPermissions(grantResults))
{
// All required permissions have been granted, display contacts fragment.
contactPermissionTcs.TrySetResult(true);
}
else
{
contactPermissionTcs.TrySetResult(false);
}
}
}
19
Source : ContactsService.cs
with MIT License
from dotnet9
with MIT License
from dotnet9
public async Task<bool> RequestPermissionAsync()
{
contactPermissionTcs = new TaskCompletionSource<bool>();
// Verify that all required contact permissions have been granted.
if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(CrossCurrentActivity.Current.Activity, Manifest.Permission.ReadContacts) != (int)Permission.Granted
|| Android.Support.V4.Content.ContextCompat.CheckSelfPermission(CrossCurrentActivity.Current.Activity, Manifest.Permission.WriteContacts) != (int)Permission.Granted)
{
// Contacts permissions have not been granted.
RequestContactsPermissions();
}
else
{
// Contact permissions have been granted.
contactPermissionTcs.TrySetResult(true);
}
return await contactPermissionTcs.Task;
}
19
Source : AsyncManualResetEvent.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public void Set()
{
var tcs = _tcs;
Task.Factory.StartNew(s => ((TaskCompletionSource<bool>)s).TrySetResult(true),
tcs, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default);
tcs.Task.Wait();
}
19
Source : ProtoBlock.cs
with MIT License
from Drawaes
with MIT License
from Drawaes
internal void Complete()
{
_task.TrySetResult(true);
}
19
Source : XFInAppBilling.android.cs
with MIT License
from EmilAlipiev
with MIT License
from EmilAlipiev
public void OnAcknowledgePurchaseResponse(BillingResult billingResult)
{
try
{
var isAcknowledged = billingResult.ResponseCode == BillingResponseCode.Ok;
var errorCode = GetErrorCode(billingResult.ResponseCode);
if (errorCode != null) //No error
{
_tcsAcknowledge?.TrySetException(errorCode);
}
else
{
_tcsAcknowledge?.TrySetResult(isAcknowledged);
}
}
catch (Exception ex)
{
_tcsAcknowledge?.TrySetException(ex);
}
}
19
Source : XFInAppBilling.android.cs
with MIT License
from EmilAlipiev
with MIT License
from EmilAlipiev
public void OnBillingSetupFinished(BillingResult billingResult)
{
try
{
if (billingResult.ResponseCode == BillingResponseCode.Ok)
{
_isServiceConnected = true;
_tcsConnect?.TrySetResult(_isServiceConnected);
}
else
{
var exception = GetErrorCode(billingResult.ResponseCode);
_tcsConnect?.TrySetException(exception);
}
}
catch (Exception ex)
{
_tcsConnect?.TrySetException(ex);
}
}
19
Source : ThriftMethodProcessor.cs
with Apache License 2.0
from endink
with Apache License 2.0
from endink
private Task<bool> CompleteMethodInvoke(Task<object> invokeTask, TProtocol outProtocol, int sequenceId, ContextChain contextChain, IRequestContext requestContext)
{
TaskCompletionSource<Boolean> resultFuture = new TaskCompletionSource<bool>();
invokeTask.ContinueWith(t =>
{
if (t.Exception == null)
{
var result = t.Result;
IRequestContext oldRequestContext = RequestContexts.GetCurrentContext();
RequestContexts.SetCurrentContext(requestContext);
// write success reply
try
{
contextChain.PreWrite(result);
WriteResponse(outProtocol,
sequenceId,
TMessageType.Reply,
"success",
(short)0,
_successCodec,
result);
contextChain.PostWrite(result);
resultFuture.TrySetResult(true);
}
catch (Exception e)
{
// An exception occurred trying to serialize a return value onto the output protocol
resultFuture.TrySetException(e);
}
finally
{
RequestContexts.SetCurrentContext(oldRequestContext);
}
}
else
{
IRequestContext oldRequestContext = RequestContexts.GetCurrentContext();
RequestContexts.SetCurrentContext(requestContext);
try
{
contextChain.PreWriteException(t.Exception);
ExceptionProcessor exceptionCodec;
if (!_exceptionCodecs.TryGetValue(t.Exception.GetType(), out exceptionCodec))
{
// In case the method throws a subtype of one of its declared
// exceptions, exact lookup will fail. We need to simulate it.
// (This isn't a problem for normal returns because there the
// output codec is decided in advance.)
foreach (var entry in _exceptionCodecs)
{
if (entry.Key.GetTypeInfo().IsreplacedignableFrom(t.Exception.GetType()))
{
exceptionCodec = entry.Value;
break;
}
}
}
if (exceptionCodec != null)
{
contextChain.DeclaredUserException(t.Exception, exceptionCodec.Codec);
// write expected exception response
WriteResponse(
outProtocol,
sequenceId,
TMessageType.Reply,
"exception",
exceptionCodec.Id,
exceptionCodec.Codec,
t);
contextChain.PostWriteException(t.Exception);
}
else
{
contextChain.UndeclaredUserException(t.Exception);
// unexpected exception
TApplicationException applicationException =
ThriftServiceProcessor.CreateAndWriteApplicationException(
outProtocol,
requestContext,
_method.Name,
sequenceId,
TApplicationException.ExceptionType.InternalError,
$"Internal error processing '{_method.Name}'.",
t.Exception,
_logger);
contextChain.PostWriteException(applicationException);
}
if (!_oneway) resultFuture.TrySetResult(true);
}
catch (Exception e)
{
// An exception occurred trying to serialize an exception onto the output protocol
resultFuture.TrySetException(e);
}
finally
{
RequestContexts.SetCurrentContext(oldRequestContext);
}
}
});
return resultFuture.Task;
}
19
Source : ThriftServiceProcessor.cs
with Apache License 2.0
from endink
with Apache License 2.0
from endink
public Task<bool> ProcessCoreAsync(TProtocol protocolIn, TProtocol protocolOut, IRequestContext requestContext, out String methodName, out int sequenceId)
{
TMessage message = protocolIn.ReadMessageBegin();
methodName = message.Name;
sequenceId = message.SeqID;
// lookup method
ThriftMethodProcessor method;
if (!this.Methods.TryGetValue(methodName, out method))
{
//TProtocolUtil.Skip(protocolIn, TType.Struct);
CreateAndWriteApplicationException(protocolOut,
requestContext, methodName,
sequenceId,
TApplicationException.ExceptionType.UnknownMethod,
$"Invalid method name: '{methodName}'",
null,
_logger);
return Task.FromResult(true);
}
switch (message.Type)
{
case TMessageType.Call:
case TMessageType.Oneway:
// Ideally we'd check the message type here to make the presence/absence of
// the "oneway" keyword annotating the method matches the message type.
// Unfortunately most clients send both one-way and two-way messages as CALL
// message type instead of using ONEWAY message type, and servers ignore the
// difference.
break;
default:
TProtocolUtil.Skip(protocolIn, TType.String);
CreateAndWriteApplicationException(protocolOut,
requestContext,
methodName,
sequenceId,
TApplicationException.ExceptionType.InvalidMessageType,
$"Received invalid message type {message.Type} from client",
null,
_logger);
return Task.FromResult(true);
}
TaskCompletionSource<Boolean> resultFuture = new TaskCompletionSource<bool>();
// invoke method
ContextChain context = new ContextChain(this._eventHandlers, method.QualifiedName, requestContext);
Task<Boolean> processResult = method.Process(protocolIn, protocolOut, sequenceId, context);
processResult.ContinueWith(task =>
{
if (task.Exception == null)
{
resultFuture.TrySetResult(task.Result);
}
else
{
_logger.LogError(default(EventId), task.Exception, $"Failed to process method [{method.QualifiedName}] of service [{method.ServiceName}].");
resultFuture.TrySetException(task.Exception);
}
});
return resultFuture.Task;
}
19
Source : UserPromptMessenger.cs
with Apache License 2.0
from Esri
with Apache License 2.0
from Esri
public Task<bool> AwaitConfirmation(string messagereplacedle, string message, bool isError, string stackTrace = null,
string affirmativeActionButtonContent = null, string negativeActionButtonContent = null, bool shouldCancel = false)
{
var taskCompletionSource = new TaskCompletionSource<bool>();
Instance.ResponseValueChanged += handler;
Instance.RaiseMessageValueChanged(messagereplacedle, message, isError, stackTrace, affirmativeActionButtonContent, negativeActionButtonContent);
void handler(object o, UserPromptResponseChangedEventArgs e)
{
{
Instance.ResponseValueChanged -= handler;
if (shouldCancel && !e.Response)
{
taskCompletionSource.TrySetCanceled();
}
else
{
taskCompletionSource.TrySetResult(e.Response);
}
}
}
return taskCompletionSource.Task;
}
19
Source : AppRating.android.cs
with MIT License
from FabriBertani
with MIT License
from FabriBertani
public void OnComplete(Com.Google.Android.Play.Core.Tasks.Task task)
{
if (!task.IsSuccessful)
{
inAppRateTCS.TrySetResult(false);
launchTask?.Dispose();
return;
}
if (Platform.CurrentActivity == null)
throw new NullReferenceException("Please ensure that you have installed Xamarin.Essential package and that it's initialized on your MainActivity.cs");
try
{
ReviewInfo reviewInfo = (ReviewInfo)task.GetResult(Java.Lang.Clreplaced.FromType(typeof(ReviewInfo)));
launchTask = reviewManager.LaunchReviewFlow(Platform.CurrentActivity, reviewInfo);
launchTask.AddOnCompleteListener(this);
}
catch (Exception ex)
{
ShowAlertMessage("ERROR", "There was an error launching in-app review. Please try again.");
inAppRateTCS.TrySetResult(false);
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
19
Source : CancellationTokenExtensions.cs
with MIT License
from fanliang11
with MIT License
from fanliang11
public static async Task<T> WithCancellation<T>(
this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
if (task != await Task.WhenAny(task, tcs.Task))
throw new TimeoutException();
return await task;
}
19
Source : FileOperationsHandler.cs
with GNU General Public License v3.0
from files-community
with GNU General Public License v3.0
from files-community
private async Task ParseFileOperationAsync(PipeStream connection, Dictionary<string, object> message)
{
switch (message.Get("fileop", ""))
{
case "GetFileHandle":
{
var filePath = (string)message["filepath"];
var readWrite = (bool)message["readwrite"];
using var hFile = Kernel32.CreateFile(filePath, Kernel32.FileAccess.GENERIC_READ | (readWrite ? Kernel32.FileAccess.GENERIC_WRITE : 0), FileShare.ReadWrite, null, FileMode.Open, FileFlagsAndAttributes.FILE_ATTRIBUTE_NORMAL);
if (hFile.IsInvalid)
{
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null));
return;
}
var processId = (int)(long)message["processid"];
using var uwpProces = System.Diagnostics.Process.GetProcessById(processId);
if (!Kernel32.DuplicateHandle(Kernel32.GetCurrentProcess(), hFile.DangerousGetHandle(), uwpProces.Handle, out var targetHandle, 0, false, Kernel32.DUPLICATE_HANDLE_OPTIONS.DUPLICATE_SAME_ACCESS))
{
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null));
return;
}
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", true },
{ "Handle", targetHandle.ToInt64() }
}, message.Get("RequestID", (string)null));
}
break;
case "Clipboard":
await Win32API.StartSTATask(() =>
{
System.Windows.Forms.Clipboard.Clear();
var fileToCopy = (string)message["filepath"];
var operation = (DataPackageOperation)(long)message["operation"];
var fileList = new System.Collections.Specialized.StringCollection();
fileList.AddRange(fileToCopy.Split('|'));
if (operation == DataPackageOperation.Copy)
{
System.Windows.Forms.Clipboard.SetFileDropList(fileList);
}
else if (operation == DataPackageOperation.Move)
{
byte[] moveEffect = new byte[] { 2, 0, 0, 0 };
MemoryStream dropEffect = new MemoryStream();
dropEffect.Write(moveEffect, 0, moveEffect.Length);
var data = new System.Windows.Forms.DataObject();
data.SetFileDropList(fileList);
data.SetData("Preferred DropEffect", dropEffect);
System.Windows.Forms.Clipboard.SetDataObject(data, true);
}
return true;
});
break;
case "DragDrop":
var dropPath = (string)message["droppath"];
var result = await Win32API.StartSTATask(() =>
{
var rdo = new RemoteDataObject(System.Windows.Forms.Clipboard.GetDataObject());
foreach (RemoteDataObject.DataPackage package in rdo.GetRemoteData())
{
try
{
if (package.ItemType == RemoteDataObject.StorageType.File)
{
string directoryPath = Path.GetDirectoryName(dropPath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
string uniqueName = Win32API.GenerateUniquePath(Path.Combine(dropPath, package.Name));
using (FileStream stream = new FileStream(uniqueName, FileMode.CreateNew))
{
package.ContentStream.CopyTo(stream);
}
}
else
{
string directoryPath = Path.Combine(dropPath, package.Name);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
}
finally
{
package.Dispose();
}
}
return true;
});
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", result } }, message.Get("RequestID", (string)null));
break;
case "CreateFile":
case "CreateFolder":
{
var filePath = (string)message["filepath"];
var template = message.Get("template", (string)null);
var dataStr = message.Get("data", (string)null);
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
op.Options = ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoConfirmMkDir
| ShellFileOperations.OperationFlags.RenameOnCollision
| ShellFileOperations.OperationFlags.NoErrorUI;
var shellOperationResult = new ShellOperationResult();
using var shd = new ShellFolder(Path.GetDirectoryName(filePath));
op.QueueNewItemOperation(shd, Path.GetFileName(filePath),
(string)message["fileop"] == "CreateFolder" ? FileAttributes.Directory : FileAttributes.Normal, template);
var createTcs = new TaskCompletionSource<bool>();
op.PostNewItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Destination = e.Desreplacedem?.FileSystemPath,
HRresult = (int)e.Result
});
};
op.FinishOperations += (s, e) => createTcs.TrySetResult(e.Result.Succeeded);
try
{
op.PerformOperations();
}
catch
{
createTcs.TrySetResult(false);
}
if (dataStr != null && (shellOperationResult.Items.SingleOrDefault()?.Succeeded ?? false))
{
Extensions.IgnoreExceptions(() =>
{
var dataBytes = Convert.FromBase64String(dataStr);
using (var fs = new FileStream(shellOperationResult.Items.Single().Destination, FileMode.Open))
{
fs.Write(dataBytes, 0, dataBytes.Length);
fs.Flush();
}
}, Program.Logger);
}
return (await createTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) }
}, message.Get("RequestID", (string)null));
}
break;
case "DeleteItem":
{
var fileToDeletePath = ((string)message["filepath"]).Split('|');
var permanently = (bool)message["permanently"];
var operationID = (string)message["operationID"];
var ownerHwnd = (long)message["HWND"];
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
op.Options = ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoConfirmation
| ShellFileOperations.OperationFlags.NoErrorUI;
op.OwnerWindow = Win32API.Win32Window.FromLong(ownerHwnd);
if (!permanently)
{
op.Options |= ShellFileOperations.OperationFlags.RecycleOnDelete
| ShellFileOperations.OperationFlags.WantNukeWarning;
}
var shellOperationResult = new ShellOperationResult();
for (var i = 0; i < fileToDeletePath.Length; i++)
{
using var shi = new ShellItem(fileToDeletePath[i]);
op.QueueDeleteOperation(shi);
}
progressHandler.OwnerWindow = op.OwnerWindow;
progressHandler.AddOperation(operationID);
var deleteTcs = new TaskCompletionSource<bool>();
op.PreDeleteItem += (s, e) =>
{
if (!permanently && !e.Flags.HasFlag(ShellFileOperations.TransferFlags.DeleteRecycleIfPossible))
{
throw new Win32Exception(HRESULT.COPYENGINE_E_RECYCLE_BIN_NOT_FOUND); // E_FAIL, stops operation
}
};
op.PostDeleteItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Source = e.SourceItem.FileSystemPath ?? e.SourceItem.ParsingName,
Destination = e.Desreplacedem?.FileSystemPath,
HRresult = (int)e.Result
});
};
op.PostDeleteItem += (s, e) => UpdateFileTageDb(s, e, "delete");
op.FinishOperations += (s, e) => deleteTcs.TrySetResult(e.Result.Succeeded);
op.UpdateProgress += (s, e) =>
{
if (progressHandler.CheckCanceled(operationID))
{
throw new Win32Exception(unchecked((int)0x80004005)); // E_FAIL, stops operation
}
progressHandler.UpdateOperation(operationID, e.ProgressPercentage);
};
try
{
op.PerformOperations();
}
catch
{
deleteTcs.TrySetResult(false);
}
progressHandler.RemoveOperation(operationID);
return (await deleteTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) }
}, message.Get("RequestID", (string)null));
}
break;
case "RenameItem":
{
var fileToRenamePath = (string)message["filepath"];
var newName = (string)message["newName"];
var operationID = (string)message["operationID"];
var overwriteOnRename = (bool)message["overwrite"];
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
var shellOperationResult = new ShellOperationResult();
op.Options = ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoErrorUI;
op.Options |= !overwriteOnRename ? ShellFileOperations.OperationFlags.RenameOnCollision : 0;
using var shi = new ShellItem(fileToRenamePath);
op.QueueRenameOperation(shi, newName);
progressHandler.OwnerWindow = op.OwnerWindow;
progressHandler.AddOperation(operationID);
var renameTcs = new TaskCompletionSource<bool>();
op.PostRenameItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Source = e.SourceItem.FileSystemPath ?? e.SourceItem.ParsingName,
Destination = !string.IsNullOrEmpty(e.Name) ? Path.Combine(Path.GetDirectoryName(e.SourceItem.FileSystemPath), e.Name) : null,
HRresult = (int)e.Result
});
};
op.PostRenameItem += (s, e) => UpdateFileTageDb(s, e, "rename");
op.FinishOperations += (s, e) => renameTcs.TrySetResult(e.Result.Succeeded);
try
{
op.PerformOperations();
}
catch
{
renameTcs.TrySetResult(false);
}
progressHandler.RemoveOperation(operationID);
return (await renameTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) },
}, message.Get("RequestID", (string)null));
}
break;
case "MoveItem":
{
var fileToMovePath = ((string)message["filepath"]).Split('|');
var moveDestination = ((string)message["destpath"]).Split('|');
var operationID = (string)message["operationID"];
var overwriteOnMove = (bool)message["overwrite"];
var ownerHwnd = (long)message["HWND"];
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
var shellOperationResult = new ShellOperationResult();
op.Options = ShellFileOperations.OperationFlags.NoConfirmMkDir
| ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoErrorUI;
op.OwnerWindow = Win32API.Win32Window.FromLong(ownerHwnd);
op.Options |= !overwriteOnMove ? ShellFileOperations.OperationFlags.PreserveFileExtensions | ShellFileOperations.OperationFlags.RenameOnCollision
: ShellFileOperations.OperationFlags.NoConfirmation;
for (var i = 0; i < fileToMovePath.Length; i++)
{
using (ShellItem shi = new ShellItem(fileToMovePath[i]))
using (ShellFolder shd = new ShellFolder(Path.GetDirectoryName(moveDestination[i])))
{
op.QueueMoveOperation(shi, shd, Path.GetFileName(moveDestination[i]));
}
}
progressHandler.OwnerWindow = op.OwnerWindow;
progressHandler.AddOperation(operationID);
var moveTcs = new TaskCompletionSource<bool>();
op.PostMoveItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Source = e.SourceItem.FileSystemPath ?? e.SourceItem.ParsingName,
Destination = e.DestFolder?.FileSystemPath != null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(e.DestFolder.FileSystemPath, e.Name) : null,
HRresult = (int)e.Result
});
};
op.PostMoveItem += (s, e) => UpdateFileTageDb(s, e, "move");
op.FinishOperations += (s, e) => moveTcs.TrySetResult(e.Result.Succeeded);
op.UpdateProgress += (s, e) =>
{
if (progressHandler.CheckCanceled(operationID))
{
throw new Win32Exception(unchecked((int)0x80004005)); // E_FAIL, stops operation
}
progressHandler.UpdateOperation(operationID, e.ProgressPercentage);
};
try
{
op.PerformOperations();
}
catch
{
moveTcs.TrySetResult(false);
}
progressHandler.RemoveOperation(operationID);
return (await moveTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) }
}, message.Get("RequestID", (string)null));
}
break;
case "CopyItem":
{
var fileToCopyPath = ((string)message["filepath"]).Split('|');
var copyDestination = ((string)message["destpath"]).Split('|');
var operationID = (string)message["operationID"];
var overwriteOnCopy = (bool)message["overwrite"];
var ownerHwnd = (long)message["HWND"];
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
var shellOperationResult = new ShellOperationResult();
op.Options = ShellFileOperations.OperationFlags.NoConfirmMkDir
| ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoErrorUI;
op.OwnerWindow = Win32API.Win32Window.FromLong(ownerHwnd);
op.Options |= !overwriteOnCopy ? ShellFileOperations.OperationFlags.PreserveFileExtensions | ShellFileOperations.OperationFlags.RenameOnCollision
: ShellFileOperations.OperationFlags.NoConfirmation;
for (var i = 0; i < fileToCopyPath.Length; i++)
{
using (ShellItem shi = new ShellItem(fileToCopyPath[i]))
using (ShellFolder shd = new ShellFolder(Path.GetDirectoryName(copyDestination[i])))
{
op.QueueCopyOperation(shi, shd, Path.GetFileName(copyDestination[i]));
}
}
progressHandler.OwnerWindow = op.OwnerWindow;
progressHandler.AddOperation(operationID);
var copyTcs = new TaskCompletionSource<bool>();
op.PostCopyItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Source = e.SourceItem.FileSystemPath ?? e.SourceItem.ParsingName,
Destination = e.DestFolder?.FileSystemPath != null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(e.DestFolder.FileSystemPath, e.Name) : null,
HRresult = (int)e.Result
});
};
op.PostCopyItem += (s, e) => UpdateFileTageDb(s, e, "copy");
op.FinishOperations += (s, e) => copyTcs.TrySetResult(e.Result.Succeeded);
op.UpdateProgress += (s, e) =>
{
if (progressHandler.CheckCanceled(operationID))
{
throw new Win32Exception(unchecked((int)0x80004005)); // E_FAIL, stops operation
}
progressHandler.UpdateOperation(operationID, e.ProgressPercentage);
};
try
{
op.PerformOperations();
}
catch
{
copyTcs.TrySetResult(false);
}
progressHandler.RemoveOperation(operationID);
return (await copyTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) }
}, message.Get("RequestID", (string)null));
}
break;
case "CancelOperation":
{
var operationID = (string)message["operationID"];
progressHandler.TryCancel(operationID);
}
break;
case "ParseLink":
try
{
var linkPath = (string)message["filepath"];
if (linkPath.EndsWith(".lnk"))
{
using var link = new ShellLink(linkPath, LinkResolution.NoUIWithMsgPump, null, TimeSpan.FromMilliseconds(100));
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "TargetPath", link.TargetPath },
{ "Arguments", link.Arguments },
{ "WorkingDirectory", link.WorkingDirectory },
{ "RunAsAdmin", link.RunAsAdministrator },
{ "IsFolder", !string.IsNullOrEmpty(link.TargetPath) && link.Target.IsFolder }
}, message.Get("RequestID", (string)null));
}
else if (linkPath.EndsWith(".url"))
{
var linkUrl = await Win32API.StartSTATask(() =>
{
var ipf = new Url.IUniformResourceLocator();
(ipf as System.Runtime.InteropServices.ComTypes.IPersistFile).Load(linkPath, 0);
ipf.GetUrl(out var retVal);
return retVal;
});
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "TargetPath", linkUrl },
{ "Arguments", null },
{ "WorkingDirectory", null },
{ "RunAsAdmin", false },
{ "IsFolder", false }
}, message.Get("RequestID", (string)null));
}
}
catch (Exception ex)
{
// Could not parse shortcut
Program.Logger.Warn(ex, ex.Message);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "TargetPath", null },
{ "Arguments", null },
{ "WorkingDirectory", null },
{ "RunAsAdmin", false },
{ "IsFolder", false }
}, message.Get("RequestID", (string)null));
}
break;
case "CreateLink":
case "UpdateLink":
try
{
var linkSavePath = (string)message["filepath"];
var targetPath = (string)message["targetpath"];
bool success = false;
if (linkSavePath.EndsWith(".lnk"))
{
var arguments = (string)message["arguments"];
var workingDirectory = (string)message["workingdir"];
var runAsAdmin = (bool)message["runasadmin"];
using var newLink = new ShellLink(targetPath, arguments, workingDirectory);
newLink.RunAsAdministrator = runAsAdmin;
newLink.SaveAs(linkSavePath); // Overwrite if exists
success = true;
}
else if (linkSavePath.EndsWith(".url"))
{
success = await Win32API.StartSTATask(() =>
{
var ipf = new Url.IUniformResourceLocator();
ipf.SetUrl(targetPath, Url.IURL_SETURL_FLAGS.IURL_SETURL_FL_GUESS_PROTOCOL);
(ipf as System.Runtime.InteropServices.ComTypes.IPersistFile).Save(linkSavePath, false); // Overwrite if exists
return true;
});
}
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", success } }, message.Get("RequestID", (string)null));
}
catch (Exception ex)
{
// Could not create shortcut
Program.Logger.Warn(ex, ex.Message);
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null));
}
break;
case "SetLinkIcon":
try
{
var linkPath = (string)message["filepath"];
using var link = new ShellLink(linkPath, LinkResolution.NoUIWithMsgPump, null, TimeSpan.FromMilliseconds(100));
link.IconLocation = new IconLocation((string)message["iconFile"], (int)message.Get("iconIndex", 0L));
link.SaveAs(linkPath); // Overwrite if exists
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", true } }, message.Get("RequestID", (string)null));
}
catch (Exception ex)
{
// Could not create shortcut
Program.Logger.Warn(ex, ex.Message);
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null));
}
break;
case "GetFilePermissions":
{
var filePathForPerm = (string)message["filepath"];
var isFolder = (bool)message["isfolder"];
var filePermissions = FilePermissions.FromFilePath(filePathForPerm, isFolder);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "FilePermissions", JsonConvert.SerializeObject(filePermissions) }
}, message.Get("RequestID", (string)null));
}
break;
case "SetFilePermissions":
{
var filePermissionsString = (string)message["permissions"];
var filePermissionsToSet = JsonConvert.DeserializeObject<FilePermissions>(filePermissionsString);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "Success", filePermissionsToSet.SetPermissions() }
}, message.Get("RequestID", (string)null));
}
break;
case "SetFileOwner":
{
var filePathForPerm = (string)message["filepath"];
var isFolder = (bool)message["isfolder"];
var ownerSid = (string)message["ownersid"];
var fp = FilePermissions.FromFilePath(filePathForPerm, isFolder);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "Success", fp.SetOwner(ownerSid) }
}, message.Get("RequestID", (string)null));
}
break;
case "SetAccessRuleProtection":
{
var filePathForPerm = (string)message["filepath"];
var isFolder = (bool)message["isfolder"];
var isProtected = (bool)message["isprotected"];
var preserveInheritance = (bool)message["preserveinheritance"];
var fp = FilePermissions.FromFilePath(filePathForPerm, isFolder);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "Success", fp.SetAccessRuleProtection(isProtected, preserveInheritance) }
}, message.Get("RequestID", (string)null));
}
break;
case "OpenObjectPicker":
var hwnd = (long)message["HWND"];
var pickedObject = await FilePermissions.OpenObjectPicker(hwnd);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "PickedObject", pickedObject }
}, message.Get("RequestID", (string)null));
break;
case "ReadCompatOptions":
{
var filePath = (string)message["filepath"];
var compatOptions = Extensions.IgnoreExceptions(() =>
{
using var compatKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers");
if (compatKey == null)
{
return null;
}
return (string)compatKey.GetValue(filePath, null);
}, Program.Logger);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "CompatOptions", compatOptions }
}, message.Get("RequestID", (string)null));
}
break;
case "SetCompatOptions":
{
var filePath = (string)message["filepath"];
var compatOptions = (string)message["options"];
bool success = false;
if (string.IsNullOrEmpty(compatOptions) || compatOptions == "~")
{
success = Win32API.RunPowershellCommand(@$"Remove-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers' -Name '{filePath}' | Out-Null", false);
}
else
{
success = Win32API.RunPowershellCommand(@$"New-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers' -Name '{filePath}' -Value '{compatOptions}' -PropertyType String -Force | Out-Null", false);
}
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", success } }, message.Get("RequestID", (string)null));
}
break;
}
}
19
Source : FileOperationsHandler.cs
with GNU General Public License v3.0
from files-community
with GNU General Public License v3.0
from files-community
private async Task ParseFileOperationAsync(PipeStream connection, Dictionary<string, object> message)
{
switch (message.Get("fileop", ""))
{
case "GetFileHandle":
{
var filePath = (string)message["filepath"];
var readWrite = (bool)message["readwrite"];
using var hFile = Kernel32.CreateFile(filePath, Kernel32.FileAccess.GENERIC_READ | (readWrite ? Kernel32.FileAccess.GENERIC_WRITE : 0), FileShare.ReadWrite, null, FileMode.Open, FileFlagsAndAttributes.FILE_ATTRIBUTE_NORMAL);
if (hFile.IsInvalid)
{
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null));
return;
}
var processId = (int)(long)message["processid"];
using var uwpProces = System.Diagnostics.Process.GetProcessById(processId);
if (!Kernel32.DuplicateHandle(Kernel32.GetCurrentProcess(), hFile.DangerousGetHandle(), uwpProces.Handle, out var targetHandle, 0, false, Kernel32.DUPLICATE_HANDLE_OPTIONS.DUPLICATE_SAME_ACCESS))
{
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null));
return;
}
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", true },
{ "Handle", targetHandle.ToInt64() }
}, message.Get("RequestID", (string)null));
}
break;
case "Clipboard":
await Win32API.StartSTATask(() =>
{
System.Windows.Forms.Clipboard.Clear();
var fileToCopy = (string)message["filepath"];
var operation = (DataPackageOperation)(long)message["operation"];
var fileList = new System.Collections.Specialized.StringCollection();
fileList.AddRange(fileToCopy.Split('|'));
if (operation == DataPackageOperation.Copy)
{
System.Windows.Forms.Clipboard.SetFileDropList(fileList);
}
else if (operation == DataPackageOperation.Move)
{
byte[] moveEffect = new byte[] { 2, 0, 0, 0 };
MemoryStream dropEffect = new MemoryStream();
dropEffect.Write(moveEffect, 0, moveEffect.Length);
var data = new System.Windows.Forms.DataObject();
data.SetFileDropList(fileList);
data.SetData("Preferred DropEffect", dropEffect);
System.Windows.Forms.Clipboard.SetDataObject(data, true);
}
return true;
});
break;
case "DragDrop":
var dropPath = (string)message["droppath"];
var result = await Win32API.StartSTATask(() =>
{
var rdo = new RemoteDataObject(System.Windows.Forms.Clipboard.GetDataObject());
foreach (RemoteDataObject.DataPackage package in rdo.GetRemoteData())
{
try
{
if (package.ItemType == RemoteDataObject.StorageType.File)
{
string directoryPath = Path.GetDirectoryName(dropPath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
string uniqueName = Win32API.GenerateUniquePath(Path.Combine(dropPath, package.Name));
using (FileStream stream = new FileStream(uniqueName, FileMode.CreateNew))
{
package.ContentStream.CopyTo(stream);
}
}
else
{
string directoryPath = Path.Combine(dropPath, package.Name);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
}
finally
{
package.Dispose();
}
}
return true;
});
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", result } }, message.Get("RequestID", (string)null));
break;
case "CreateFile":
case "CreateFolder":
{
var filePath = (string)message["filepath"];
var template = message.Get("template", (string)null);
var dataStr = message.Get("data", (string)null);
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
op.Options = ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoConfirmMkDir
| ShellFileOperations.OperationFlags.RenameOnCollision
| ShellFileOperations.OperationFlags.NoErrorUI;
var shellOperationResult = new ShellOperationResult();
using var shd = new ShellFolder(Path.GetDirectoryName(filePath));
op.QueueNewItemOperation(shd, Path.GetFileName(filePath),
(string)message["fileop"] == "CreateFolder" ? FileAttributes.Directory : FileAttributes.Normal, template);
var createTcs = new TaskCompletionSource<bool>();
op.PostNewItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Destination = e.Desreplacedem?.FileSystemPath,
HRresult = (int)e.Result
});
};
op.FinishOperations += (s, e) => createTcs.TrySetResult(e.Result.Succeeded);
try
{
op.PerformOperations();
}
catch
{
createTcs.TrySetResult(false);
}
if (dataStr != null && (shellOperationResult.Items.SingleOrDefault()?.Succeeded ?? false))
{
Extensions.IgnoreExceptions(() =>
{
var dataBytes = Convert.FromBase64String(dataStr);
using (var fs = new FileStream(shellOperationResult.Items.Single().Destination, FileMode.Open))
{
fs.Write(dataBytes, 0, dataBytes.Length);
fs.Flush();
}
}, Program.Logger);
}
return (await createTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) }
}, message.Get("RequestID", (string)null));
}
break;
case "DeleteItem":
{
var fileToDeletePath = ((string)message["filepath"]).Split('|');
var permanently = (bool)message["permanently"];
var operationID = (string)message["operationID"];
var ownerHwnd = (long)message["HWND"];
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
op.Options = ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoConfirmation
| ShellFileOperations.OperationFlags.NoErrorUI;
op.OwnerWindow = Win32API.Win32Window.FromLong(ownerHwnd);
if (!permanently)
{
op.Options |= ShellFileOperations.OperationFlags.RecycleOnDelete
| ShellFileOperations.OperationFlags.WantNukeWarning;
}
var shellOperationResult = new ShellOperationResult();
for (var i = 0; i < fileToDeletePath.Length; i++)
{
using var shi = new ShellItem(fileToDeletePath[i]);
op.QueueDeleteOperation(shi);
}
progressHandler.OwnerWindow = op.OwnerWindow;
progressHandler.AddOperation(operationID);
var deleteTcs = new TaskCompletionSource<bool>();
op.PreDeleteItem += (s, e) =>
{
if (!permanently && !e.Flags.HasFlag(ShellFileOperations.TransferFlags.DeleteRecycleIfPossible))
{
throw new Win32Exception(HRESULT.COPYENGINE_E_RECYCLE_BIN_NOT_FOUND); // E_FAIL, stops operation
}
};
op.PostDeleteItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Source = e.SourceItem.FileSystemPath ?? e.SourceItem.ParsingName,
Destination = e.Desreplacedem?.FileSystemPath,
HRresult = (int)e.Result
});
};
op.PostDeleteItem += (s, e) => UpdateFileTageDb(s, e, "delete");
op.FinishOperations += (s, e) => deleteTcs.TrySetResult(e.Result.Succeeded);
op.UpdateProgress += (s, e) =>
{
if (progressHandler.CheckCanceled(operationID))
{
throw new Win32Exception(unchecked((int)0x80004005)); // E_FAIL, stops operation
}
progressHandler.UpdateOperation(operationID, e.ProgressPercentage);
};
try
{
op.PerformOperations();
}
catch
{
deleteTcs.TrySetResult(false);
}
progressHandler.RemoveOperation(operationID);
return (await deleteTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) }
}, message.Get("RequestID", (string)null));
}
break;
case "RenameItem":
{
var fileToRenamePath = (string)message["filepath"];
var newName = (string)message["newName"];
var operationID = (string)message["operationID"];
var overwriteOnRename = (bool)message["overwrite"];
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
var shellOperationResult = new ShellOperationResult();
op.Options = ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoErrorUI;
op.Options |= !overwriteOnRename ? ShellFileOperations.OperationFlags.RenameOnCollision : 0;
using var shi = new ShellItem(fileToRenamePath);
op.QueueRenameOperation(shi, newName);
progressHandler.OwnerWindow = op.OwnerWindow;
progressHandler.AddOperation(operationID);
var renameTcs = new TaskCompletionSource<bool>();
op.PostRenameItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Source = e.SourceItem.FileSystemPath ?? e.SourceItem.ParsingName,
Destination = !string.IsNullOrEmpty(e.Name) ? Path.Combine(Path.GetDirectoryName(e.SourceItem.FileSystemPath), e.Name) : null,
HRresult = (int)e.Result
});
};
op.PostRenameItem += (s, e) => UpdateFileTageDb(s, e, "rename");
op.FinishOperations += (s, e) => renameTcs.TrySetResult(e.Result.Succeeded);
try
{
op.PerformOperations();
}
catch
{
renameTcs.TrySetResult(false);
}
progressHandler.RemoveOperation(operationID);
return (await renameTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) },
}, message.Get("RequestID", (string)null));
}
break;
case "MoveItem":
{
var fileToMovePath = ((string)message["filepath"]).Split('|');
var moveDestination = ((string)message["destpath"]).Split('|');
var operationID = (string)message["operationID"];
var overwriteOnMove = (bool)message["overwrite"];
var ownerHwnd = (long)message["HWND"];
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
var shellOperationResult = new ShellOperationResult();
op.Options = ShellFileOperations.OperationFlags.NoConfirmMkDir
| ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoErrorUI;
op.OwnerWindow = Win32API.Win32Window.FromLong(ownerHwnd);
op.Options |= !overwriteOnMove ? ShellFileOperations.OperationFlags.PreserveFileExtensions | ShellFileOperations.OperationFlags.RenameOnCollision
: ShellFileOperations.OperationFlags.NoConfirmation;
for (var i = 0; i < fileToMovePath.Length; i++)
{
using (ShellItem shi = new ShellItem(fileToMovePath[i]))
using (ShellFolder shd = new ShellFolder(Path.GetDirectoryName(moveDestination[i])))
{
op.QueueMoveOperation(shi, shd, Path.GetFileName(moveDestination[i]));
}
}
progressHandler.OwnerWindow = op.OwnerWindow;
progressHandler.AddOperation(operationID);
var moveTcs = new TaskCompletionSource<bool>();
op.PostMoveItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Source = e.SourceItem.FileSystemPath ?? e.SourceItem.ParsingName,
Destination = e.DestFolder?.FileSystemPath != null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(e.DestFolder.FileSystemPath, e.Name) : null,
HRresult = (int)e.Result
});
};
op.PostMoveItem += (s, e) => UpdateFileTageDb(s, e, "move");
op.FinishOperations += (s, e) => moveTcs.TrySetResult(e.Result.Succeeded);
op.UpdateProgress += (s, e) =>
{
if (progressHandler.CheckCanceled(operationID))
{
throw new Win32Exception(unchecked((int)0x80004005)); // E_FAIL, stops operation
}
progressHandler.UpdateOperation(operationID, e.ProgressPercentage);
};
try
{
op.PerformOperations();
}
catch
{
moveTcs.TrySetResult(false);
}
progressHandler.RemoveOperation(operationID);
return (await moveTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) }
}, message.Get("RequestID", (string)null));
}
break;
case "CopyItem":
{
var fileToCopyPath = ((string)message["filepath"]).Split('|');
var copyDestination = ((string)message["destpath"]).Split('|');
var operationID = (string)message["operationID"];
var overwriteOnCopy = (bool)message["overwrite"];
var ownerHwnd = (long)message["HWND"];
var (success, shellOperationResult) = await Win32API.StartSTATask(async () =>
{
using (var op = new ShellFileOperations())
{
var shellOperationResult = new ShellOperationResult();
op.Options = ShellFileOperations.OperationFlags.NoConfirmMkDir
| ShellFileOperations.OperationFlags.Silent
| ShellFileOperations.OperationFlags.NoErrorUI;
op.OwnerWindow = Win32API.Win32Window.FromLong(ownerHwnd);
op.Options |= !overwriteOnCopy ? ShellFileOperations.OperationFlags.PreserveFileExtensions | ShellFileOperations.OperationFlags.RenameOnCollision
: ShellFileOperations.OperationFlags.NoConfirmation;
for (var i = 0; i < fileToCopyPath.Length; i++)
{
using (ShellItem shi = new ShellItem(fileToCopyPath[i]))
using (ShellFolder shd = new ShellFolder(Path.GetDirectoryName(copyDestination[i])))
{
op.QueueCopyOperation(shi, shd, Path.GetFileName(copyDestination[i]));
}
}
progressHandler.OwnerWindow = op.OwnerWindow;
progressHandler.AddOperation(operationID);
var copyTcs = new TaskCompletionSource<bool>();
op.PostCopyItem += (s, e) =>
{
shellOperationResult.Items.Add(new ShellOperationItemResult()
{
Succeeded = e.Result.Succeeded,
Source = e.SourceItem.FileSystemPath ?? e.SourceItem.ParsingName,
Destination = e.DestFolder?.FileSystemPath != null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(e.DestFolder.FileSystemPath, e.Name) : null,
HRresult = (int)e.Result
});
};
op.PostCopyItem += (s, e) => UpdateFileTageDb(s, e, "copy");
op.FinishOperations += (s, e) => copyTcs.TrySetResult(e.Result.Succeeded);
op.UpdateProgress += (s, e) =>
{
if (progressHandler.CheckCanceled(operationID))
{
throw new Win32Exception(unchecked((int)0x80004005)); // E_FAIL, stops operation
}
progressHandler.UpdateOperation(operationID, e.ProgressPercentage);
};
try
{
op.PerformOperations();
}
catch
{
copyTcs.TrySetResult(false);
}
progressHandler.RemoveOperation(operationID);
return (await copyTcs.Task, shellOperationResult);
}
});
await Win32API.SendMessageAsync(connection, new ValueSet() {
{ "Success", success },
{ "Result", JsonConvert.SerializeObject(shellOperationResult) }
}, message.Get("RequestID", (string)null));
}
break;
case "CancelOperation":
{
var operationID = (string)message["operationID"];
progressHandler.TryCancel(operationID);
}
break;
case "ParseLink":
try
{
var linkPath = (string)message["filepath"];
if (linkPath.EndsWith(".lnk"))
{
using var link = new ShellLink(linkPath, LinkResolution.NoUIWithMsgPump, null, TimeSpan.FromMilliseconds(100));
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "TargetPath", link.TargetPath },
{ "Arguments", link.Arguments },
{ "WorkingDirectory", link.WorkingDirectory },
{ "RunAsAdmin", link.RunAsAdministrator },
{ "IsFolder", !string.IsNullOrEmpty(link.TargetPath) && link.Target.IsFolder }
}, message.Get("RequestID", (string)null));
}
else if (linkPath.EndsWith(".url"))
{
var linkUrl = await Win32API.StartSTATask(() =>
{
var ipf = new Url.IUniformResourceLocator();
(ipf as System.Runtime.InteropServices.ComTypes.IPersistFile).Load(linkPath, 0);
ipf.GetUrl(out var retVal);
return retVal;
});
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "TargetPath", linkUrl },
{ "Arguments", null },
{ "WorkingDirectory", null },
{ "RunAsAdmin", false },
{ "IsFolder", false }
}, message.Get("RequestID", (string)null));
}
}
catch (Exception ex)
{
// Could not parse shortcut
Program.Logger.Warn(ex, ex.Message);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "TargetPath", null },
{ "Arguments", null },
{ "WorkingDirectory", null },
{ "RunAsAdmin", false },
{ "IsFolder", false }
}, message.Get("RequestID", (string)null));
}
break;
case "CreateLink":
case "UpdateLink":
try
{
var linkSavePath = (string)message["filepath"];
var targetPath = (string)message["targetpath"];
bool success = false;
if (linkSavePath.EndsWith(".lnk"))
{
var arguments = (string)message["arguments"];
var workingDirectory = (string)message["workingdir"];
var runAsAdmin = (bool)message["runasadmin"];
using var newLink = new ShellLink(targetPath, arguments, workingDirectory);
newLink.RunAsAdministrator = runAsAdmin;
newLink.SaveAs(linkSavePath); // Overwrite if exists
success = true;
}
else if (linkSavePath.EndsWith(".url"))
{
success = await Win32API.StartSTATask(() =>
{
var ipf = new Url.IUniformResourceLocator();
ipf.SetUrl(targetPath, Url.IURL_SETURL_FLAGS.IURL_SETURL_FL_GUESS_PROTOCOL);
(ipf as System.Runtime.InteropServices.ComTypes.IPersistFile).Save(linkSavePath, false); // Overwrite if exists
return true;
});
}
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", success } }, message.Get("RequestID", (string)null));
}
catch (Exception ex)
{
// Could not create shortcut
Program.Logger.Warn(ex, ex.Message);
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null));
}
break;
case "SetLinkIcon":
try
{
var linkPath = (string)message["filepath"];
using var link = new ShellLink(linkPath, LinkResolution.NoUIWithMsgPump, null, TimeSpan.FromMilliseconds(100));
link.IconLocation = new IconLocation((string)message["iconFile"], (int)message.Get("iconIndex", 0L));
link.SaveAs(linkPath); // Overwrite if exists
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", true } }, message.Get("RequestID", (string)null));
}
catch (Exception ex)
{
// Could not create shortcut
Program.Logger.Warn(ex, ex.Message);
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null));
}
break;
case "GetFilePermissions":
{
var filePathForPerm = (string)message["filepath"];
var isFolder = (bool)message["isfolder"];
var filePermissions = FilePermissions.FromFilePath(filePathForPerm, isFolder);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "FilePermissions", JsonConvert.SerializeObject(filePermissions) }
}, message.Get("RequestID", (string)null));
}
break;
case "SetFilePermissions":
{
var filePermissionsString = (string)message["permissions"];
var filePermissionsToSet = JsonConvert.DeserializeObject<FilePermissions>(filePermissionsString);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "Success", filePermissionsToSet.SetPermissions() }
}, message.Get("RequestID", (string)null));
}
break;
case "SetFileOwner":
{
var filePathForPerm = (string)message["filepath"];
var isFolder = (bool)message["isfolder"];
var ownerSid = (string)message["ownersid"];
var fp = FilePermissions.FromFilePath(filePathForPerm, isFolder);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "Success", fp.SetOwner(ownerSid) }
}, message.Get("RequestID", (string)null));
}
break;
case "SetAccessRuleProtection":
{
var filePathForPerm = (string)message["filepath"];
var isFolder = (bool)message["isfolder"];
var isProtected = (bool)message["isprotected"];
var preserveInheritance = (bool)message["preserveinheritance"];
var fp = FilePermissions.FromFilePath(filePathForPerm, isFolder);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "Success", fp.SetAccessRuleProtection(isProtected, preserveInheritance) }
}, message.Get("RequestID", (string)null));
}
break;
case "OpenObjectPicker":
var hwnd = (long)message["HWND"];
var pickedObject = await FilePermissions.OpenObjectPicker(hwnd);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "PickedObject", pickedObject }
}, message.Get("RequestID", (string)null));
break;
case "ReadCompatOptions":
{
var filePath = (string)message["filepath"];
var compatOptions = Extensions.IgnoreExceptions(() =>
{
using var compatKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers");
if (compatKey == null)
{
return null;
}
return (string)compatKey.GetValue(filePath, null);
}, Program.Logger);
await Win32API.SendMessageAsync(connection, new ValueSet()
{
{ "CompatOptions", compatOptions }
}, message.Get("RequestID", (string)null));
}
break;
case "SetCompatOptions":
{
var filePath = (string)message["filepath"];
var compatOptions = (string)message["options"];
bool success = false;
if (string.IsNullOrEmpty(compatOptions) || compatOptions == "~")
{
success = Win32API.RunPowershellCommand(@$"Remove-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers' -Name '{filePath}' | Out-Null", false);
}
else
{
success = Win32API.RunPowershellCommand(@$"New-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers' -Name '{filePath}' -Value '{compatOptions}' -PropertyType String -Force | Out-Null", false);
}
await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", success } }, message.Get("RequestID", (string)null));
}
break;
}
}
19
Source : TplExtensions.cs
with MIT License
from fintermobilityas
with MIT License
from fintermobilityas
public static async Task<T> WithCancellation<T>([NotNull] this Task<T> task, CancellationToken cancellationToken)
{
if (task == null) throw new ArgumentNullException(nameof(task));
// The tasck completion source.
var tcs = new TaskCompletionSource<bool>();
// Register with the cancellation token.
await using (cancellationToken.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(true), tcs))
{
// If the task waited on is the cancellation token...
if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
{
throw new OperationCanceledException(cancellationToken);
}
}
// Wait for one or the other to complete.
return await task;
}
19
Source : TplExtensions.cs
with MIT License
from fintermobilityas
with MIT License
from fintermobilityas
public static async Task WithCancellation([NotNull] this Task task, CancellationToken cancellationToken)
{
if (task == null) throw new ArgumentNullException(nameof(task));
// The tasck completion source.
var tcs = new TaskCompletionSource<bool>();
// Register with the cancellation token.
await using (cancellationToken.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(true), tcs))
{
// If the task waited on is the cancellation token...
if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
{
throw new OperationCanceledException(cancellationToken);
}
}
// Wait for one or the other to complete.
await task;
}
See More Examples