In a Visual Studio 2013 Web Performance test, how can I delay sending the very first request in a ".webtest" for a period of time that I specify? My web test is part of a load test. The first request of the web test should be issued after a delay period specified by a data source field. Determining when the request should be issued is simply:
delayPeriod = dataSourceValue - ( timeNow - loadTestStartTime )
Writing this delayPeriod into the think time for a request causes the correct delay. Unfortunately, think times are applied after the response to a request is received. Hence it is easy to delay the second request of the web test until the desired time. I want to delay before the first request.
As a workaround, I have included a dummy first request to http://localhost/ and set the expected status code result to 404. The required delay is set as a think time on this request. But this add an unwanted request to localhost.
Background:
We have a log file from a web server. It gives the URL and the time for each request. We want to repeat the requests in that log file at the same rate as when they were recorded.
OK, another shot at it. Bare bones though, no error checking.
The LoadTestStartTime load test plugin puts a reference to the load test itself and the load test start time into the web test context.
public class LoadTestStartTime : ILoadTestPlugin
{
public const string LoadTestContextParameterName = "$LoadTest";
public const string LoadTestStartTimeContextParameterName = "$LoadTestStartTime";
public void Initialize(LoadTest loadTest)
{
DateTime startTime = default(DateTime);
loadTest.LoadTestStarting += (sender, e) => { startTime = DateTime.Now; };
loadTest.TestStarting += (sender,e) => {
e.TestContextProperties[LoadTestContextParameterName] = loadTest;
e.TestContextProperties[LoadTestStartTimeContextParameterName] = startTime;
};
}
}
The DelayWebTest web test plugin must be attached to a new web test containing one dummy request (the dummy request will not be executed). This new web test must be added to the Load Test Scenario test mix as the "Initialize Test".
The plugin reads the delay time from a context parameter, then sets the scenario's current load to 0. It then sets up a timer which calls an event handler after the properly calculated delay, which restores the load profile allowing the test to proceed. It uses locking so that only the first virtual user will execute the load profile logic while the others wait.
public class DelayWebTest : WebTestPlugin
{
public string ContextParameterName { get; set; }
private bool completed = false;
private object _lock = new object();
public override void PreRequest(object sender, PreRequestEventArgs e)
{
e.Instruction = WebTestExecutionInstruction.Skip;
if (!completed)
{
lock (_lock)
{
if (!completed)
{
if (e.WebTest.Context.WebTestUserId > 0) return;
LoadTest loadTest = (LoadTest)e.WebTest.Context[LoadTestStartTime.LoadTestContextParameterName];
DateTime startTime = (DateTime)e.WebTest.Context[LoadTestStartTime.LoadTestStartTimeContextParameterName];
TimeSpan delay = TimeSpan.Parse(e.WebTest.Context[ContextParameterName].ToString());
TimeSpan timer = delay - (DateTime.Now - startTime);
if (timer > default(TimeSpan))
{
var loadProfile = loadTest.Scenarios[0].LoadProfile.Copy();
loadTest.Scenarios[0].CurrentLoad = 0;
Timer t = new Timer() { AutoReset = false, Enabled = true, Interval = timer.TotalMilliseconds };
t.Elapsed += (_sender, _e) =>
{
loadTest.Scenarios[0].LoadProfile = loadProfile;
t.Stop();
};
t.Start();
}
completed = true;
}
}
}
}
}
Seems to work. 50 users with 30 second delay:
Your solution of the dummy request to localhost is as good as it gets as far as I know. But here's an alternative shot at it.
Two parts:
(1) A load test plugin to copy the load test start time to the web test context:
[DisplayName("Load Test Start Time")]
[Description("Record the load test start time in the context of new web test iterations")]
public class LoadTestStartTime : ILoadTestPlugin
{
public const string LoadTestStartTimeContextParameterName = "$LoadTestStartTime";
public void Initialize(LoadTest loadTest)
{
DateTime startTime = DateTime.Now;
// Copy the load test start time into the context of each new test
loadTest.TestStarting += (sender, e) =>
{
e.TestContextProperties[LoadTestStartTimeContextParameterName] = startTime;
};
}
}
(2) A web test plugin that gets its delay time from a property which can be a static value or a context parameter, and can be HH:MM:SS.SSS or integer milliseconds:
[DisplayName("Delay WebTest")]
[Description("Delay the start of this WebTest by a certain amount of time.")]
public class DelayWebTest : WebTestPlugin
{
[Description("Time to delay this WebTest, in HH:MM:SS.SSS time format or in ms (e.g. 00:01:23.456 or 83456 for 1m 23.456s delay)")]
public string Delay { get; set; }
public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
DateTime start;
// Make sure this works when not in a load test
if (!e.WebTest.Context.ContainsKey("$LoadTestUserContext"))
start = DateTime.Now;
else
start = (DateTime)(e.WebTest.Context[LoadTestStartTime.LoadTestStartTimeContextParameterName]);
TimeSpan elapsed = DateTime.Now - start;
TimeSpan delay;
// Support {{context parameter}} substitutions
if (Delay.StartsWith("{{") && Delay.EndsWith("}}"))
{
string key = Delay.Substring(2, Delay.Length - 4);
object value = e.WebTest.Context[key];
if (value is TimeSpan) delay = (TimeSpan)value;
else if (value is int) delay = new TimeSpan(0, 0, 0, 0, (int)value);
else if (value is string) delay = ParseDelayFromString(value as string);
else throw new ArgumentException("Delay value must be TimeSpan, int or string. Found: " + value.GetType());
}
else delay = ParseDelayFromString(Delay);
TimeSpan sleep = delay - elapsed;
if (sleep > new TimeSpan(0))
{
e.WebTest.AddCommentToResult("Current time: " + DateTime.Now);
e.WebTest.AddCommentToResult("About to sleep for " + sleep);
System.Threading.Thread.Sleep(sleep);
e.WebTest.AddCommentToResult("Current time: " + DateTime.Now);
}
}
public static TimeSpan ParseDelayFromString(string s)
{
TimeSpan ts;
if (TimeSpan.TryParse(s, out ts)) return ts;
int i;
if (int.TryParse(s, out i)) return new TimeSpan(0, 0, 0, 0, (int)i);
throw new FormatException("Could not parse value as TimeSpan or int: " + s);
}
}
This seems to work for me.
However it uses Thread.Sleep which "...is NOT recommended for
web tests is because it is a blocking API and more than one web test can share a thread, therefore it can adversely affect more than one vuser." (See Visual Studio Performance Testing Quick Reference Guide) page 187.
So this would certainly be OK for a single-user load test and maybe for small loads where virtual users don't outnumber threads*, but chances are it will screw up the results for larger loads.
(* I don't claim to know how the threading model works however)
Related
This is not about Delayed message delivery. Lately I've noticed my endpoint has a delay in handling a message when looking at when the message is taken from the RabbitMQ queue.
I was wondering if there is some configuration option I’m overlooking that has an impact on the delay between the receipt of the message from RabbitMQ by NServiceBus and the actual handling of the message (command) in the IHandleMessages<> handler.
I’m seeing a consistent delay when comparing the NServiceBus logfile and the logfile of the handler. It does vary a bit between client and server but in a given session it’s always constant. Now I’m running through all the options that I can find but there’s no real pointer for me out in the wild.
The thing is I’m running a workflow solution that uses NServiceBus to do all the messaging between the workflow server (based on MS WF) and 50/60 clients. The server runs on NServiceBus 7.6.0 but all client still use NServiceBus 5.2.26. I decided to write a small test client that also runs on NServiceBus 7.6.0 but that also shows the delay albeit a smaller one. But the delay between individual commands is constant at 6.5 seconds in the test client. So the message is retrieved by NSB from the queue and 6.5 seconds the IHandleMessages<> handler is invoked.
I’ve tried a couple of things (direct routing vs conventional routing, making sure license files where distributed properly for example). The only thing I’m able to come up right now is flat out making a new test server of the workflow server I’m using that is only able to accept 1 command, generating a reply and nothing more and see if that makes a difference.
Configuration wise the solution runs on a Windows Server 2016 having 4 cores, RabbitMQ 3.7.21 and NServiceBus 7.6.0. Clients run on Windows 10 machines using NServiceBus 5.2.26 but the test client uses NServiceBus 7.6.0.
Now for the logs. This is the NServicebus log when it receives the GetVersionCommand:
2022-01-20 16:09:58.104 DEBUG Processing message type: HyFlo.Service.Messages.Commands.Info.GetVersionCommand
Message headers:
CorrelationId : 619d678d-25bf-46c0-b5c0-57c624e3d557
NServiceBus.MessageId : 548813d5-2465-4ff5-904d-ae2300f9ee23
NServiceBus.MessageIntent : Send
NServiceBus.ConversationId : 367575b0-7bee-40d0-90ca-ae2300f9ee24
NServiceBus.CorrelationId : 548813d5-2465-4ff5-904d-ae2300f9ee23
NServiceBus.TimeToBeReceived : 00:10:00
NServiceBus.ReplyToAddress : Hyflo.Client.Test
NServiceBus.OriginatingMachine : DYP297
NServiceBus.OriginatingEndpoint : Hyflo.Client.Test
$.diagnostics.originating.hostid : 3a3bbd6661214b655aa6dbcd95d112a2
NServiceBus.ContentType : text/xml
NServiceBus.EnclosedMessageTypes : HyFlo.Service.Messages.Commands.Info.GetVersionCommand, HyFlo.Service.Messages, Version=4.10.3.26734, Culture=neutral, PublicKeyToken=null;HyFlo.Types.Interfaces.IInfoCommand, HyFlo.Types, Version=4.10.8.20782, Culture=neutral, PublicKeyToken=null
NServiceBus.Version : 7.6.0
NServiceBus.TimeSent : 2022-01-20 15:09:58:107461 Z
NServiceBus.NonDurableMessage : False
Handlers to invoke:
HyFlo.Service.CommandHandlers.Info.GetVersionHandler
Then the custom log of the GetVersionHandler:
2022-01-20 16:10:04.6516 TRACE = New Message =====================================================================================================================================
2022-01-20 16:10:04.6516 TRACE CommandEventId:9125b036-c315-484e-9948-889ed1e56587: New message handled by handler of type 'HyFlo.Service.CommandHandlers.Info.GetVersionHandler' with CorrelationId '619d678d-25bf-46c0-b5c0-57c624e3d557' ..
2022-01-20 16:10:04.6516 TRACE ===================================================================================================================================================
2022-01-20 16:10:04.6516 INFO Cache contains a systemstatus ..
2022-01-20 16:10:04.6516 INFO Retrieved systemstatus from cache is: 0
2022-01-20 16:10:04.6516 INFO Running the injected code ..
2022-01-20 16:10:04.6672 TRACE ===================================================================================================================================================
2022-01-20 16:10:04.6672 TRACE CommandEventId:9125b036-c315-484e-9948-889ed1e56587: Message processed by handler of type 'HyFlo.Service.CommandHandlers.Info.GetVersionHandler' with CorrelationId '619d678d-25bf-46c0-b5c0-57c624e3d557' ..
2022-01-20 16:10:04.6672 TRACE Elapsed time: 00:00:00.0156159 ..
2022-01-20 16:10:04.6672 TRACE = End of Message ==================================================================================================================================
The command is received at 2022-01-20 16:09:58.104 but is delivered at the Handler at 2022-01-20 16:10:04.6516 and this delay is quite consistent between this and other commands. I just can't get my head around why this delay is there.
The endpoint configuration is the following:
internal class ProgramService : ServiceBase
{
private IEndpointInstance _endpointInstance = null;
/// <summary>
/// Determines if application is ran as service or just as console application
/// </summary>
/// <param name="name"></param>
/// <returns>true if it's a service</returns>
private static bool IsService(string name)
{
if (!Environment.UserInteractive) return true;
var sc = new ServiceController(name);
try
{
return sc.Status == ServiceControllerStatus.StartPending;
}
catch (InvalidOperationException)
{
return false;
}
}
/// <summary>
/// Main entry
/// </summary>
private static void Main()
{
using (var service = new ProgramService())
{
// so we can run interactive from Visual Studio or as a windows service
if (!IsService("HyFlo.Service"))
{
Console.CancelKeyPress += (sender, e) => { service.OnStop(); };
service.OnStart(null);
Console.WriteLine("\r\nPress enter key to stop program\r\n");
Console.Read();
service.OnStop();
return;
}
Run(service);
}
}
/// <summary>
/// On critical errors bail out
/// </summary>
/// <param name="errorMessage"></param>
/// <param name="exception"></param>
async Task OnCriticalError(ICriticalErrorContext context)
{
var fatalMessage = $"The following critical error was encountered:\n{context.Error}\nProcess is shutting down.";
try
{
Console.WriteLine("fatalMessage: " + fatalMessage);
TraceWriter.Error(fatalMessage);
if (context.Exception.InnerException != null)
{
TraceWriter.Error("innerException message: " + context.Exception.InnerException.Message + #"\n" +
context.Exception.InnerException.StackTrace);
}
await context.Stop().ConfigureAwait(false);
}
finally
{
Environment.FailFast(fatalMessage, context.Exception);
}
}
/// <summary>
/// Starting the service
/// </summary>
/// <param name="args"></param>
private async Task AsyncOnStart()
{
TraceWriter.Trace("AsyncOnStart() running .. ");
try
{
TraceWriter.Info("Running configuration management ..");
var config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var section =
config.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("DPAPIProtection");
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
var endpointConfig = new EndpointConfiguration("hyflo.service");
endpointConfig.EnableInstallers();
endpointConfig.SendFailedMessagesTo("hyflo.service.errors");
endpointConfig.AuditProcessedMessagesTo("hyflo.service.audit");
endpointConfig.UseSerialization<XmlSerializer>();
endpointConfig.DefineCriticalErrorAction(OnCriticalError);
endpointConfig.LimitMessageProcessingConcurrencyTo(8);
var persistenceMethod = ConfigurationManager.AppSettings["NServicebusPersistence"];
if (persistenceMethod.ToUpper() == "RAVENDB")
{
string connectionString = ConfigurationManager.ConnectionStrings["NServiceBus/Persistence"].ConnectionString;
TraceWriter.Info($"Setting persistence to RavenDBPersistence based on connectionString '{connectionString}' .. ");
var documentStore = new Raven.Client.Document.DocumentStore
{
ConnectionStringName = "NServiceBus/Persistence",
DefaultDatabase = "HyFlo.Service"
};
documentStore.Initialize();
endpointConfig.UsePersistence<RavenDBPersistence>().SetDefaultDocumentStore(documentStore);
}
else
{
TraceWriter.Info("Setting persistence to InMemoryPersistence .. ");
endpointConfig.UsePersistence<InMemoryPersistence>();
}
var transportConnection = ConfigurationManager.ConnectionStrings[#"NServiceBus/Transport"];
string transportConnectionString = transportConnection.ConnectionString;
if (String.IsNullOrEmpty(transportConnectionString))
{
transportConnectionString = "host=localhost";
}
TraceWriter.Info($"Configuring RabbitMQTransport for connection '{transportConnectionString}' .. ");
var transport = endpointConfig.UseTransport<RabbitMQTransport>();
transport.ConnectionString(transportConnectionString);
transport.UseConventionalRoutingTopology();
string databusBasePath = ConfigurationManager.AppSettings["DataBusBasePath"] ?? "";
TraceWriter.Info($"Setting Databus's basepath to '{databusBasePath}' ..");
endpointConfig.UseDataBus<FileShareDataBus>().BasePath(databusBasePath);
TraceWriter.Info("Scannning for Hyflo assemblies .. ");
List<string> hyfloAssemblies =
Directory.GetFiles(Directory.GetCurrentDirectory(), "HyFlo.*dll", SearchOption.TopDirectoryOnly).ToList();
TraceWriter.Info("Initializing Autofac with assemblies .. ");
foreach (string assemblyName in hyfloAssemblies)
{
TraceWriter.Info($"Scanning '{assemblyName}' for an Autofac module .. ");
}
try
{
var containerSettings = endpointConfig.UseContainer(new AutofacServiceProviderFactory());
containerSettings.ConfigureContainer(containerBuilder =>
{
var loadedAssemblies = hyfloAssemblies.Select(Assembly.LoadFile).ToList();
containerBuilder.RegisterAssemblyModules(loadedAssemblies.ToArray());
});
}
catch (Exception ex)
{
TraceWriter.Error($"{ex.Message}\n{ex.StackTrace}\n{ex.InnerException?.Source}");
await OnCriticalError(new CriticalErrorContext(null, $"Exception occurred during initialization. Exception is: {ex.Message}\n{ex.StackTrace}\n{ex.InnerException?.Source}", ex));
}
TraceWriter.Info("Setting up default message conventions ..");
var conventions = endpointConfig.Conventions();
conventions.DefiningTimeToBeReceivedAs(type => TimeSpan.FromMinutes(10));
var logFactory = LogManager.Use<DefaultFactory>();
logFactory.Level(LogLevel.Debug);
endpointConfig.EnableFeature<HyfloInitializationFeature>();
TraceWriter.Info("Initialized! Now starting Hyflo ..");
_endpointInstance = await Endpoint.Start(endpointConfig);
TraceWriter.Info("Hyflo started ..");
}
catch (Exception exception)
{
TraceWriter.Error($"{exception.Message}\n{exception.StackTrace}\n{exception.InnerException?.Source}");
await OnCriticalError(new CriticalErrorContext(null, "Failed to start the bus.", exception));
}
}
/// <summary>
/// Stopping the service
/// </summary>
/// <returns></returns>
private Task AsyncOnStop()
{
TraceWriter.Info("Shutting down Hyflo ..");
if (_endpointInstance != null)
{
return _endpointInstance.Stop();
}
return Task.CompletedTask;
}
// <summary>
/// Starting the service
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
TraceWriter.Trace("ProgramService.OnStart() ..");
AsyncOnStart().GetAwaiter().GetResult();
}
/// <summary>
/// Stopping the service
/// </summary>
protected override void OnStop()
{
TraceWriter.Trace("ProgramService.OnStop() ..");
AsyncOnStop().GetAwaiter().GetResult();
}
}
The HyfloInitializationFeature is a startup task that sends a list of all current workflows to the connected clients.
using HyFlo.Tasks.Interfaces;
using NServiceBus.Features;
namespace HyFlo.Service
{
public class HyfloInitializationFeature : Feature
{
protected override void Setup(FeatureConfigurationContext context)
{
context.RegisterStartupTask(c => new SystemStartupTask(c.Build<IGetInfoOnAllWorkflowsTask>(), c.Build<ISystemTestTask>()));
}
}
}
This is the SystemStartupTask:
namespace HyFlo.Service
{
public class SystemStartupTask : FeatureStartupTask, IDisposable
{
private readonly IGetInfoOnAllWorkflowsTask _getInfoOnAllWorkflowsTask;
private readonly ISystemTestTask _systemTestTask;
public SystemStartupTask(IGetInfoOnAllWorkflowsTask getInfoOnAllWorkflowsTask, ISystemTestTask systemTestTask)
{
_getInfoOnAllWorkflowsTask = getInfoOnAllWorkflowsTask;
_systemTestTask = systemTestTask;
}
public void Dispose()
{
}
/// <summary>
/// OnStart
/// </summary>
/// <param name="session"></param>
/// <returns></returns>
protected override async Task OnStart(IMessageSession session)
{
TraceWriter.Trace($"==> Running SystemStartupTask.OnStart() ..");
DeleteHeartbeatIndicator();
ObjectCache cache = MemoryCache.Default;
var policy = new CacheItemPolicy { SlidingExpiration = (TimeSpan.FromSeconds(15)) };
bool systemOk = false;
if (_systemTestTask != null)
{
_systemTestTask.ContextWrapper = new MessageContextWrapper { Session = session };
_systemTestTask.QuickTest = false;
_systemTestTask.TestComponentsMask = 31;
_systemTestTask.SystemStartup = true;
if (_systemTestTask.Run())
{
var systemResultTexts = new List<string>();
if (int.TryParse(_systemTestTask.Results.ToString(), out int systemsResult))
{
if ((systemsResult & 1) == 1)
{
systemResultTexts.Add("HSB offline");
}
if ((systemsResult & 2) == 2)
{
systemResultTexts.Add("HDM offline");
}
if ((systemsResult & 4) == 4)
{
systemResultTexts.Add("SqlServer offline");
}
if ((systemsResult & 8) == 8)
{
systemResultTexts.Add("Workflow Queueing offline");
}
}
TraceWriter.Trace(
$"SystemStartupTask: Results returned by systemtest: '{(!systemResultTexts.Any() ? "All online" : String.Join(",", systemResultTexts))}' ..");
if (!_systemTestTask.Failure && !systemResultTexts.Any())
{
TraceWriter.Info("HyFlo dependencies all up and running ..");
systemOk = true;
// for caching purposes
if (_getInfoOnAllWorkflowsTask != null)
{
_getInfoOnAllWorkflowsTask.UserId = "";
_getInfoOnAllWorkflowsTask.Run();
}
}
else
{
TraceWriter.Warn("HyFlo can't be started. One or more of its dependencies returned a failure!");
}
}
}
else
{
TraceWriter.Warn("A general failure occurred during the Hyflo systemcheck!");
}
var allworkflowStates = new WorkflowState[0];
if (_getInfoOnAllWorkflowsTask != null)
{
if (!_getInfoOnAllWorkflowsTask.Failure && _getInfoOnAllWorkflowsTask.Results is List<WorkflowState>)
{
allworkflowStates = (_getInfoOnAllWorkflowsTask.Results as List<WorkflowState>).ToArray();
}
TraceWriter.Info(
$"Workflowstate retrieval completed. Failure: '{_getInfoOnAllWorkflowsTask.Failure}', Results: '{allworkflowStates.Count()}' workflow{(allworkflowStates.Count() == 1 ? "" : "s")} found ..");
var timeStamp = DateTime.Now;
TraceWriter.Trace("Sending IStartedHyflo # GUI with the following parameters:\n" +
$"\tErrorCode: '{Convert.ToInt32(_systemTestTask?.Results)}'\n" +
$"\tFailure: '{!systemOk}'\n" + $"\tTimeStamp: '{timeStamp}'\n" +
$"\tResulting workflowcount: '{allworkflowStates.Length}'\n");
await session.Publish<IStartedHyflo>(evt =>
{
evt.ErrorCode = Convert.ToInt32(_systemTestTask?.Results);
evt.Failure = !systemOk;
evt.TimeStamp = timeStamp;
evt.Result = new DataBusProperty<WorkflowState[]>(allworkflowStates);
}).ConfigureAwait(false);
cache.Set("SystemTest", systemOk, policy);
}
}
/// <summary>
/// OnStop
/// </summary>
/// <param name="session"></param>
/// <returns></returns>
protected override async Task OnStop(IMessageSession session)
{
TraceWriter.Trace($"==> Running SystemStartupTask.OnStop() ..");
TraceWriter.Info("Deleting heartbeat indicator .. ");
DeleteHeartbeatIndicator();
var timeStamp = DateTime.Now;
TraceWriter.Trace("Sending IShutdownHyflo # GUI with the following parameters:\n" + "\tErrorCode: '0'\n" +
"\tFailure: 'false'\n" + $"\tTimeStamp: '{timeStamp}'");
await session.Publish<IShutdownHyflo>(evt =>
{
evt.ErrorCode = 0;
evt.Failure = false;
evt.TimeStamp = timeStamp;
}).ConfigureAwait(false);
TraceWriter.Info("HyFlo has shutted down .. ");
}
/// <summary>
/// Function deletes the heartbeat.txt file that indicates wether a heartbeat flow is running or not
/// </summary>
private void DeleteHeartbeatIndicator()
{
string stateFolder = ConfigurationManager.AppSettings["StateFolder"];
string fullStateFolder = stateFolder.IndexOf(":", StringComparison.Ordinal) == -1
? $"{AppDomain.CurrentDomain.BaseDirectory}{stateFolder}"
: stateFolder;
string fileName = $#"{fullStateFolder}\heartbeat.txt";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
}
}
The GetVersionHandler is the following:
namespace HyFlo.Service.CommandHandlers.Info
{
public class GetVersionHandler : HandlerBase, IHandleMessages<GetVersionCommand>
{
public GetVersionHandler(ISystemTestTask systemTestTask, ITaskBuilderController taskBuilderController)
{
_systemTestTask = systemTestTask;
_taskBuilderController = taskBuilderController;
}
public virtual async Task Handle(GetVersionCommand message, IMessageHandlerContext context)
{
if (message == null)
return;
await RunDirect(async () =>
{
var assemblyVersion = Assembly.GetAssembly(typeof(GetVersionHandler)).GetName().Version;
var reply = new GetVersionReply
{
Failure = false,
Version = $"{assemblyVersion.Major}.{assemblyVersion.Minor}",
TimeStamp = DateTime.Now,
TaskId = CommandEventId,
ErrorCode = 0
};
await Retry.ExecuteAsync(async () =>
{
var replyOptions = new ReplyOptions();
replyOptions.SetHeader("CorrelationId", CorrelationId);
await context.Reply(reply, replyOptions);
});
}, new MessageContextWrapper { HandlerContext = context });
}
}
}
The RunDirect method is located in the HandlerBase class and one of the first things it does is log that a new message is being handled.
public async Task RunDirect(Action codeToRun, IMessageContextWrapper contextWrapper)
{
_taskBuilderController.HandlerBase = this;
CommandEventId = Guid.NewGuid();
ContextWrapper = contextWrapper;
CorrelationId = GetHeaderValue("CorrelationId");
string fullMethodName = GetType().ToString();
TraceWriter.Trace("= New Message =====================================================================================================================================");
TraceWriter.Trace($"CommandEventId:{CommandEventId}: New message handled by handler of type '{fullMethodName}' with CorrelationId '{CorrelationId}' .. ");
TraceWriter.Trace("===================================================================================================================================================");
...
The last thing is the test client I've used to send this GetVersionCommand:
namespace HPS_EndpointTest
{
internal class Program
{
static void Main(string[] args)
{
var endpointConfiguration = new EndpointConfiguration("Hyflo.Client.Test");
endpointConfiguration.EnableInstallers();
endpointConfiguration.UsePersistence<InMemoryPersistence>();
endpointConfiguration.PurgeOnStartup(true);
var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
endpointConfiguration.UseTransport<RabbitMQTransport>().ConnectionString("host=hswv0601;username=hyflo;password=hyflo");
endpointConfiguration.UseTransport<RabbitMQTransport>().UseDirectRoutingTopology();
IEndpointInstance endpointInstance = null;
AsyncPump.Run(async delegate
{
endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
});
Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyyTHH:mm:ss.ffff") + ": Client started ..");
var correlationId = Guid.NewGuid();
string destination = "hyflo.service";
var sendOptions = new SendOptions();
sendOptions.SetHeader("CorrelationId", correlationId.ToString());
sendOptions.SetDestination(destination);
sendOptions.RequireImmediateDispatch();
var versionMessage = new HyFlo.Service.Messages.Commands.Info.GetVersionCommand();
Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyyTHH:mm:ss.ffff") + ": Sending message ..");
AsyncPump.Run(async delegate
{
if (endpointInstance != null)
{
await endpointInstance.Send(versionMessage, sendOptions).ConfigureAwait(false);
}
});
Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyyTHH:mm:ss.ffff") + ": Message sent!");
while (true)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Enter)
{
break;
}
}
AsyncPump.Run(async delegate
{
await endpointInstance.Stop().ConfigureAwait(false);
});
}
}
public class RetrieveAllWorkflowsHandler : IHandleMessages<HyFlo.Service.Messages.Events.IRetrievedAllWorkflowsEvent>
{
public Task Handle(HyFlo.Service.Messages.Events.IRetrievedAllWorkflowsEvent message, IMessageHandlerContext context)
{
Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyyTHH:mm:ss.ffff") + ": IRetrievedAllWorkflowEvents reply received ..");
return Task.CompletedTask;
}
}
public class RetrieveVersionHandler : IHandleMessages<GetVersionReply>
{
public Task Handle(GetVersionReply message, IMessageHandlerContext context)
{
Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyyTHH:mm:ss.ffff") + ": GetVersionReply reply received ..");
return Task.CompletedTask;
}
}
}
I just don't understand why this delay is there.
What I'm doing right now is create a completely new endpoint with limited functionality (ie only supporting the GetVersionCommand) and see what happens with that. If the delay isn't there I'll expand support with other commands and see what happens then. Hope any of you guys sees this and slaps him/herself to the head and replying "but you forgot so and so".
Thanks in advance!!
With help of Daniel Marbach I managed to pin point the problem. Because of a complex object graph in one of the classes of the solution (the class that is the primary access point to the solution in fact) the delay occurred. Now when creating either specialised classes or injecting the actual needed dependency there was virtually no delay.
So the final solution was to alter each and every IHandleMessages-handler to have it injected a targeted dependency with which the handler could work.
How to I make the call so that the GetRecords is completed before _reportViewerService.ShowReport starts. Using SignalR the setUi updates a txt field which displays names from part of the result calculated in getRecords, and the rest should be printed in report there after.
(whats happening now is both running the same time, then the report being showed before I see the live update status)
Thanks in advance
public async Task ViewReport()
{
var reportData = await _apiCallExecutor.ExecuteAsync(new GetRecords(queryModel, setUiHooks));
try
{
if (reportData.Count > 0)
{
var settings = new ReportSettings();
settings.ReportPath = "Utilities/SetDeliveryIdByBatchReport";
settings.ReportTitle = "Set Delivery ID By Batch - Exception Listing";
settings.DataSources.Add("DeliveryIdExceptionRecords", reportData);
ReportStatus = "Printing Exception Report...";
await _reportViewerService.ShowReport(settings);
}
}
finally
{
ViewModelState = ViewModelStates.Edit;
}
ReportStatus = "Done...";
}
You want to use some kind of "signal" from GetRecords, e.g., an IObservable or Task that completes when the data has arrived.
class GetRecords
{
...
public Task Done { get; }
// or: public IObservable<Unit> Done { get; }
}
then:
var getRecords = new GetRecords(queryModel, setUiHooks);
var reportData = await _apiCallExecutor.ExecuteAsync(getRecords);
await getRecords.Done;
...
I have this non-async Task> which just requests:
TaskCompletionSource<ObservableCollection<ItemDto>> tcs = new TaskCompletionSource<ObservableCollection<ItemDto>>();
ObservableCollection<ItemDto> results = new ObservableCollection<ItemDto>();
try
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.OpenTimeout = new TimeSpan(0, 0, 30);
binding.CloseTimeout = new TimeSpan(0, 0, 30);
binding.SendTimeout = new TimeSpan(0, 0, 30);
binding.ReceiveTimeout = new TimeSpan(0, 0, 30);
MobileClient clientMobile = new MobileClient(binding, new EndpointAddress(_endpointUrl));
clientMobile.FindItemsCompleted += (object sender, FindItemsCompletedEventArgs e) =>
{
if (e.Error != null)
{
_error = e.Error.Message;
tcs.TrySetException(e.Error);
}
else if (e.Cancelled)
{
_error = "Cancelled";
tcs.TrySetCanceled();
}
if (string.IsNullOrWhiteSpace(_error) && e.Result.Count() > 0)
{
results = SetItemList(e.Result);
tcs.TrySetResult(results);
}
clientMobile.CloseAsync();
};
clientMobile.FindItemsAsync(SetSearchParam(searchString, 100));
}
catch (Exception)
{
results = new ObservableCollection<ItemDto>();
tcs.TrySetResult(results);
}
return tcs.Task;
Yes, I know, nothing special, it's just that this
clientMobile.FindItemsAsync(SetSearchParam(searchString, 100))
is a call to a void method, which in turn calls another void method which sets a few params in order to then call an async method which itself calls an async method which performs an async operation to return the list of Items.
Problem is, I have no control whatsoever of anything beyond the scope of this Task above, because everything I just explained is part of an API, in which I'm not allowed to touch, and of which I can make no comment, regarding the way it works, as the policy is for me to adapt my work to it... -_-
So, in order to do that, I must kill this call to the FindItemsAsync, as soon as a total of 1 minute has passed... I tried setting the above timespans to a minute each (first worked, now some changes have been made and no go), I tried reducing to half the time, and no go...
Here's the code which is calling this Task:
public void LoadItemList(string searchString)
{
_itemList = new ObservableCollection<ItemDto>();
// Calls the Task LoadList.
var result = LoadList(searchString).Result;
if (result != null && result != new ObservableCollection<ItemDto>())
{
_itemList = result;
}
else
{
_isTaskCompleted = false;
}
_isListEmpty = (_itemList != new ObservableCollection<ItemDto>()) ? false : true;
}
and below is the code which calls the caller of this task... (what a mess -_-):
void Init(string searchString = "")
{
Device.BeginInvokeOnMainThread(async () =>
{
if (!LoadingStackLayout.IsVisible && !LoadingActivityIndicator.IsRunning)
{
ToggleDisplayLoadingListView(true);
}
await Task.Run(() => _listVM.LoadItemList(searchString));
ToggleDisplayLoadingListView();
if (!string.IsNullOrWhiteSpace(_listVM.Error))
{
await DisplayAlert("Error", _listVM.Error, "OK");
}
else if (_listVM.AdList != null && !_listVM.IsListEmpty)
{
ItemListView.IsVisible = true;
ItemListView.ItemsSource = _listVM.ItemList;
}
else if (!_listVM.IsTaskCompleted || _listVM.IsListEmpty)
{
await DisplayAlert("", "At the moment it is not possible to show results for your search.", "OK");
}
else if (_listVM.ItemList.Count == 0)
{
await DisplayAlert("", "At the moment there are no results for your search.", "OK");
}
});
}
At the moment I'm trying to implement the MVVM arch...
Really, thank you so much for your help on this matter, it's been great, and I really apologize for all this inconvenience...
EDIT
Sorry because I didn't explain my objective clearly; it is: I need to fetch a list of Items accessing an API that just communicates with me via a void method FindItemsAsync. I have 60 seconds to fetch all those items. If something goes wrong, or if timeout, I have to cancel the process and inform the user something went wrong.
That doesn't happen. It never cancels. Either gets me the Items, or stays loading forever, dispite my hardest tries... I'm new to tasks and most of this stuff, hence my constant issues...
You can call CloseAsync when your cancellation token expires.
//Creates an object which cancels itself after 5000 ms
var cancel = new CancellationTokenSource(5000);
//Give "cancel.Token" as a submethod parameter
public void SomeMethod(CancellationToken cancelToken)
{
...
//Then use the CancellationToken to force close the connection once you created it
cancelToken.Register(()=> clientMobile.CloseAsync());
}
It will cut down the connection.
I want to prove that re-using instances of OrganizationServiceProxy between threads will cause problems.
This console app does not have a problem re-using the same instance of OrganizationServiceProxy between threads:
class Program
{
private static OrganizationServiceProxy Service { get; set; }
static void Main(string[] args)
{
Connect(); // Initializes Service
for (int i = 0; i < 100; i++)
{
int index = i;
Task.Run(() =>
{
for (int i2 = 0; i2 < 10; i2++)
{
try
{
Console.WriteLine("Creating" + index);
Entity record = new Entity("account");
record.Id = new Guid("4986e130-45f7-e411-9454-00155d91de01");
record["name"] = index + " - " + i2;
Service.Update(record);
Console.WriteLine("Created" + index);
}
catch (Exception e)
{ }
}
});
}
Console.ReadLine(); // the name of the record ends up as 99 - 9, which is right
}
/* Initialize Service */
private static bool Connect()
{
try
{
ClientCredentials cred = new ClientCredentials();
cred.UserName.UserName = #"r";
cred.UserName.Password = #"";
IServiceManagement<IOrganizationService> serviceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(#"/XRMServices/2011/Organization.svc"));
Service = new OrganizationServiceProxy(serviceManagement, cred);
var who = new Microsoft.Crm.Sdk.Messages.WhoAmIRequest(); // used to test the connection
var whoResponse = (Microsoft.Crm.Sdk.Messages.WhoAmIResponse)Service.Execute(who); // this fails if not connected
}
catch (Exception e)
{
Console.WriteLine("Connecting to CRM.\n" + e.Message + ((e.InnerException != null) ? "\n" + e.InnerException.Message : ""));
return false;
}
return true;
}
}
The SDK states that any instance members of OrganizationServiceProxy are not guaranteed to be thread safe.
How can I cause a problem with an OrganizationServiceProxy shared between threads?
What kinds of problem are to be expected?
I'm not sure I know the specific answer to your question, but something that is marked as not guaranteed of being thread-safe just means exactly that: It may be safe, but the author has not tested for it or specifically written any thread-safe code for those classes, and thus cannot guarantee thread safety.
I do know that thread-safety definitely comes into play with Plugins on the server. This is why you are not supposed to use local fields in a Plugin class. The Plugin engine re-uses the instances of your Plugin class instead of re-instantiating them for each execution. This means it is possible that your Plugin could execute with "old data" in those local fields that was used by the last thread, which could obviously cause all kinds of problems.
I'm using WebClient object in to poll some data from server.
It's working good and it's updating text block fine. Till I don't use map on same Page. When I add a map, only one request get completed and data is retrieved only once.
This is the code for getting messages:
public MessagesPage()
{
InitializeComponent();
new System.Threading.Timer(messagePolling, null, 0, 5000); // every 5 seconds
}
void messagePolling(object state)
{
getMessages(Const.GET_MESSAGES_URL + uuid);
}
private void getMessages(string uri)
{
WebClient webClient = new WebClient();
webClient.DownloadStringAsync(new Uri(uri));
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(messagesResponseCompleted);
}
void messagesResponseCompleted(object sender, DownloadStringCompletedEventArgs e)
{
lock (this)
{
try
{
string s = e.Result;
if (s.Length > 0)
{
List<Message> messagesResult = JSONHelper.Deserialize<List<Message>>(s);
foreach (Message m in messagesResult)
{
tbMessages.Text += m.message + "\n";
}
}
else
{
tbMessages.Text += "No new messages #: " + System.DateTime.Now + "\n";
}
}
catch (System.Net.WebException we)
{
MessageBox.Show(we.Message);
}
}
}
Anyone?
The WebClient response is processed on the UI thread - so you don't need the lock that you have in your event handler.
For your particular problem - is this just occurring in the emulator? I've seen quite a few timer issues with the emulator - but never anything similar on the real phone.
As an aside, I believe in general it's better to use HttpWebRequest rather than WebClient - see the explanation here of webclient using the UI thread Silverlight Background Thread using WebClient - for your particular code I don't think this will be a problem.
If using
System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 5000);
myDispatcherTimer.Tick += new EventHandler(messagePolling);
myDispatcherTimer.Start();
instead of
new System.Threading.Timer(messagePolling, null, 0, 5000); // every 5 seconds
is working fine =)