Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions src/Appium.Net/Appium/Service/AppiumCommandExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ internal class AppiumCommandExecutor : ICommandExecutor
{
private readonly AppiumLocalService Service;
private readonly Uri URL;
private readonly ICommandExecutor RealExecutor;
private ICommandExecutor RealExecutor;
private bool isDisposed;
private const string IdempotencyHeader = "X-Idempotency-Key";

private static ICommandExecutor CreateRealExecutor(Uri remoteAddress, TimeSpan commandTimeout)
{
Expand All @@ -34,7 +35,7 @@ private static ICommandExecutor CreateRealExecutor(Uri remoteAddress, TimeSpan c
if (null != commandType)
{
commandExecutor =
Activator.CreateInstance(commandType, new object[] {remoteAddress, commandTimeout}) as
Activator.CreateInstance(commandType, new object[] { remoteAddress, commandTimeout }) as
ICommandExecutor;
}

Expand Down Expand Up @@ -64,23 +65,26 @@ internal AppiumCommandExecutor(AppiumLocalService service, TimeSpan timeForTheSe
public Response Execute(Command commandToExecute)
{
Response result = null;
if (commandToExecute.Name == DriverCommand.NewSession && this.Service != null)
{
Service.Start();
}

try
{
if (commandToExecute.Name == DriverCommand.NewSession)
{
Service?.Start();
RealExecutor = ModifyNewSessionHttpRequestHeader(RealExecutor);
}

result = RealExecutor.Execute(commandToExecute);
return result;
}
catch (Exception e)
{
if ((commandToExecute.Name == DriverCommand.NewSession) && (Service != null))
if ((commandToExecute.Name == DriverCommand.NewSession))
{
Service.Dispose();
Service?.Dispose();
}
throw e;

throw;
}
finally
{
Expand All @@ -97,21 +101,25 @@ public Response Execute(Command commandToExecute)
}
}

public void Dispose()
private ICommandExecutor ModifyNewSessionHttpRequestHeader(ICommandExecutor commandExecutor)
{
this.Dispose(true);
if (commandExecutor == null) throw new ArgumentNullException(nameof(commandExecutor));
var modifiedCommandExecutor = commandExecutor as HttpCommandExecutor;
if (modifiedCommandExecutor != null)
modifiedCommandExecutor.SendingRemoteHttpRequest += (sender, args) =>
args.Request.Headers.Add(IdempotencyHeader, Guid.NewGuid().ToString());
return modifiedCommandExecutor;
}

public void Dispose() => Dispose(true);

protected void Dispose(bool disposing)
{
if (!isDisposed)
{
if (disposing)
{
if (Service != null)
{
Service.Dispose();
}
Service?.Dispose();
}

isDisposed = true;
Expand Down