public async void ExceptionWrapped() { Exception ex = null; try { throw new NotImplementedException(); } catch (Exception e) { ex = e; } var converter = new ResponseConverter(); var response = new RemoteResponse(ex); object result = converter.Convert(response, typeof(int)); var castedResult = result.ShouldBeAssignableTo <Task <int> >(); castedResult.IsFaulted.ShouldBe(true); castedResult.Exception.ShouldNotBeNull(); var targetInvocationException = castedResult.Exception.InnerExceptions.First().ShouldBeAssignableTo <TargetInvocationException>(); targetInvocationException.GetBaseException().ShouldBeAssignableTo <NotImplementedException>(); await Assert.ThrowsAsync <TargetInvocationException>(() => castedResult); }
private void FetchAndStore <T>(Uri requestUri, Func <Uri, T> fetcher) { var key = new RequestKey(typeof(T), requestUri); try { var data = fetcher(requestUri); lock (_lock) { _responses[key] = new RemoteResponse(data, null); } } catch (Exception exception) { RemoteServerException remoteException = exception as RemoteServerException; // ReSharper disable once ConvertIfStatementToNullCoalescingExpression if (null == remoteException) { remoteException = new RemoteServerException( Resources.RemoteSession_FetchContents_There_was_an_error_communicating_with_the_server__ + exception.Message, exception); } lock (_lock) { _responses[key] = new RemoteResponse(null, remoteException); } } FireContentsAvailable(); }
public void ThrowsOnIncorrectType(object responseData, Type targetType) { var converter = new ResponseConverter(); var response = new RemoteResponse(responseData); Assert.Throws <InvalidCastException>(() => converter.Convert(response, targetType)); }
public void TaskOfExpectedTypeReturned(object responseData, Type targetType) { var converter = new ResponseConverter(); var response = new RemoteResponse(responseData); object result = converter.Convert(response, targetType); result.ShouldBeAssignableTo(typeof(Task <>).MakeGenericType(targetType)); }
private void SendErrorResponse(Exception exception, MessageHeaders requestHeaders) { var msg = new RemoteResponse(exception) { Headers = { CorrelationId = requestHeaders.CorrelationId, RoutingKey = requestHeaders.RoutingKey } }; _sender.Send(msg); }
private void SendResponse(object response, MessageHeaders requestHeaders) { var msg = new RemoteResponse(response) { Headers = { CorrelationId = requestHeaders.CorrelationId, RoutingKey = requestHeaders.RoutingKey } }; _sender.Send(msg); }
public void OnMessageReceived(string text) { ServerWebSocketService swss = WebSocketSettings.WsServer; try { RemoteAction remote = JsonConvert.DeserializeObject <RemoteAction>(text); if (remote.action == null) { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.MissingMemberHandling = MissingMemberHandling.Error; RemoteResponse response = JsonConvert.DeserializeObject <RemoteResponse>(text, settings); // response ereignis } else { if (AssignRemoteAction(remote.action.Value, remote.value)) { if (swss != null) { RemoteResponse rr = new RemoteResponse(); if (remote.action.Value == RemoteClasses.Action.Information) { string deviceName = Settings.DeviceName; rr.status = 100; rr.message = String.IsNullOrEmpty(deviceName) ? Environment.MachineName : deviceName; swss.SendMessage(JsonConvert.SerializeObject(rr)); } else { rr.status = 200; rr.message = "ok"; swss.SendMessage(JsonConvert.SerializeObject(rr)); } } } } } catch (JsonSerializationException ex) { Debug.WriteLine(ex.ToString()); } catch (JsonReaderException jre) { Debug.WriteLine("Received invalid json: " + text); RemoteResponse rr = new RemoteResponse(); rr.status = 406; rr.message = "Invalid JSON-Object"; swss.SendMessage(JsonConvert.SerializeObject(rr)); } }
public dynamic Convert(RemoteResponse response, Type targetType) { try { if (response.IsFaulted) { return(_fromExceptionMethod.MakeGenericMethod(targetType).Invoke(this, new[] { response.Exception })); } else { return(_fromResultMethod.MakeGenericMethod(targetType).Invoke(this, new[] { response.Response })); } } catch (TargetInvocationException ex) { throw ex.GetBaseException(); } }
public RemoteResponse ExecuteRequest(RemoteRequest oRequest) { RemoteResponse ret = null; try { try { ret = base.Channel.ExecuteRequest(oRequest); } catch (FaultException <ExceptionDetail> ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); // extract & throw original exception from Fault contract Exception originalException = null; try { originalException = (Exception)Activator.CreateInstance(Type.GetType(ex.Detail.Type), BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new object[] { ex.Message, ex }, null); } catch { throw; } throw originalException; } } catch (CommunicationObjectFaultedException ex) { // wrap WCF specific exception throw new RemoteSideFaultedException(ex.Message, ex); } catch (EndpointNotFoundException ex) { // wrap WCF specific exception throw new RemoteSideUnreachableException(ex.Message, ex); } return(ret); }
private bool HandleResponse(RemoteResponse response) { var responseAwaiter = this._awaitersRegistry.Get(response.Headers.CorrelationId); if (responseAwaiter == null) { return(false); } try { responseAwaiter.SetResult(response); } catch (Exception ex) { responseAwaiter.SetException(ex); } finally { this._awaitersRegistry.Remove(responseAwaiter); } return(true); }
/// <summary> /// Gets class entity from selected class. /// </summary> /// <exception cref="Exception"> /// Thrown when an exception error condition occurs. /// </exception> /// <param name="TargetProject"> /// Target project. /// </param> /// <param name="NameOfSourceCommand"> /// Name of the source command. /// </param> /// <returns> /// The class entity from selected class. /// </returns> public ClassEntity GetClassEntityFromSelectedClass(Project TargetProject, string NameOfSourceCommand) { // Karl Shifflett in original vb code: // // 'TODO karl you left off here. must ensure that the SL verions is added // 'Dim strSilverlightVersion As String = String.Empty // 'If bolIsSilverlight Then // ' strSilverlightVersion = Me.Application.ActiveDocument.ProjectItem.ContainingProject.Properties.Item("TargetFrameworkMoniker").Value.ToString.Replace("Silverlight,Version=v", String.Empty) // 'End If // // Yes, this portion of code was not implemented. string assemblyPath = GetAssemblyInformation(TargetProject); if (assemblyPath.IsNullOrEmpty()) { // This should never execute since, the menu option would be disabled. // If it does run, there is a programming error. throw new Exception("The project associated with the selected file is either not vb, cs or is blacklisted."); } RemoteWorker remoteWorker = null; RemoteResponse <AssembliesNamespacesClasses> remoteResponse = null; try { var appSetup = new AppDomainSetup() { ApplicationBase = Path.GetDirectoryName(assemblyPath), DisallowApplicationBaseProbing = false, ShadowCopyFiles = "True" }; //++ Secondary Application Domain _secondaryAppDomain = AppDomain.CreateDomain("SecondaryAppDomain", null, appSetup); AppDomain.CurrentDomain.AssemblyResolve += SecondaryAppDomain_AssemblyResolve; //! This creates remoteWorker in a secondary domain, allowing it to run //! in a separate context from the current domain. This separates //! remoteWorker from the rest of the application (VS), so if the //! domain becomes unstable, it can be unloaded without harming the //! current domain. remoteWorker = _secondaryAppDomain.CreateInstanceFromAndUnwrap(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "XamlHelpmeet.ReflectionLoader.dll"), "XamlHelpmeet.ReflectionLoader.RemoteWorker") as RemoteWorker; //+ remoteWorker inherits a MarshalByRefObject. This //+ enables access to objects returned by its //+ methods across domains. if (remoteWorker != null) { var isSilverlight = PtHelpers.IsProjectSilverlight(PtHelpers.GetProjectTypeGuids(TargetProject).Split(';')); // remoteResponse is a helper class that is serialized so it can // wrap objects returned from a secondary (i.e., remote) application // domain. // A problem exists in this call when an object is returned from // the secondary domain that is of a different version than the // same object in the current domain. When that happens an // InvalidCastException is thrown, and remoteResponse will be // null. I think this may occur when XHM is used on its own // assemblies, if the assemblies have been recompiled since // the operating vsix file was produced. In fact it is likely // that the object that is causing the throw is remoteResponse // itself. This might be resolved by freezing the project // that RemoteResponse is in, and compile it only when necessary. // It would make sense also to move the class into the // ReflectionLoader namespace so it is less likely it would // need to be recompiled when other changes are needed in // the solution. remoteResponse = remoteWorker.GetClassEntityFromUserSelectedClass(assemblyPath, isSilverlight, GetProjectReferences(TargetProject)); if (remoteResponse.ResponseStatus != ResponseStatus.Success) { UIUtilities.ShowExceptionMessage("Unable to Reflect Type", String.Format("The following exception was returned. {0}", remoteResponse.CustomMessageAndException), string.Empty, remoteResponse.Exception.ToString()); } } else { UIUtilities.ShowExceptionMessage("Unable To Create Worker", "Can't create Secondary AppDomain RemoteWorker class. CreateInstance and Unwrap methods returned null."); } } catch (FileNotFoundException ex) { UIUtilities.ShowExceptionMessage("File Not Found", String.Format("File not found.{0}{0}Have you built your application?{0}{0}{1}", Environment.NewLine, ex.Message), String.Empty, ex.ToString()); } catch (Exception ex) { UIUtilities.ShowExceptionMessage("Unable To Create Secondary AppDomain RemoteWorker", ex.Message, String.Empty, ex.ToString()); } finally { AppDomain.CurrentDomain.AssemblyResolve -= SecondaryAppDomain_AssemblyResolve; remoteWorker = null; if (_secondaryAppDomain != null) { try { AppDomain.Unload(_secondaryAppDomain); } catch (Exception ex) { UIUtilities.ShowExceptionMessage("AppDomain.Unload Exception", ex.Message, String.Empty, ex.ToString()); } } _secondaryAppDomain = null; } if (remoteResponse == null || remoteResponse.ResponseStatus != ResponseStatus.Success || remoteResponse.Result == null || remoteResponse.Result.Count == 0) { if (remoteResponse == null || remoteResponse.ResponseStatus == ResponseStatus.Success) { UIUtilities.ShowInformationMessage("No Model", "Unable to find a class suitable for this command."); } return(null); } SelectClassFromAssembliesWindow frm = null; // ClassEntity classEntity = null; // Not used in original frm = new SelectClassFromAssembliesWindow(remoteResponse.Result, NameOfSourceCommand); if (!frm.ShowDialog() ?? false) { return(null); } frm.SelectedAssemblyNamespaceClass.ClassEntity.Success = true; if (frm.SelectedAssemblyNamespaceClass.ClassEntity.IsSilverlight) { frm.SelectedAssemblyNamespaceClass.ClassEntity.SilverlightVersion = TargetProject.Properties.Item("TargetFrameworkMoniker").Value.ToString().Replace("Silverlight,Version=v", string.Empty); } return(frm.SelectedAssemblyNamespaceClass.ClassEntity); }
/// <summary> /// Gets class entities for selected project. /// </summary> /// <exception cref="Exception"> /// Thrown when an exception error condition occurs. /// </exception> /// <param name="TargetProject"> /// Target project. /// </param> /// <param name="NameOfSourceCommand"> /// Name of the source command. /// </param> /// <returns> /// The class entities for selected project. /// </returns> public AssembliesNamespacesClasses GetClassEntitiesForSelectedProject(Project TargetProject, string NameOfSourceCommand) { string assemblyPath = GetAssemblyInformation(TargetProject); if (assemblyPath.IsNullOrEmpty()) { throw new Exception("The project associated with the selected file is either not vb, cs or is blacklisted."); } RemoteWorker remoteWorker = null; RemoteResponse <AssembliesNamespacesClasses> remoteResponse = null; try { var appSetup = new AppDomainSetup() { ApplicationBase = Path.GetDirectoryName(assemblyPath), DisallowApplicationBaseProbing = false, ShadowCopyFiles = "True" }; _secondaryAppDomain = AppDomain.CreateDomain("SecondaryAppDomain", null, appSetup); AppDomain.CurrentDomain.AssemblyResolve += SecondaryAppDomain_AssemblyResolve; remoteWorker = _secondaryAppDomain.CreateInstanceFromAndUnwrap(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "XamlHelpmeet.ReflectionLoader.dll"), "XamlHelpmeet.ReflectionLoader.RemoteWorker") as RemoteWorker; if (remoteWorker != null) { var isSilverlight = PtHelpers.IsProjectSilverlight(PtHelpers.GetProjectTypeGuids(TargetProject).Split(';')); remoteResponse = remoteWorker.GetClassEntityFromUserSelectedClass(assemblyPath, isSilverlight, GetProjectReferences(TargetProject)); if (remoteResponse.ResponseStatus != ResponseStatus.Success) { UIUtilities.ShowExceptionMessage("Unable to Reflect Type", "The following exception was returned. " + remoteResponse.CustomMessageAndException, string.Empty, remoteResponse.Exception.ToString()); } else if (remoteResponse.CustomMessage.IsNotNullOrEmpty()) { UIUtilities.ShowInformationMessage("Reflection Error", string.Format("Unable to reflect the following:\r\n\r\n{0}\r\nAt least one other assembly however successfully reflected.", remoteResponse.CustomMessage)); } } else { UIUtilities.ShowExceptionMessage("Unable To Create Worker", "Can't create Secondary AppDomain RemoteWorker class. CreateInstance and Unwrap methods returned null."); } } catch (FileNotFoundException ex) { UIUtilities.ShowExceptionMessage("File Not Found", String.Format("File not found.{0}{0}Have you built your application?{0}{0}{1}", Environment.NewLine, ex.Message), String.Empty, ex.ToString()); } catch (Exception ex) { UIUtilities.ShowExceptionMessage("Unable To Create Secondary AppDomain RemoteWorker", ex.Message, String.Empty, ex.ToString()); } finally { AppDomain.CurrentDomain.AssemblyResolve -= SecondaryAppDomain_AssemblyResolve; remoteWorker = null; if (_secondaryAppDomain != null) { try { AppDomain.Unload(_secondaryAppDomain); } catch (Exception ex) { UIUtilities.ShowExceptionMessage("AppDomain.Unload Exception", ex.Message, String.Empty, ex.ToString()); } } _secondaryAppDomain = null; } if (remoteResponse != null || remoteResponse.ResponseStatus != ResponseStatus.Success) { return(null); } return(remoteResponse.Result); }