public static async Task <bool> Kill(NetworkObject bandit) { if (bandit == null) { GlobalLog.Error("[KillBandit] Bandit object is null."); return(false); } await bandit.WalkablePosition().ComeAtOnce(); if (!await OpenBanditPanel(bandit)) { return(false); } var err = LokiPoe.InGameState.BanditPanel.KillBandit(); if (err != LokiPoe.InGameState.TalkToBanditResult.None) { GlobalLog.Error($"[KillBandit] Fail to select \"Kill\" option. Error: \"{err}\"."); return(false); } return(true); }
public IAsyncResult BeginAuthenticateAsClient( NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel); LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback); _negoState.ProcessAuthentication(result); return(result); #if DEBUG } #endif }
private void LogBuffer(long size) { if (!SocketsEventSource.Log.IsEnabled()) { if (GlobalLog.IsEnabled) { GlobalLog.AssertFormat("AcceptOverlappedAsyncResult#{0}::LogBuffer()|Logging is off!", LoggingHash.HashString(this)); } Debug.Fail("AcceptOverlappedAsyncResult#" + LoggingHash.HashString(this) + "::LogBuffer()|Logging is off!"); } IntPtr pinnedBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, 0); if (pinnedBuffer != IntPtr.Zero) { if (size > -1) { SocketsEventSource.Dump(pinnedBuffer, (int)Math.Min(size, (long)_buffer.Length)); } else { SocketsEventSource.Dump(pinnedBuffer, (int)_buffer.Length); } } }
/// <summary> /// 执行查询的SQL语句。查询完毕后回调 callback参数。 /// callback委派格式 delegate void OnExeQuerySQL(DbDataReader reader); /// </summary> /// <param name="sql"></param> /// <param name="callback"></param> public void ExeQuerySQL(String sql, Action <DbDataReader> callback) { DbCommand command = conn.CreateCommand(); command.CommandText = sql; command.CommandType = CommandType.Text; try { conn.Open(); LogSQL(sql); callback(command.ExecuteReader()); } catch (Exception e) { GlobalLog.Debug(string.Format("SQL Error: {0} \r\n{1}", sql, e.Message)); throw e; } finally { conn.Close(); } }
internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent) { if (GlobalLog.IsEnabled) { GlobalLog.Print("NetworkStream#" + LoggingHash.HashString(this) + "::SetSocketTimeoutOption() mode:" + mode + " silent:" + silent + " timeout:" + timeout + " m_CurrentReadTimeout:" + _currentReadTimeout + " m_CurrentWriteTimeout:" + _currentWriteTimeout); } GlobalLog.ThreadContract(ThreadKinds.Unknown, "NetworkStream#" + LoggingHash.HashString(this) + "::SetSocketTimeoutOption"); if (timeout < 0) { timeout = 0; // -1 becomes 0 for the winsock stack } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { return; } if (mode == SocketShutdown.Send || mode == SocketShutdown.Both) { if (timeout != _currentWriteTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout, silent); _currentWriteTimeout = timeout; } } if (mode == SocketShutdown.Receive || mode == SocketShutdown.Both) { if (timeout != _currentReadTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout, silent); _currentReadTimeout = timeout; } } }
public override UIHandlerAction HandleWindow(IntPtr topLevelhWnd, IntPtr hwnd, System.Diagnostics.Process process, string title, UIHandlerNotification notification) { // Sleep for a bit. Takes a bit longer for window to be ready in Longhorn. Thread.Sleep(800); // Get a reference to the IE window... GlobalLog.LogDebug("Finding IE window"); AutomationElement ieWindow = AutomationElement.FromHandle(topLevelhWnd); if (ApplicationDeploymentHelper.GetIEVersion() >= 8) { GlobalLog.LogDebug("IE8+ present, using IWebBrowser2 Navigate() for reliability"); Thread.Sleep(3000); // Other approaches are fine until they meet LCIE. // IF this proves to be 100% reliable, this could be the only implementation. IENavigationHelper.NavigateInternetExplorer(uriToNavigate.ToString(), process.MainWindowHandle); } else { NavigateIEWindow(ieWindow, uriToNavigate); } return(UIHandlerAction.Unhandled); }
public async Task <bool> Run() { var area = World.CurrentArea; if (!area.IsHideoutArea && !area.IsMapRoom) { return(false); } await Coroutines.CloseBlockingWindows(); var golemSkill = SkillBar.Skills.FirstOrDefault(s => s.IsOnSkillBar && s.SkillTags.Contains("golem")); if (golemSkill != null) { var golemObj = golemSkill.DeployedObjects.FirstOrDefault() as Monster; if (golemObj == null || golemObj.HealthPercent < MinGolemHpPercent) { GlobalLog.Debug($"[CastAuraTask] Now summoning \"{golemSkill.Name}\"."); SkillBar.Use(golemSkill.Slot, false); await Wait.SleepSafe(100); await Coroutines.FinishCurrentAction(); await Wait.SleepSafe(100); } } var auras = GetAurasForCast(); if (auras.Count > 0 && AllAuras.Any(a => a.IsOnSkillBar)) { GlobalLog.Info($"[CastAuraTask] Found {auras.Count} aura(s) for casting."); await CastAuras(auras); } return(false); }
/// <summary> /// Starts the variation loop on a new thread. /// </summary> /// <remarks> /// The Dispatcher thread is kept seperate from the VariationPerformer thread /// so nested loop actions, such as opening dialogs and drag/drop, may run. /// </remarks> protected void StartLoop() { CommonStorage.Current.Store("Controller", this); // // Ensure we log any unhandled exceptions. // Dispatcher.CurrentDispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(_OnDispatcherException); // string execDir = DriverState.ExecutionDirectory;//Harness.Current.RemoteSite["STI_ExecutionDirectory"]; string currentDir = Environment.CurrentDirectory; // // If the app is a new process, the current directory will likely be // different than the original execution directory. Copy files // from the original directory to the current one. // if (!String.Equals(currentDir, execDir)) { GlobalLog.LogStatus("Current directory is different than original execution directory."); GlobalLog.LogStatus("Execution directory: " + execDir); GlobalLog.LogStatus("Current directory: " + currentDir); GlobalLog.LogStatus("Changing current directory to original execution directory..."); Environment.CurrentDirectory = execDir; } this.TestDispatcher = Dispatcher.CurrentDispatcher; Thread thread = new Thread(new ThreadStart(_RunLoop)); thread.Start(); }
public static async Task <bool> TurnInQuest() { if (!Helpers.PlayerHasQuestItem(QuestItemMetadata.EyeOfDesire)) { return(false); } if (World.Act4.CrystalVeins.IsCurrentArea) { var dialla = Helpers.LadyDialla; if (dialla == null) { GlobalLog.Error("[KingOfDesire] Fail to detect Lady Dialla in Crystal Veins."); ErrorManager.ReportCriticalError(); return(true); } await Helpers.TalkTo(dialla); return(true); } await Travel.To(World.Act4.CrystalVeins); return(true); }
public static async Task <bool> KillGemlings() { if (_finished) { return(false); } if (World.Act8.GrainGate.IsCurrentArea) { var gemling = CachedGemlings.FirstOrDefault(); if (gemling != null) { var pos = gemling.Position; if (pos.Distance > 30) { pos.Come(); } else { var gemlingObj = gemling.Object; if (gemlingObj == null) { GlobalLog.Warn($"[GemlingLegion] Gemling with id {gemling.Id} no longer exist."); CachedGemlings.RemoveAt(0); } } return(true); } await Helpers.Explore(); return(true); } await Travel.To(World.Act8.GrainGate); return(true); }
/// <summary> /// Constructor for Vscan Common /// Master is specivif Path /// </summary> /// <param name="testwin">Window to capture image of</param> /// <param name="test">Calling Test</param> /// <param name="master">Master Name</param> public VScanCommon(Window testwin, object test, string master) { if (test != null && testwin != null) { masterPath = Common.ResolvePath(test); Index = new LayoutMasterIndex(null); if (master == null || master == string.Empty) { index.FileName = test.GetType().Name; } else { index.FileName = master; } GlobalLog.LogStatus("Master Name : {0}", index.FileName); index.Path = masterPath; GlobalLog.LogStatus("Master Path : {0}", index.Path); SetWindow(testwin); } }
void ConnectCallback(IAsyncResult result) { GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::ConnectCallback"); try { transport.EndGetConnection(result); if (cancelled) { Complete(null, result); } else { // Detected durring Begin/EndGetConnection, restrictable using DeliveryFormat bool allowUnicode = IsUnicodeSupported(); ValidateUnicodeRequirement(message, recipients, allowUnicode); transport.BeginSendMail(message.Sender ?? message.From, recipients, message.BuildDeliveryStatusNotificationString(), allowUnicode, new AsyncCallback(SendMailCallback), result.AsyncState); } } catch (Exception e) { Complete(e, result); } GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::ConnectCallback"); }
public SecurityBuffer(byte[] data, int offset, int size, SecurityBufferType tokentype) { if (offset < 0 || offset > (data == null ? 0 : data.Length)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecurityBuffer::.ctor", "'offset' out of range. [" + offset + "]"); } Debug.Fail("SecurityBuffer::.ctor", "'offset' out of range. [" + offset + "]"); } if (size < 0 || size > (data == null ? 0 : data.Length - offset)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecurityBuffer::.ctor", "'size' out of range. [" + size + "]"); } Debug.Fail("SecurityBuffer::.ctor", "'size' out of range. [" + size + "]"); } this.offset = data == null || offset < 0 ? 0 : Math.Min(offset, data.Length); this.size = data == null || size < 0 ? 0 : Math.Min(size, data.Length - this.offset); this.type = tokentype; this.token = size == 0 ? null : data; }
private bool CheckSpn() { if (_Context.IsKerberos) { return(true); } if (_ExtendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Never || _ExtendedProtectionPolicy.CustomServiceNames == null) { return(true); } if (!AuthenticationManager.OSSupportsExtendedProtection) { GlobalLog.Assert(_ExtendedProtectionPolicy.PolicyEnforcement != PolicyEnforcement.Always, "User managed to set PolicyEnforcement.Always when the OS does not support extended protection!"); return(true); } string clientSpn = _Context.ClientSpecifiedSpn; if (String.IsNullOrEmpty(clientSpn)) { if (_ExtendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported) { return(true); } } else { return(_ExtendedProtectionPolicy.CustomServiceNames.Contains(clientSpn)); } return(false); }
protected override bool ReleaseHandle() { GlobalLog.Print( "SafeCloseSocket#" + Logging.HashString(this) + "::ReleaseHandle() m_InnerSocket=" + _innerSocket == null ? "null" : Logging.HashString(_innerSocket)); _released = true; InnerSafeCloseSocket innerSocket = _innerSocket == null ? null : Interlocked.Exchange <InnerSafeCloseSocket>(ref _innerSocket, null); if (innerSocket != null) { #if DEBUG // On AppDomain unload we may still have pending Overlapped operations. // ThreadPoolBoundHandle should handle this scenario by canceling them. innerSocket.LogRemainingOperations(); #endif innerSocket.DangerousRelease(); } InnerReleaseHandle(); return(true); }
// This method is called after an asynchronous call is made for the user. // It checks and acts accordingly if the IO: // 1) completed synchronously. // 2) was pended. // 3) failed. internal unsafe SocketError CheckAsyncCallOverlappedResult(SocketError errorCode) { if (GlobalLog.IsEnabled) { GlobalLog.Print( "BaseOverlappedAsyncResult#" + LoggingHash.HashString(this) + "::CheckAsyncCallOverlappedResult(" + errorCode.ToString() + ")"); } if (errorCode == SocketError.Success || errorCode == SocketError.IOPending) { // Ignore cases in which a completion packet will be queued: // we'll deal with this IO in the callback. return(SocketError.Success); } // In the remaining cases a completion packet will NOT be queued: // we have to call the callback explicitly signaling an error. ErrorCode = (int)errorCode; Result = -1; ReleaseUnmanagedStructures(); // Additional release for the completion that won't happen. return(errorCode); }
public static async Task <bool> ClearFetidPool() { if (_finished) { return(false); } if (World.Act1.FetidPool.IsCurrentArea) { if (await TrackMobLogic.Execute()) { return(true); } if (!await CombatAreaCache.Current.Explorer.Execute()) { if (QuestManager.GetState(Quests.DirtyJob) <= FinishedStateMinimum) { return(false); } GlobalLog.Error("[ClearFetidPool] Fetid Pool is fully explored but not all monsters were killed. Now going to create a new Fetid Pool instance."); Travel.RequestNewInstance(World.Act1.FetidPool); if (!await PlayerAction.TpToTown()) { ErrorManager.ReportError(); } } return(true); } await Travel.To(World.Act1.FetidPool); return(true); }
// private void CheckRetrieveOnResponse(Stream responseStream) { GlobalLog.Assert(_ProtocolStatus == CacheValidationStatus.Continue || _ProtocolStatus == CacheValidationStatus.RetryResponseFromServer, "CheckRetrieveOnResponse()|Unexpected _ProtocolStatus = ", _ProtocolStatus); bool closeCacheStream = true; try { // This will inspect the live response on the correctness matter switch (_ProtocolStatus = ValidateResponse()) { case CacheValidationStatus.Continue: closeCacheStream = false; // The response looks good break; case CacheValidationStatus.RetryResponseFromServer: closeCacheStream = false; break; case CacheValidationStatus.Fail: _ProtocolStatus = CacheValidationStatus.Fail; _ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_fail, "ValidateResponse")); break; case CacheValidationStatus.DoNotUseCache: break; default: _ProtocolStatus = CacheValidationStatus.Fail; _ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_result, "ValidateResponse", _Validator.ValidationStatus.ToString())); if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_unexpected_status, "ValidateResponse()", _Validator.ValidationStatus.ToString())); } break; } } catch (Exception e) { closeCacheStream = true; _ProtocolException = e; _ProtocolStatus = CacheValidationStatus.Fail; if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_object_and_exception, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), (e is WebException? e.Message: e.ToString()))); } } finally { // This is to release cache entry in case we are not interested in it if (closeCacheStream && _ResponseStream != null) { _ResponseStream.Close(); _ResponseStream = null; _Validator.CacheStream = Stream.Null; } } if (_ProtocolStatus != CacheValidationStatus.Continue) { return; } // // only CacheValidationStatus.Continue goes here with closeCacheStream == false // try { // switch (_ProtocolStatus = RevalidateCache()) { case CacheValidationStatus.DoNotUseCache: case CacheValidationStatus.RemoveFromCache: case CacheValidationStatus.DoNotTakeFromCache: closeCacheStream = true; break; case CacheValidationStatus.ReturnCachedResponse: if (_Validator.CacheStream == null || _Validator.CacheStream == Stream.Null) { _ProtocolStatus = CacheValidationStatus.Fail; _ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_no_stream, _Validator.CacheKey)); if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_null_cached_stream, "RevalidateCache()")); } break; } Stream stream = _Validator.CacheStream; if (_Validator.CacheStreamOffset != 0L || _Validator.CacheStreamLength != _Validator.CacheEntry.StreamSize) { stream = new RangeStream(stream, _Validator.CacheStreamOffset, _Validator.CacheStreamLength); if (Logging.On) { Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_returned_range_cache, "RevalidateCache()", _Validator.CacheStreamOffset, _Validator.CacheStreamLength)); } } _ResponseStream = stream; _ResponseStreamLength = _Validator.CacheStreamLength; break; case CacheValidationStatus.CombineCachedAndServerResponse: if (_Validator.CacheStream == null || _Validator.CacheStream == Stream.Null) { _ProtocolStatus = CacheValidationStatus.Fail; _ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_no_stream, _Validator.CacheKey)); if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_requested_combined_but_null_cached_stream, "RevalidateCache()")); } break; } if (responseStream != null) { stream = new CombinedReadStream(_Validator.CacheStream, responseStream); } else { // So Abort can close the cache stream stream = _Validator.CacheStream; } _ResponseStream = stream; _ResponseStreamLength = _Validator.CacheStreamLength; break; case CacheValidationStatus.Fail: closeCacheStream = true; _ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_fail, "RevalidateCache")); break; default: closeCacheStream = true; _ProtocolStatus = CacheValidationStatus.Fail; _ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_result, "RevalidateCache", _Validator.ValidationStatus.ToString())); if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_unexpected_status, "RevalidateCache()", _Validator.ValidationStatus.ToString())); } break; } } catch (Exception e) { closeCacheStream = true; _ProtocolException = e; _ProtocolStatus = CacheValidationStatus.Fail; if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_object_and_exception, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), (e is WebException? e.Message: e.ToString()))); } } finally { // This is to release cache entry in case we are not interested in it if (closeCacheStream && _ResponseStream != null) { _ResponseStream.Close(); _ResponseStream = null; _Validator.CacheStream = Stream.Null; } } }
/// <summary> /// Performs the Activation step /// </summary> /// <returns>returns true if the rest of the steps should be executed, otherwise, false</returns> protected override bool BeginStep() { //Create ApplicationMonitor appMonitor = new ApplicationMonitor(); // If defined, set a value in property bag. Used for communication test variations to target app if (PropertyBagValue != "") { // Update this code to allow > 1 prop bag values being set at once string[] values = PropertyBagValue.Trim().Split('='); if (values.Length == 2) { DictionaryStore.Current[values[0].Trim()] = values[1].Trim(); } else { throw new System.ArgumentException("Values must be a single 'foo=bar' format"); } } if (hostingPolicyResetter != null) { hostingPolicyResetter.Dispose(); } if (StrictHostingMode) { hostingPolicyResetter = HostingRuntimePolicyHelper.SetHostingRuntimePolicyValues( doNotLaunchV3AppInV4Runtime: true); } else { hostingPolicyResetter = HostingRuntimePolicyHelper.SetHostingRuntimePolicyValues( doNotLaunchV3AppInV4Runtime: false); } // upload files to FileHost is specified and scheme is not local if (Scheme != ActivationScheme.Local) { if (SupportFiles.Length > 0) { // Create host to copy files to... fileHost = new FileHost(UserDefinedDirectory, (Scheme == ActivationScheme.HttpInternetExternal)); // Upload each file foreach (SupportFile suppFile in SupportFiles) { // Whether to copy foo\bar\baz.xbap to the foo\bar created on the remote machine or just flattened fileHost.PreserveDirectoryStructure = suppFile.PreserveDirectoryStructure; if (suppFile.IncludeDependencies && !string.IsNullOrEmpty(suppFile.TargetDirectory)) { GlobalLog.LogEvidence("TargetDirectory with IncludeDependencies not yet implemented"); throw new NotImplementedException("TargetDirectory with IncludeDependencies not yet supported"); } if (suppFile.CustomTestScratchServerPath == null) { if (suppFile.IncludeDependencies) { fileHost.UploadFileWithDependencies(suppFile.Name); } else { fileHost.UploadFile(suppFile.Name, suppFile.TargetDirectory); } } else { fileHost.UploadFileNonDefaultServer(suppFile.Name, suppFile.CustomTestScratchServerPath); } } } // If no support files are listed, check the parent steps to see if one is a FileHostStep. // If this is the case, no need to upload the files as the FileHostStep has already. // Don't set throttle rate; this should be set in the markup for the parent's filehost. else { LoaderStep parent = this.ParentStep; while (parent != null) { if (parent.GetType() == typeof(Microsoft.Test.Loaders.Steps.FileHostStep)) { this.fileHost = ((FileHostStep)parent).fileHost; break; } // Failed to find it in the immediate parent: try til we hit null or the right one parent = parent.ParentStep; } } } // register UIHandlers foreach (UIHandler handler in UIHandlers) { if (handler.NamedRegistration != null) { appMonitor.RegisterUIHandler(handler, handler.NamedRegistration, handler.Notification); } else { appMonitor.RegisterUIHandler(handler, handler.ProcessName, handler.WindowTitle, handler.Notification); } } string param = ""; if (FileName.StartsWith("&") && FileName.EndsWith("&")) { param = DictionaryStore.Current[FileName.Substring(1, FileName.Length - 2)]; if (param == null) { throw new InvalidOperationException(FileName + " is not defined in the property bag; cannot be used to launch app"); } } else { // Allows for launching things in %program files%, which is localized. param = Environment.ExpandEnvironmentVariables(FileName); } if (Scheme != ActivationScheme.Local) { FileHostUriScheme hostScheme = FileHostUriScheme.Unc; if (Scheme != ActivationScheme.HttpInternetExternal) { hostScheme = (FileHostUriScheme)Enum.Parse(typeof(FileHostUriScheme), Scheme.ToString()); } param = fileHost.GetUri(FileName, hostScheme).ToString(); } // Clear the fusion cache by default. Can be disabled for custom ClickOnce scenarios if (ClearFusionCache) { ApplicationDeploymentHelper.CleanClickOnceCache(); } // Clear IE History but only if specified (defaults to false). Only matters for history-based navigation if (ClearIEHistory) { ApplicationDeploymentHelper.ClearIEHistory(); } // Launch the appropriate handler... switch (Method) { case ActivationMethod.Launch: { // This only works for local paths for security reasons. if (PresentationHostDebugMode) { param = Path.GetFullPath(param); // Workaround ... for some reason on XP64 there's no guarantee that it will actually find PresHost // Even though it verily is in the SysWOW64 directory. Solution... find the right one before we try string presHostPath = "presentationhost.exe"; if ((Environment.OSVersion.Version.Major == 5)) { presHostPath = (Directory.GetFiles(Environment.GetEnvironmentVariable("SystemRoot"), "PresentationHost.exe", SearchOption.AllDirectories))[0]; } appMonitor.StartProcess(presHostPath, " -debug \"" + param + "\""); } else { // Launch process with specified arguments. If shell: specified, then start that way. // If the arguments are for the URL, directly concatenate them. if ((Arguments.Length > 6) && (Arguments.ToLowerInvariant().StartsWith("shell:"))) { appMonitor.StartProcess(param, Environment.ExpandEnvironmentVariables(Arguments.Substring(6))); } else if ((Arguments.Length > 11) && (Arguments.ToLowerInvariant().StartsWith("currentdir:"))) { appMonitor.StartProcess(param, Path.Combine(Environment.CurrentDirectory, Arguments.Substring(11))); } else { appMonitor.StartProcess(param + Arguments); } } break; } case ActivationMethod.Navigate: { // If local we need to fully qualify the path if (Scheme == ActivationScheme.Local) { param = Path.GetFullPath(param); } // Fail to IE, since it has far more tests. string defaultBrowserExecutable = "iexplore.exe"; try { defaultBrowserExecutable = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Clients\StartMenuInternet", null, "iexplore.exe").ToString(); } catch (Exception) { try { defaultBrowserExecutable = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Clients\StartMenuInternet", null, "iexplore.exe").ToString(); } catch (Exception) { // Do nothing, some machines have been seen in weird states where this is undefined. Log it anyways. GlobalLog.LogDebug("Unable to get StartMenuInternet key, FireFox or other non-standard browser tests may be affected. Contact Microsoft if this is the case"); } } // Handle the case where this value exists but isnt set to anything usable. IE is far more common so fall back to it. if (string.IsNullOrEmpty(defaultBrowserExecutable)) { defaultBrowserExecutable = "iexplore.exe"; } // start the default browser... currently just FF or IE. if (defaultBrowserExecutable.ToLowerInvariant().Contains("iexplore")) { // Create & register IE navigation handler // IE can be strange: About:NavigateIE sometimes gets a cancelled navigation // Workaround: Be less sensitive about the window title we trigger on. appMonitor.RegisterUIHandler(new NavigateIE(param + Arguments), "iexplore", "RegExp:(Internet Explorer)", UIHandlerNotification.All); appMonitor.StartProcess("iexplore.exe", "about:NavigateIE"); } else if (defaultBrowserExecutable.ToLowerInvariant().Contains("firefox")) { if (Scheme == ActivationScheme.Unc) { param = param.Replace("file:", "").Replace("/", @"\"); } } else { throw new InvalidOperationException("Don't know how to navigate an instance of \"" + defaultBrowserExecutable + "\" browser!!! Contact Microsoft with this message."); } break; } // GOTO used here for fallthrough since there's only 2 lines difference. case ActivationMethod.EHome: goto case ActivationMethod.EHomeFullScreen; case ActivationMethod.EHomeFullScreen: { // If local we need to fully qualify the path if (Scheme == ActivationScheme.Local) { param = Path.GetFullPath(param); } // Get a reference to the path for the ehome exe... string eHomePath = Environment.GetEnvironmentVariable("SystemRoot") + "\\ehome\\ehshell.exe"; // Fail hard if EHome isnt present on the system. // Need to mark testcases accurately in test DB to avoid this. if (!File.Exists(eHomePath)) { throw new InvalidOperationException("\"Ehome\" or \"EHomeFullScreen\" method selected but case was run on non-Media-Center-enabled SKU! \n Contact Microsoft for more info on this issue."); } // Construct args with path to content to launch (MUST be a Uri) string eHomeArgs = "/url:\"" + param + "\""; // Tack on the argument for full screen if requested if (Method == ActivationMethod.EHomeFullScreen) { eHomeArgs += " /directmedia:general"; } // Start MCE... appMonitor.StartProcess(eHomePath, eHomeArgs); break; } } // Store the activation path into the property bag. This way apps or child steps can directly figure out the deployment URI DictionaryStore.Current["ActivationStepUri"] = param; return(true); }
// // This is (optionally) called after receiveing a live response // protected internal override CacheValidationStatus RevalidateCache() { if (HttpProxyMode) { return(base.RevalidateCache()); } if (Policy.Level >= RequestCacheLevel.Reload) { // For those policies cache is never returned GlobalLog.Assert("RevalidateCache()", "This validator should not be called for policy = " + Policy.ToString()); if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_validator_invalid_for_policy, Policy.ToString())); } return(CacheValidationStatus.DoNotTakeFromCache); } // First check is do we still hold on a cached entry? if (CacheStream == Stream.Null) { return(CacheValidationStatus.DoNotTakeFromCache); } // // This is a second+ time validation after receiving at least one response // CacheValidationStatus result = CacheValidationStatus.DoNotTakeFromCache; FtpWebResponse resp = Response as FtpWebResponse; if (resp == null) { // This will result to an application error return(CacheValidationStatus.DoNotTakeFromCache); } if (resp.StatusCode == FtpStatusCode.FileStatus) { if (Logging.On) { Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_response_last_modified, resp.LastModified.ToUniversalTime().ToString("r", CultureInfo.InvariantCulture), resp.ContentLength)); } if (Logging.On) { Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_cache_last_modified, CacheEntry.LastModifiedUtc.ToString("r", CultureInfo.InvariantCulture), CacheEntry.StreamSize)); } if (CacheStreamOffset != 0L && CacheEntry.IsPartialEntry) { //should never happen if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_partial_and_non_zero_content_offset, CacheStreamOffset.ToString(CultureInfo.InvariantCulture))); } result = CacheValidationStatus.DoNotTakeFromCache; } if (resp.LastModified.ToUniversalTime() == CacheEntry.LastModifiedUtc) { if (CacheEntry.IsPartialEntry) { // A caller will need to use Validator.CacheEntry.StreamSize to figure out what the restart point is if (resp.ContentLength > 0) { this.CacheStreamLength = resp.ContentLength; } else { this.CacheStreamLength = -1; } result = CacheValidationStatus.CombineCachedAndServerResponse; } else if (resp.ContentLength == CacheEntry.StreamSize) { result = CacheValidationStatus.ReturnCachedResponse; } else { result = CacheValidationStatus.DoNotTakeFromCache; } } else { result = CacheValidationStatus.DoNotTakeFromCache; } } else { result = CacheValidationStatus.DoNotTakeFromCache; } return(result); }
// // Private methods // // // This method may be invoked as part of the request submission but before issuing a live request // private void CheckRetrieveBeforeSubmit() { GlobalLog.Assert(_ProtocolStatus == CacheValidationStatus.Continue, "CheckRetrieveBeforeSubmit()|Unexpected _ProtocolStatus = {0}", _ProtocolStatus); try { while (true) { RequestCacheEntry cacheEntry; if (_Validator.CacheStream != null && _Validator.CacheStream != Stream.Null) { // Reset to Initial state _Validator.CacheStream.Close(); _Validator.CacheStream = Stream.Null; } if (_Validator.StrictCacheErrors) { _Validator.CacheStream = _RequestCache.Retrieve(_Validator.CacheKey, out cacheEntry); } else { Stream stream; _RequestCache.TryRetrieve(_Validator.CacheKey, out cacheEntry, out stream); _Validator.CacheStream = stream; } if (cacheEntry == null) { cacheEntry = new RequestCacheEntry(); cacheEntry.IsPrivateEntry = _RequestCache.IsPrivateCache; _Validator.FetchCacheEntry(cacheEntry); } if (_Validator.CacheStream == null) { // If entry does not have a stream an empty stream wrapper must be returned. // A null or Stream.Null value stands for non existent cache entry. _Validator.CacheStream = Stream.Null; } ValidateFreshness(cacheEntry); _ProtocolStatus = ValidateCache(); // This will tell us what to do next switch (_ProtocolStatus) { case CacheValidationStatus.ReturnCachedResponse: if (_Validator.CacheStream == null || _Validator.CacheStream == Stream.Null) { if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_no_cache_entry, "ValidateCache()")); } _ProtocolStatus = CacheValidationStatus.Fail; _ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_no_stream, _Validator.CacheKey)); break; } // Final decision is made, check on a range response from cache Stream stream = _Validator.CacheStream; // The entry can now be replaced as we are not going for cache entry metadata-only update _RequestCache.UnlockEntry(_Validator.CacheStream); if (_Validator.CacheStreamOffset != 0L || _Validator.CacheStreamLength != _Validator.CacheEntry.StreamSize) { stream = new RangeStream(stream, _Validator.CacheStreamOffset, _Validator.CacheStreamLength); if (Logging.On) { Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_returned_range_cache, "ValidateCache()", _Validator.CacheStreamOffset, _Validator.CacheStreamLength)); } } _ResponseStream = stream; _ResponseStreamLength = _Validator.CacheStreamLength; break; case CacheValidationStatus.Continue: // copy a cache stream ref _ResponseStream = _Validator.CacheStream; break; case CacheValidationStatus.RetryResponseFromCache: // loop thought cache retrieve continue; case CacheValidationStatus.DoNotTakeFromCache: case CacheValidationStatus.DoNotUseCache: break; case CacheValidationStatus.Fail: _ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_fail, "ValidateCache")); break; default: _ProtocolStatus = CacheValidationStatus.Fail; _ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_result, "ValidateCache", _Validator.ValidationStatus.ToString())); if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_unexpected_status, "ValidateCache()", _Validator.ValidationStatus.ToString())); } break; } break; } } catch (Exception e) { _ProtocolStatus = CacheValidationStatus.Fail; _ProtocolException = e; if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_object_and_exception, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), (e is WebException? e.Message: e.ToString()))); } } finally { // This is to release cache entry on error if (_ResponseStream == null && _Validator.CacheStream != null && _Validator.CacheStream != Stream.Null) { _Validator.CacheStream.Close(); _Validator.CacheStream = Stream.Null; } } }
private static async Task GetFragment() { var tabs = new List <string>(ExSettings.Instance.GetTabsForCategory(ExSettings.StashingCategory.Fragment)); if (tabs.Count > 1 && StashUi.IsOpened) { var currentTab = StashUi.StashTabInfo.DisplayName; var index = tabs.IndexOf(currentTab); if (index > 0) { var tab = tabs[index]; tabs.RemoveAt(index); tabs.Insert(0, tab); } } foreach (var tab in tabs) { GlobalLog.Debug($"[TakeMapTask] Looking for Sacrifice Fragment in \"{tab}\" tab."); if (!await Inventories.OpenStashTab(tab)) { return; } if (StashUi.StashTabInfo.IsPremiumSpecial) { var tabType = StashUi.StashTabInfo.TabType; if (tabType == InventoryTabType.Fragment) { foreach (var control in SacrificeControls) { var fragment = control.CustomTabItem; if (fragment != null) { GlobalLog.Debug($"[TakeMapTask] Found \"{fragment.Name}\" in \"{tab}\" tab."); await Inventories.FastMoveFromPremiumStashTab(control); return; } GlobalLog.Debug($"[TakeMapTask] There are no Sacrifice Fragments in \"{tab}\" tab."); } } else { GlobalLog.Error($"[TakeMapTask] Incorrect tab type ({tabType}) for sacrifice fragments."); } } else { var fragment = Inventories.StashTabItems .Where(i => i.IsSacrificeFragment()) .OrderBy(i => i.Name == "Sacrifice at Midnight") // move midnights to the end of the list .FirstOrDefault(); if (fragment != null) { GlobalLog.Debug($"[TakeMapTask] Found \"{fragment.Name}\" in \"{tab}\" tab."); await Inventories.FastMoveFromStashTab(fragment.LocationTopLeft); return; } GlobalLog.Debug($"[TakeMapTask] There are no Sacrifice Fragments in \"{tab}\" tab."); } } GlobalLog.Info("[TakeMapTask] There are no Sacrifice Fragments in all tabs assigned to them. Now marking them as unavailable."); _hasFragments = false; }
// This method may add headers under the "Warning" header name protected internal override CacheValidationStatus ValidateCache() { if (HttpProxyMode) { return(base.ValidateCache()); } if (Policy.Level >= RequestCacheLevel.Reload) { // For those policies cache is never returned GlobalLog.Assert("OnValidateCache()", "This validator should not be called for policy = " + Policy.ToString()); if (Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_validator_invalid_for_policy, Policy.ToString())); } return(CacheValidationStatus.DoNotTakeFromCache); } // First check is do we have a cached entry at all? if (CacheStream == Stream.Null || CacheEntry.IsPartialEntry) { if (Policy.Level == RequestCacheLevel.CacheOnly) { // Throw because entry was not found and it's cache-only policy FailRequest(WebExceptionStatus.CacheEntryNotFound); } if (CacheStream == Stream.Null) { return(CacheValidationStatus.DoNotTakeFromCache); } // Otherwise it's a partial entry and we can go on the wire } CacheStreamOffset = 0L; CacheStreamLength = CacheEntry.StreamSize; // // Before request submission validation // if (Policy.Level == RequestCacheLevel.Revalidate || CacheEntry.IsPartialEntry) { return(TryConditionalRequest()); } long contentOffset = Request is FtpWebRequest ? ((FtpWebRequest)Request).ContentOffset: 0L; if (CacheFreshnessStatus == CacheFreshnessStatus.Fresh || Policy.Level == RequestCacheLevel.CacheOnly || Policy.Level == RequestCacheLevel.CacheIfAvailable) { if (contentOffset != 0) { if (contentOffset >= CacheStreamLength) { if (Policy.Level == RequestCacheLevel.CacheOnly) { // Throw because request is outside of cached size and it's cache-only policy FailRequest(WebExceptionStatus.CacheEntryNotFound); } return(CacheValidationStatus.DoNotTakeFromCache); } CacheStreamOffset = contentOffset; } return(CacheValidationStatus.ReturnCachedResponse); } return(CacheValidationStatus.DoNotTakeFromCache); }
// BeginWrite - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the underlying socket async send. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to written. // // Returns: // // An IASyncResult, representing the write. public IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Call BeginSend on the Socket. IAsyncResult asyncResult = chkStreamSocket.BeginSend( buffer, offset, size, SocketFlags.None, callback, state); return(asyncResult); } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif }
public async Task <bool> Run() { if (MapBot.IsOnRun) { return(false); } var area = World.CurrentArea; if (!area.IsTown && !area.IsHideoutArea) { return(false); } if (Settings.StopRequested) { GlobalLog.Warn("Stopping the bot by a user's request (stop after current map)"); Settings.StopRequested = false; BotManager.Stop(); return(true); } var mapTabs = ExSettings.Instance.GetTabsForCategory(ExSettings.StashingCategory.Map); Item map; foreach (var tab in mapTabs) { if (!await Inventories.OpenStashTab(tab)) { ErrorManager.ReportError(); return(true); } if (StashUi.StashTabInfo.IsPremiumMap) { GlobalLog.Error("Map stash tab is unsupported and there are no plans to support it in the future. Please remove it from stashing settings."); BotManager.Stop(); return(true); } if ((map = FindProperMap()) != null) { goto hasProperMap; } GlobalLog.Debug($"[TakeMapTask] Fail to find a proper map in \"{tab}\" tab."); } GlobalLog.Error("[TakeMapTask] Fail to find a proper map in all map tabs. Now stopping the bot because it cannot continue."); BotManager.Stop(); return(true); hasProperMap: GlobalLog.Info($"[TakeMapTask] Map of choice is \"{map.Name}\" (Tier: {map.MapTier})"); if (!await Inventories.FastMoveFromStashTab(map.LocationTopLeft)) { ErrorManager.ReportError(); return(true); } if (!await Wait.For(() => (map = Inventories.InventoryItems.Find(i => i.IsMap())) != null, "map appear in inventory")) { GlobalLog.Error("[TakeMapTask] Unexpected error. Map did not appear in player's inventory after fast move from stash."); return(true); } var mapPos = map.LocationTopLeft; var mapRarity = map.RarityLite(); if (mapRarity == Rarity.Unique || !map.IsIdentified || map.IsMirrored || map.IsCorrupted) { ChooseMap(mapPos); return(false); } switch (mapRarity) { case Rarity.Normal: if (!await HandleNormalMap(mapPos)) { return(true); } break; case Rarity.Magic: if (!await HandleMagicMap(mapPos)) { return(true); } break; case Rarity.Rare: if (!await HandleRareMap(mapPos)) { return(true); } break; default: GlobalLog.Error($"[TakeMapTask] Unknown map rarity: \"{mapRarity}\"."); ErrorManager.ReportCriticalError(); return(true); } UpdateMapReference(mapPos, ref map); if (map.ShouldUpgrade(Settings.VaalUpgrade) && HasCurrency(CurrencyNames.Vaal)) { if (!await CorruptMap(mapPos)) { return(true); } UpdateMapReference(mapPos, ref map); } if (map.ShouldUpgrade(Settings.FragmentUpgrade) && _hasFragments) { await GetFragment(); } ChooseMap(mapPos); return(false); }
// // This method is called after an asynchronous call is made for the user, // it checks and acts accordingly if the IO: // 1) completed synchronously. // 2) was pended. // 3) failed. // internal unsafe SocketError CheckAsyncCallOverlappedResult(SocketError errorCode) { #if DEBUG m_SavedErrorCode = errorCode; #endif // // Check if the Async IO call: // 1) was pended. // 2) completed synchronously. // 3) failed. // if (m_UseOverlappedIO) { // // we're using overlapped IO under Win9x (or NT with registry setting overriding // completion port usage) // switch (errorCode) { case 0: case SocketError.IOPending: // // the Async IO call was pended: // Queue our event to the thread pool. // GlobalLog.Assert(m_UnmanagedBlob != null, "BaseOverlappedAsyncResult#{0}::CheckAsyncCallOverlappedResult()|Unmanaged blob isn't allocated.", ValidationHelper.HashString(this)); ThreadPool.UnsafeRegisterWaitForSingleObject( m_OverlappedEvent, new WaitOrTimerCallback(OverlappedCallback), this, -1, true); // // we're done, completion will be asynchronous // in the callback. return // return(SocketError.Success); default: // // the Async IO call failed: // set the number of bytes transferred to -1 (error) // ErrorCode = (int)errorCode; Result = -1; ReleaseUnmanagedStructures(); break; } } else { #if DEBUG OverlappedCache cache = m_Cache; if (cache != null) { unsafe { NativeOverlapped *nativeOverlappedPtr = (NativeOverlapped *)cache.NativeOverlapped; if (nativeOverlappedPtr != null) { m_IntermediateNativeOverlapped = *nativeOverlappedPtr; } } } #endif // // We're using completion ports under WinNT. Release one reference on the structures for // the main thread. // ReleaseUnmanagedStructures(); switch (errorCode) { // // ignore cases in which a completion packet will be queued: // we'll deal with this IO in the callback // case 0: case SocketError.IOPending: // // ignore, do nothing // return(SocketError.Success); // // in the remaining cases a completion packet will NOT be queued: // we'll have to call the callback explicitly signaling an error // default: // // call the callback with error code // ErrorCode = (int)errorCode; Result = -1; // The AsyncResult must be cleared since the callback isn't going to be called. // Not doing so leads to a leak where the pinned cached OverlappedData continues to point to the async result object, // which points to the Socket (as well as user data) and to the OverlappedCache, preventing the OverlappedCache // finalizer from freeing the pinned OverlappedData. if (m_Cache != null) { // Could be null only if SetUnmanagedStructures weren't called. m_Cache.Overlapped.AsyncResult = null; } ReleaseUnmanagedStructures(); // Additional release for the completion that won't happen. break; } } return(errorCode); }
private unsafe static void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped *nativeOverlapped) { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.CompletionPort); using (GlobalLog.SetThreadKind(ThreadKinds.System)) { #endif // // Create an Overlapped object out of the native pointer we're provided with. // (this will NOT free the unmanaged memory in the native overlapped structure) // Overlapped callbackOverlapped = Overlapped.Unpack(nativeOverlapped); BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)callbackOverlapped.AsyncResult; // The AsyncResult must be cleared before the callback is called (i.e. before ExtractCache is called). // Not doing so leads to a leak where the pinned cached OverlappedData continues to point to the async result object, // which points to the Socket (as well as user data), which points to the OverlappedCache, preventing the OverlappedCache // finalizer from freeing the pinned OverlappedData. callbackOverlapped.AsyncResult = null; object returnObject = null; GlobalLog.Assert(!asyncResult.InternalPeekCompleted, "BaseOverlappedAsyncResult#{0}::CompletionPortCallback()|asyncResult.IsCompleted", ValidationHelper.HashString(asyncResult)); GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::CompletionPortCallback" + " errorCode:" + errorCode.ToString() + " numBytes:" + numBytes.ToString() + " pOverlapped:" + ((int)nativeOverlapped).ToString()); // // complete the IO and invoke the user's callback // SocketError socketError = (SocketError)errorCode; if (socketError != SocketError.Success && socketError != SocketError.OperationAborted) { Socket socket = asyncResult.AsyncObject as Socket; if (socket == null) { socketError = SocketError.NotSocket; } else if (socket.CleanedUp) { socketError = SocketError.OperationAborted; } else { try { // // The Async IO completed with a failure. // here we need to call WSAGetOverlappedResult() just so Marshal.GetLastWin32Error() will return the correct error. // bool success = UnsafeNclNativeMethods.OSSOCK.WSAGetOverlappedResult( socket.SafeHandle, (IntPtr)nativeOverlapped, out numBytes, false, IntPtr.Zero); if (!success) { socketError = (SocketError)Marshal.GetLastWin32Error(); GlobalLog.Assert(socketError != 0, "BaseOverlappedAsyncResult#{0}::CompletionPortCallback()|socketError:0 numBytes:{1}", ValidationHelper.HashString(asyncResult), numBytes); } GlobalLog.Assert(!success, "BaseOverlappedAsyncResult#{0}::CompletionPortCallback()|Unexpectedly succeeded. errorCode:{1} numBytes:{2}", ValidationHelper.HashString(asyncResult), errorCode, numBytes); } // CleanedUp check above does not always work since this code is subject to race conditions catch (ObjectDisposedException) { socketError = SocketError.OperationAborted; } } } asyncResult.ErrorCode = (int)socketError; returnObject = asyncResult.PostCompletion((int)numBytes); asyncResult.ReleaseUnmanagedStructures(); asyncResult.InvokeCallback(returnObject); #if DEBUG } #endif }
// // SetUnmanagedStructures - // // This needs to be called for overlapped IO to function properly. // // Fills in Overlapped Structures used in an Async Overlapped Winsock call // these calls are outside the runtime and are unmanaged code, so we need // to prepare specific structures and ints that lie in unmanaged memory // since the Overlapped calls can be Async // internal void SetUnmanagedStructures(object objectsToPin) { if (!m_DisableOverlapped) { // Casting to object[] is very expensive. Only do it once. object[] objectsToPinArray = null; bool triedCastingToArray = false; bool useCache = false; if (m_Cache != null) { if (objectsToPin == null && m_Cache.PinnedObjects == null) { useCache = true; } else if (m_Cache.PinnedObjects != null) { if (m_Cache.PinnedObjectsArray == null) { if (objectsToPin == m_Cache.PinnedObjects) { useCache = true; } } else if (objectsToPin != null) { triedCastingToArray = true; objectsToPinArray = objectsToPin as object[]; if (objectsToPinArray != null && objectsToPinArray.Length == 0) { objectsToPinArray = null; } if (objectsToPinArray != null && objectsToPinArray.Length == m_Cache.PinnedObjectsArray.Length) { useCache = true; for (int i = 0; i < objectsToPinArray.Length; i++) { if (objectsToPinArray[i] != m_Cache.PinnedObjectsArray[i]) { useCache = false; break; } } } } } } if (!useCache && m_Cache != null) { GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(this) + "::SetUnmanagedStructures() Cache miss - freeing cache."); m_Cache.Free(); m_Cache = null; } Socket s = (Socket)AsyncObject; if (m_UseOverlappedIO) { GlobalLog.Assert(m_UnmanagedBlob == null, "BaseOverlappedAsyncResult#{0}::SetUnmanagedStructures()|Unmanaged blob already allocated. (Called twice?)", ValidationHelper.HashString(this)); m_UnmanagedBlob = SafeOverlappedFree.Alloc(s.SafeHandle); PinUnmanagedObjects(objectsToPin); // // create the event handle // m_OverlappedEvent = new AutoResetEvent(false); // // fill in the overlapped structure with the event handle. // Marshal.WriteIntPtr(m_UnmanagedBlob.DangerousGetHandle(), Win32.OverlappedhEventOffset, m_OverlappedEvent.SafeWaitHandle.DangerousGetHandle()); } else { // // Bind the Win32 Socket Handle to the ThreadPool // s.BindToCompletionPort(); if (m_Cache == null) { GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(this) + "::EnableCompletionPort() Creating new overlapped cache."); if (objectsToPinArray != null) { m_Cache = new OverlappedCache(new Overlapped(), objectsToPinArray, s_IOCallback); } else { m_Cache = new OverlappedCache(new Overlapped(), objectsToPin, s_IOCallback, triedCastingToArray); } } else { GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(this) + "::EnableCompletionPort() Using cached overlapped."); } m_Cache.Overlapped.AsyncResult = this; #if DEBUG unsafe { m_InitialNativeOverlapped = *((NativeOverlapped *)m_Cache.NativeOverlapped); } #endif GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(this) + "::EnableCompletionPort() overlapped:" + ValidationHelper.HashString(m_Cache.Overlapped) + " NativeOverlapped = " + m_Cache.NativeOverlapped.ToString("x")); } } }
/// <summary> /// Displays a tree by putting it in an HwndSource and running a dispatcher. /// </summary> /// <param name="root">The root of the tree to display.</param> /// <param name="titleSuffix">A string to append to the window title bar.</param> /// <param name="continueDispatcher">Whether or not continue dispatcher after display tree. Works only with Custome Elements defined under CustomElements</param> public void DisplayTree(object root, string titleSuffix, bool continueDispatcher) { _continueDispatcher = continueDispatcher; if (root == null) { throw new ArgumentNullException("root"); } if (root is UIElement && LogicalTreeHelper.GetParent((UIElement)root) != null) { throw new ArgumentException("root", "The given node has a parent."); } Dispatcher dispatcher = Dispatcher.CurrentDispatcher; if (dispatcher == null) { throw new InvalidOperationException("Cannot show the tree. The current thread has not entered a Dispatcher."); } if (!_AttachRenderedHandler(root)) { GlobalLog.LogStatus("Not displaying element tree; root not recognized as framework element or custom test element."); return; } // Get window - create one if necessary. Window win = null; if (root is Window) { win = (Window)root; } else { win = CreateWindow(); win.Content = root; } Point point = UpdatePosition(100, 100); // Set window size. win.Top = point.Y; win.Left = point.X; win.Width = 800; win.Height = 700; // Show window. _SetWindowVisibility(win, true); // Run dispatcher. GlobalLog.LogStatus("Running dispatcher..."); _dispatcherFrame = new DispatcherFrame(); Dispatcher.PushFrame(_dispatcherFrame); GlobalLog.LogStatus("Dispatcher is done..."); _dispatcherFrame = null; // If an exception happened within the Avalon app, // forward that exception now. Exception testResultEx = RetrieveException(); if (testResultEx != null) { StoreException(null); throw new Exception("Exception was logged while displaying tree.\r\n\r\n" + testResultEx); } // If an failure was "logged" while displaying the tree, // forward the failure now. string testResultMsg = testResultStore; if (testResultMsg != null) { testResultStore = null; if (testResultMsg.ToLowerInvariant() == "fail") { throw new Exception("Fail was logged while displaying tree."); } } if (!_didRender) { throw new Exception("ICustomElement.RenderedEvent handler did not fire."); } else { _didRender = false; } // Hide the Window so it doesn't serialize with // Visibility on. _SetWindowVisibility(win, false); }
/// <summary> /// Callback routine to complete the round trip test. /// </summary> public void AsyncRoundTripTest(object firstTreeRoot, XamlWriterMode expressionMode, bool attemptDisplay) { try { object secondTreeRoot = null; string firstSerialized = String.Empty; string secondSerialized = String.Empty; _iteration++; if (null == firstTreeRoot) { throw new Exception("First tree root is null."); } _firstTreeRoot = firstTreeRoot; // Fire PreFirstDisplay event if (PreFirstDisplay != null) { PreFirstDisplay(_firstTreeRoot); } // // Display first tree. // if (attemptDisplay) { _isFirst = true; GlobalLog.LogStatus("Attempting to display the first tree root..."); DisplayTree(firstTreeRoot, _iteration + " " + " - first tree root", true); } // Fire PreFirstSerialization event if (PreFirstSerialization != null) { PreFirstSerialization(_firstTreeRoot); } // // Serialize first tree. // GlobalLog.LogStatus("Serializing the first tree root..."); firstSerialized = SerializeObjectTree(firstTreeRoot, expressionMode); GlobalLog.LogStatus("Done serializing the first tree root."); // Fire an event with the serialized xaml string. _FireXamlSerializedEvent(firstSerialized); if (this.CompareOriginalXaml && _originalXaml != null) { GlobalLog.LogStatus("Comparing original xaml to first serialized xaml..."); _CompareXamls(_originalXaml, firstSerialized); } // // Parse the first serialized xaml. // Nullify _parserContext (if it's not null already) so that // it can't be reused anymore // secondTreeRoot = ParseXaml(firstSerialized); _parserContext = null; _secondTreeRoot = secondTreeRoot; // Fire PreSecondDisplay event if (PreSecondDisplay != null) { PreSecondDisplay(_secondTreeRoot); } // // Display the second tree. // if (attemptDisplay) { _isFirst = false; GlobalLog.LogStatus("Attempting to display the second tree root..."); DisplayTree(secondTreeRoot, _iteration + " " + " - second tree root"); } // Fire PreSecondSerialization event if (PreSecondSerialization != null) { PreSecondSerialization(_secondTreeRoot); } // // Serialize the second tree. // GlobalLog.LogStatus("Serializing the second tree..."); secondSerialized = SerializeObjectTree(secondTreeRoot, expressionMode); GlobalLog.LogStatus("Done serializing the second tree root."); // Fire an event with the serialized xaml string. _FireXamlSerializedEvent(secondSerialized); // // Compare the first and second trees. // if (DoTreeComparison) { GlobalLog.LogStatus("Comparing object trees..."); _CompareObjectTree(firstTreeRoot, secondTreeRoot); } if (XamlWriterMode.Expression != expressionMode && AlwaysTestExpressionMode) { // For XamlWriterMode.Value, Expression mode is also verified. // // Serialize first tree with Expression Mode // GlobalLog.LogStatus("Serializing the first tree root with Expression mode..."); secondSerialized = SerializeObjectTree(firstTreeRoot, XamlWriterMode.Expression); GlobalLog.LogStatus("Done serializing the first tree root with Expression mode."); // Fire an event with the serialized xaml string. _FireXamlSerializedEvent(secondSerialized); // // Parse the serialized xaml. // secondTreeRoot = ParseXaml(secondSerialized); // Fire PreSecondDisplay event if (PreSecondDisplay != null) { PreSecondDisplay(secondTreeRoot); } // // Display the second tree. // if (attemptDisplay) { _isFirst = false; GlobalLog.LogStatus("Attempting to display the tree loaded from string serialized with Expression mode ..."); DisplayTree(secondTreeRoot, _iteration + " " + " - additional tree", false); } // // Compare the first and the additional tree parsed from string serialized with Expression mode. // if (DoTreeComparison) { GlobalLog.LogStatus("Comparing object trees..."); _CompareObjectTree(firstTreeRoot, secondTreeRoot); } } // // Compare first and second serialized xaml files. // if (DoXamlComparison) { GlobalLog.LogStatus("Comparing xamls..."); _CompareXamls(firstSerialized, secondSerialized); } } finally { // // Shutdown the dispatcher. // Set the appropriate flags to indicates the shutdown // is expected. // _roundTripTestExit = true; Dispatcher.CurrentDispatcher.ShutdownFinished -= new EventHandler(_ValidatingExitDispatcher); _ShutdownDispatcher(); } }