public void StringAsyncDownloadTest() { UTF8Encoding encoding = new UTF8Encoding(); byte[] contentAsBytes = encoding.GetBytes(TestResources.CharacterSheet); MemoryStream sourceResponseStream = new MemoryStream(); sourceResponseStream.Write(contentAsBytes, 0, contentAsBytes.Length); sourceResponseStream.Position = 0; Mock <HttpWebRequest> mockRequest = MockManager.Mock <HttpWebRequest>(Constructor.NotMocked); MockObject <HttpWebResponse> mockResponse = MockManager.MockObject <HttpWebResponse>(Constructor.Mocked); mockResponse.ExpectAndReturn("GetResponseStream", sourceResponseStream); mockRequest.ExpectAndReturn("GetResponse", mockResponse.Object); _stringAsyncCompletedTrigger = new AutoResetEvent(false); HttpWebService service = new HttpWebService(); service.DownloadStringAsync("http://www.battleclinic.com", StringAysncDownloadTestCompleted, null); _stringAsyncCompletedTrigger.WaitOne(); if (_stringAsyncDownloadResult.Error != null) { Assert.Fail(_stringAsyncDownloadResult.Error.Message); } Assert.AreEqual(TestResources.CharacterSheet, _stringAsyncDownloadResult.Result); sourceResponseStream.Close(); _stringAsyncCompletedTrigger = null; _stringAsyncDownloadResult = null; }
/// <summary> /// Callback method for synchronisation check. The user's clock is deemed to be in sync with BattleClinic time /// if it is no more than 60 seconds different to BattleClinic time as local time /// </summary> /// <param name="e"></param> /// <param name="userState"></param> private static void SyncDownloadCompleted(DownloadStringAsyncResult e, object userState) { DateTime completionTime = DateTime.Now; SyncState state = (SyncState)userState; bool isSynchronised = true; DateTime timeNow = DateTime.MinValue; if (e.Error == null) { string timeString = e.Result; if (timeString != String.Empty) { try { timeNow = DateTime.ParseExact(timeString, "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz", CultureInfo.InvariantCulture); double timediff = Math.Abs((timeNow.ToLocalTime() - completionTime).TotalSeconds); isSynchronised = timediff < 60; } catch (Exception ex) { ExceptionHandler.LogException(ex, true); } } } state.Callback(isSynchronised, timeNow, completionTime); }
private void StringAysncDownloadTestCompleted(DownloadStringAsyncResult e, object state) { _stringAsyncDownloadResult = e; _stringAsyncCompletedTrigger.Set(); }