public void Method1() { _called++; methodOneWay = RemotingServices.IsOneWay(MethodBase.GetCurrentMethod()); }
public static IAgent Connect(string host, int port, string password) { return(((IAgentFactory)RemotingServices.Connect(typeof(IAgentFactory), string.Format("tcp://{0}:{1}/{2}", (object)host, (object)port, (object)"ImageManager4"))).Create(password)); }
public void Dispose() { //Disconnects the remoting channel(s) of this object and all nested objects. RemotingServices.Disconnect(this); }
[System.Security.SecuritySafeCritical] // auto-generated public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles == null) { throw new ArgumentNullException("waitHandles", Environment.GetResourceString("ArgumentNull_Waithandles")); } if (waitHandles.Length == 0) { // // Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct. // Somehow, in 2.0, this became ArgumentNullException. This was not fixed until Silverlight 2, // which went back to ArgumentException. // // Now we're in a bit of a bind. Backward-compatibility requires us to keep throwing ArgumentException // in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking // user code. // #if FEATURE_CORECLR throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); #else throw new ArgumentNullException("waitHandles", Environment.GetResourceString("Argument_EmptyWaithandleArray")); #endif } if (waitHandles.Length > MAX_WAITHANDLES) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles")); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) { throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement")); } #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(waitHandle)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); } #endif internalWaitHandles[i] = waitHandle; } #if _DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, true /* waitall*/); if (AppDomainPauseManager.IsPaused) { AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); } if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret)) { //In the case of WaitAll the OS will only provide the // information that mutex was abandoned. // It won't tell us which one. So we can't set the Index or provide access to the Mutex ThrowAbandonedMutexException(); } GC.KeepAlive(internalWaitHandles); return(ret != WaitTimeout); }
/// <summary> /// Sets property value, doing any type conversions that are necessary along the way. /// </summary> /// <param name="context">Context to evaluate expressions against.</param> /// <param name="evalContext">Current expression evaluation context.</param> /// <param name="newValue">New value for this node.</param> private void SetPropertyOrFieldValue(object context, EvaluationContext evalContext, object newValue) { bool isWriteable = accessor.IsWriteable; Type targetType = accessor.TargetType; try { if (!isWriteable) { if (!AddToCollections(context, evalContext, newValue)) { throw new NotWritablePropertyException( "Can't change the value of the read-only property or field '" + this.memberName + "'."); } } else if (targetType.IsPrimitive && (newValue == null || String.Empty.Equals(newValue))) { throw new ArgumentException("Invalid value [" + newValue + "] for property or field '" + this.memberName + "' of primitive type [" + targetType + "]"); } else if (newValue == null || ObjectUtils.IsAssignable(targetType, newValue)) // targetType.IsAssignableFrom(newValue.GetType()) { SetPropertyOrFieldValueInternal(context, newValue); } else if (!RemotingServices.IsTransparentProxy(newValue) && (newValue is IList || newValue is IDictionary || newValue is ISet)) { if (!AddToCollections(context, evalContext, newValue)) { object tmpValue = TypeConversionUtils.ConvertValueIfNecessary(targetType, newValue, this.memberName); SetPropertyOrFieldValueInternal(context, tmpValue); } } else { object tmpValue = TypeConversionUtils.ConvertValueIfNecessary(targetType, newValue, this.memberName); SetPropertyOrFieldValueInternal(context, tmpValue); } } catch (TargetInvocationException ex) { PropertyChangeEventArgs propertyChangeEvent = new PropertyChangeEventArgs(this.memberName, null, newValue); if (ex.GetBaseException() is InvalidCastException) { throw new TypeMismatchException(propertyChangeEvent, targetType, ex.GetBaseException()); } else { throw new MethodInvocationException(ex.GetBaseException(), propertyChangeEvent); } } catch (UnauthorizedAccessException ex) { throw new FatalReflectionException("Illegal attempt to set property '" + this.memberName + "'", ex); } catch (NotWritablePropertyException) { throw; } catch (NotReadablePropertyException) { throw; } catch (ArgumentException ex) { PropertyChangeEventArgs propertyChangeEvent = new PropertyChangeEventArgs(this.memberName, null, newValue); throw new TypeMismatchException(propertyChangeEvent, targetType, ex); } }
public ObjRef RegisterMarshalObject(object obj, string objectUri = null) { return(RemotingServices.Marshal((MarshalByRefObject)obj, string.IsNullOrEmpty(objectUri) ? obj.GetType().FullName : objectUri)); }
/// <summary> /// TODO /// </summary> /// <param name="name"> /// The name of the object that is having the value of one of its properties resolved. /// </param> /// <param name="definition"> /// The definition of the named object. /// </param> /// <param name="argumentName"> /// The name of the property the value of which is being resolved. /// </param> /// <param name="argumentValue"> /// The value of the property that is being resolved. /// </param> private object ResolvePropertyValue(string name, IObjectDefinition definition, string argumentName, object argumentValue) { object resolvedValue = null; // we must check the argument value to see whether it requires a runtime // reference to another object to be resolved. // if it does, we'll attempt to instantiate the object and set the reference. if (RemotingServices.IsTransparentProxy(argumentValue)) { resolvedValue = argumentValue; } else if (argumentValue is ICustomValueReferenceHolder) { resolvedValue = ((ICustomValueReferenceHolder)argumentValue).Resolve(objectFactory, name, definition, argumentName, argumentValue); } else if (argumentValue is ObjectDefinitionHolder) { // contains an IObjectDefinition with name and aliases... ObjectDefinitionHolder holder = (ObjectDefinitionHolder)argumentValue; resolvedValue = ResolveInnerObjectDefinition(name, holder.ObjectName, argumentName, holder.ObjectDefinition, definition.IsSingleton); } else if (argumentValue is IObjectDefinition) { // resolve plain IObjectDefinition, without contained name: use dummy name... IObjectDefinition def = (IObjectDefinition)argumentValue; resolvedValue = ResolveInnerObjectDefinition(name, "(inner object)", argumentName, def, definition.IsSingleton); } else if (argumentValue is RuntimeObjectReference) { RuntimeObjectReference roref = (RuntimeObjectReference)argumentValue; resolvedValue = ResolveReference(definition, name, argumentName, roref); } else if (argumentValue is ExpressionHolder) { ExpressionHolder expHolder = (ExpressionHolder)argumentValue; object context = null; IDictionary <string, object> variables = null; if (expHolder.Properties != null) { PropertyValue contextProperty = expHolder.Properties.GetPropertyValue("Context"); context = contextProperty == null ? null : ResolveValueIfNecessary(name, definition, "Context", contextProperty.Value); PropertyValue variablesProperty = expHolder.Properties.GetPropertyValue("Variables"); object vars = (variablesProperty == null ? null : ResolveValueIfNecessary(name, definition, "Variables", variablesProperty.Value)); if (vars is IDictionary <string, object> ) { variables = (IDictionary <string, object>)vars; } if (vars is IDictionary) { IDictionary temp = (IDictionary)vars; variables = new Dictionary <string, object>(temp.Count); foreach (DictionaryEntry entry in temp) { variables.Add((string)entry.Key, entry.Value); } } else { if (vars != null) { throw new ArgumentException("'Variables' must resolve to an IDictionary"); } } } if (variables == null) { variables = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); } // add 'this' objectfactory reference to variables variables.Add(Expression.ReservedVariableNames.CurrentObjectFactory, objectFactory); resolvedValue = expHolder.Expression.GetValue(context, variables); } else if (argumentValue is IManagedCollection) { resolvedValue = ((IManagedCollection)argumentValue).Resolve(name, definition, argumentName, ResolveValueIfNecessary); } else if (argumentValue is TypedStringValue) { TypedStringValue tsv = (TypedStringValue)argumentValue; try { Type resolvedTargetType = ResolveTargetType(tsv); if (resolvedTargetType != null) { resolvedValue = TypeConversionUtils.ConvertValueIfNecessary(tsv.TargetType, tsv.Value, null); } else { resolvedValue = tsv.Value; } } catch (Exception ex) { throw new ObjectCreationException(definition.ResourceDescription, name, "Error converted typed String value for " + argumentName, ex); } } else { // no need to resolve value... resolvedValue = argumentValue; } return(resolvedValue); }
internal void DoSetCOMIUnknown(IntPtr pUnk) { RemotingServices.GetRealProxy(this).SetCOMIUnknown(pUnk); }
public void UnloadProject(ProjectBuilder pb) { ((ProjectBuilder)pb).Dispose(); RemotingServices.Disconnect((MarshalByRefObject)pb); }
public void ShouldInitialzeAndCleanupBeforeAndAfterMethodIsCalled() { this.testApplication.CreateObject(typeof(Test), Arg.Is <object[]>(args => (args != null) && (args.Length == 1) && (args[0] == this.initializationManager))).Returns(this.realTest); Test test = new Test(this.initializationManager); test.TestSomething(); Assert.Equal(this.realTest, RemotingServices.GetRealProxy(test).GetType().GetField("target", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(RemotingServices.GetRealProxy(test))); int methodCallId = (int)this.initializationManager.ReceivedCalls().First().GetArguments()[0]; this.initializationManager.Received().Initialize(methodCallId, Arg.Is <TestInitializationContext>(c => (c.Instance == this.realTest) && (c.Method == typeof(Test).GetMethod("TestSomething") && (c.Arguments.Length == 0)))); this.initializationManager.Received().Cleanup(methodCallId, Arg.Is <TestInitializationContext>(c => (c.Instance == this.realTest) && (c.Method == typeof(Test).GetMethod("TestSomething") && (c.Arguments.Length == 0)))); }
// called at the end of request processing // to disconnect the remoting proxy for Connection object // and allow GC to pick it up public void OnRequestEnd(Connection conn) { RemotingServices.Disconnect(conn); }
public void ShouldUseInstantiationFromTheBaseClass() { this.testApplication.CreateObject(typeof(Test), Arg.Is <object[]>(args => (args != null) && (args.Length == 1) && (args[0] == this.initializationManager))).Returns(this.realTest); Test test = new Test(this.initializationManager); Assert.Equal(this.realTest, RemotingServices.GetRealProxy(test).GetType().GetField("target", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(RemotingServices.GetRealProxy(test))); }
public void ShouldPerformCleanupEvenAfterException() { this.testApplication.CreateObject(typeof(Test), Arg.Is <object[]>(args => (args != null) && (args.Length == 1) && (args[0] == this.initializationManager))).Returns(this.realTest); Test test = new Test(this.initializationManager); Assert.ThrowsDelegate action = test.FailingTest; Assert.Throws <Exception>(action); Assert.Equal(this.realTest, RemotingServices.GetRealProxy(test).GetType().GetField("target", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(RemotingServices.GetRealProxy(test))); int methodCallId = (int)this.initializationManager.ReceivedCalls().First().GetArguments()[0]; this.initializationManager.Received().Initialize(methodCallId, Arg.Is <TestInitializationContext>(c => (c.Instance == this.realTest) && (c.Method == typeof(Test).GetMethod("FailingTest")) && (c.Arguments.Length == 0))); this.initializationManager.Received().Cleanup(methodCallId, Arg.Is <TestInitializationContext>(c => (c.Instance == this.realTest) && (c.Method == typeof(Test).GetMethod("FailingTest")) && (c.Arguments.Length == 0))); }
public void Method3() { methodOneWay = RemotingServices.IsOneWay(MethodBase.GetCurrentMethod()); }
/// <summary> /// Creates a globally reachable, managed IPC-Port. /// </summary> /// <remarks> /// Because it is something tricky to get a port working for any constellation of /// target processes, I decided to write a proper wrapper method. Just keep the returned /// <see cref="IpcChannel"/> alive, by adding it to a global list or static variable, /// as long as you want to have the IPC port open. /// </remarks> /// <typeparam name="TRemoteObject"> /// A class derived from <see cref="MarshalByRefObject"/> which provides the /// method implementations this server should expose. /// </typeparam> /// <param name="InObjectMode"> /// <see cref="WellKnownObjectMode.SingleCall"/> if you want to handle each call in an new /// object instance, <see cref="WellKnownObjectMode.Singleton"/> otherwise. The latter will implicitly /// allow you to use "static" remote variables. /// </param> /// <param name="RefChannelName"> /// Either <c>null</c> to let the method generate a random channel name to be passed to /// <see cref="IpcConnectClient{TRemoteObject}"/> or a predefined one. If you pass a value unequal to /// <c>null</c>, you shall also specify all SIDs that are allowed to connect to your channel! /// </param> /// <param name="ipcInterface">Provide a TRemoteObject object to be made available as a well known type on the server end of the channel.</param> /// <param name="InAllowedClientSIDs"> /// If no SID is specified, all authenticated users will be allowed to access the server /// channel by default. You must specify an SID if <paramref name="RefChannelName"/> is unequal to <c>null</c>. /// </param> /// <returns> /// An <see cref="IpcChannel"/> that shall be keept alive until the server is not needed anymore. /// </returns> /// <exception cref="System.Security.HostProtectionException"> /// If a predefined channel name is being used, you are required to specify a list of well known SIDs /// which are allowed to access the newly created server. /// </exception> /// <exception cref="RemotingException"> /// The given channel name is already in use. /// </exception> public static IpcServerChannel IpcCreateServer <TRemoteObject>( ref String RefChannelName, WellKnownObjectMode InObjectMode, TRemoteObject ipcInterface, params WellKnownSidType[] InAllowedClientSIDs) where TRemoteObject : MarshalByRefObject { String ChannelName = RefChannelName ?? GenerateName(); /////////////////////////////////////////////////////////////////// // create security descriptor for IpcChannel... System.Collections.IDictionary Properties = new System.Collections.Hashtable(); Properties["name"] = ChannelName; Properties["portName"] = ChannelName; DiscretionaryAcl DACL = new DiscretionaryAcl(false, false, 1); if (InAllowedClientSIDs.Length == 0) { if (RefChannelName != null) { throw new System.Security.HostProtectionException("If no random channel name is being used, you shall specify all allowed SIDs."); } // allow access from all users... Channel is protected by random path name! DACL.AddAccess( AccessControlType.Allow, new SecurityIdentifier( WellKnownSidType.WorldSid, null), -1, InheritanceFlags.None, PropagationFlags.None); } else { for (int i = 0; i < InAllowedClientSIDs.Length; i++) { DACL.AddAccess( AccessControlType.Allow, new SecurityIdentifier( InAllowedClientSIDs[i], null), -1, InheritanceFlags.None, PropagationFlags.None); } } CommonSecurityDescriptor SecDescr = new CommonSecurityDescriptor(false, false, ControlFlags.GroupDefaulted | ControlFlags.OwnerDefaulted | ControlFlags.DiscretionaryAclPresent, null, null, null, DACL); ////////////////////////////////////////////////////////// // create IpcChannel... BinaryServerFormatterSinkProvider BinaryProv = new BinaryServerFormatterSinkProvider(); BinaryProv.TypeFilterLevel = TypeFilterLevel.Full; IpcServerChannel Result = new IpcServerChannel(Properties, BinaryProv, SecDescr); ChannelServices.RegisterChannel(Result, false); if (ipcInterface == null) { RemotingConfiguration.RegisterWellKnownServiceType( typeof(TRemoteObject), ChannelName, InObjectMode); } else { RemotingServices.Marshal(ipcInterface, ChannelName); } RefChannelName = ChannelName; return(Result); }
/// <summary> /// Disconnects the remoting channel(s) of this object and all nested objects. /// </summary> private void Disconnect() { RemotingServices.Disconnect(this); }
/// <summary> /// 注册服务端初始化单例对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public ObjRef RegisterMarshalObject <T>(T obj) where T : MarshalByRefObject { return(RemotingServices.Marshal(obj, typeof(T).FullName)); }
/// <summary>Creates an <see cref="T:System.Runtime.Remoting.ObjRef" /> for the specified object type, and registers it with the remoting infrastructure as a client-activated object.</summary> /// <returns>A new instance of <see cref="T:System.Runtime.Remoting.ObjRef" /> that is created for the specified type.</returns> /// <param name="requestedType">The object type that an <see cref="T:System.Runtime.Remoting.ObjRef" /> is created for. </param> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /> /// </PermissionSet> public virtual ObjRef CreateObjRef(Type requestedType) { return(RemotingServices.Marshal((MarshalByRefObject)this.GetTransparentProxy(), null, requestedType)); }
String GetHeaders(ISmtpMessage smtpMessage, ref Smtp.Fields headers, ref String contentType, ref Header[] msgHeaders) { // Get the headers from the message object headers = smtpMessage.Fields; #if _DEBUG long count = headers.Count; InternalRemotingServices.RemotingTrace(" Count of fields " + count); for (long i = 0; i < count; i++) { //InternalRemotingServices.RemotingTrace(" Field " + i + " " + headers[i].Name + " " + headers[i].Value); } #endif // Get the content type string Field typeField = headers["urn:schemas:mailheader:contenttype"]; if (null == typeField) { throw new FormatException(CoreChannel.GetResourceString("Remoting_MissingContentType")); } contentType = (String)(typeField.Value); InternalRemotingServices.RemotingTrace("Content type " + typeField.Name + " " + contentType); // Extract the requested uri from the mail header Field uriField = headers["urn:schemas:mailheader:requesteduri"]; if (null == uriField) { throw new FormatException(CoreChannel.GetResourceString("Remoting_MissingRequestedURIHeader")); } String uriValue = (String)uriField.Value; if (null == uriValue) { throw new FormatException(CoreChannel.GetResourceString("Remoting_MissingRequestedURIHeader")); } // process SoapAction (extract the type and the name of the method to be invoked) Field actionField = headers["urn:schemas:mailheader:soapaction"]; if (null == actionField) { throw new FormatException(CoreChannel.GetResourceString("Remoting_SoapActionMissing")); } String actionValue = (String)actionField.Value; if (null == actionValue) { throw new FormatException(CoreChannel.GetResourceString("Remoting_SoapActionMissing")); } String typeName, methodName; if (!SoapServices.GetTypeAndMethodNameFromSoapAction(actionValue, out typeName, out methodName)) { // This means there are multiple methods for this soap action, so we will have to // settle for the type based off of the uri. Type type = RemotingServices.GetServerTypeForUri(uriValue); typeName = type.FullName + ", " + type.Module.Assembly.GetName().Name; } // BUGBUG: need code to verify soap action after the message has been deserialized. // this will probably be done once we have the new activation scenario working. msgHeaders = new Header[3]; msgHeaders[0] = new Header("__Uri", uriValue); msgHeaders[1] = new Header("__TypeName", typeName); msgHeaders[2] = new Header("__MethodName", methodName); // Extract the message sequence number field from the // mail header Field seqField = headers["urn:schemas:mailheader:soapmsgseqnum"]; if (null == seqField) { throw new FormatException(CoreChannel.GetResourceString("Remoting_MissingSoapMsgSeqNum")); } String seqValue = (String)(seqField.Value); InternalRemotingServices.RemotingTrace("Guid value " + seqValue); return(seqValue); }
public IConstructionReturnMessage InitializeServerObject(IConstructionCallMessage ctorMsg) { IConstructionReturnMessage retMsg = null; if (_serverObject == null) { Type svrType = GetProxiedType(); if ((ctorMsg != null) && (ctorMsg.ActivationType != svrType)) { throw new RemotingException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Proxy_BadTypeForActivation"), svrType.FullName, ctorMsg.ActivationType)); } // Create a blank object _serverObject = RemotingServices.AllocateUninitializedObject(svrType); // If the stub is the default stub, then set the server context // to be the current context. SetContextForDefaultStub(); // OK... we are all set to run the constructor call on the uninitialized object MarshalByRefObject proxy = (MarshalByRefObject)GetTransparentProxy(); IMethodReturnMessage msg = null; Exception e = null; if (null != ctorMsg) { msg = RemotingServices.ExecuteMessage(proxy, ctorMsg); e = msg.Exception; } else { try { RemotingServices.CallDefaultCtor(proxy); } catch (Exception excep) { e = excep; } } // Construct a return message if (null == e) { Object[] outArgs = (msg == null ? null : msg.OutArgs); int outLength = (null == outArgs ? 0 : outArgs.Length); LogicalCallContext callCtx = (msg == null ? null : msg.LogicalCallContext); retMsg = new ConstructorReturnMessage(proxy, outArgs, outLength, callCtx, ctorMsg); // setup identity SetupIdentity(); if (IsRemotingProxy()) { ((RemotingProxy)this).Initialized = true; } } else { // Exception occurred retMsg = new ConstructorReturnMessage(e, ctorMsg); } } return(retMsg); }
// This is not unit tested right now public ICruiseManager GetCruiseManager(string url) { ICruiseManager cruiseManager = (ICruiseManager)RemotingServices.Connect(typeof(ICruiseManager), url); return(cruiseManager); }
[System.Security.SecurityCritical] // auto-generated public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { Object obj = GetTransparentProxy(); RemotingServices.GetObjectData(obj, info, context); }
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles == null) { throw new ArgumentNullException("waitHandles", Environment.GetResourceString("ArgumentNull_Waithandles")); } if (waitHandles.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); } if (MAX_WAITHANDLES < waitHandles.Length) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles")); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) { throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement")); } #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(waitHandle)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); } #endif internalWaitHandles[i] = waitHandle; } #if _DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, false /* waitany*/); if (AppDomainPauseManager.IsPaused) { AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); } if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret)) { int mutexIndex = ret - WAIT_ABANDONED; if (0 <= mutexIndex && mutexIndex < internalWaitHandles.Length) { ThrowAbandonedMutexException(mutexIndex, internalWaitHandles[mutexIndex]); } else { ThrowAbandonedMutexException(); } } GC.KeepAlive(internalWaitHandles); return(ret); }
[System.Security.SecurityCritical] // auto-generated private void PrivateInvoke(ref MessageData msgData, int type) { IMessage reqMsg = null; CallType callType = (CallType)type; IMessage retMsg = null; int msgFlags = -1; // Used only for Construction case RemotingProxy rp = null; // Create a message object based on the type of call if (CallType.MethodCall == callType) { Message msg = new Message(); msg.InitFields(msgData); reqMsg = msg; msgFlags = msg.GetCallType(); } else if (CallType.ConstructorCall == (CallType)callType) { // We use msgFlags to handle CallContext around // the virtual call to Invoke() msgFlags = Message.Sync; rp = this as RemotingProxy; ConstructorCallMessage ctorMsg = null; bool bIsWellKnown = false; if (!IsRemotingProxy()) { // Create a new constructor call message // < ctorMsg = new ConstructorCallMessage(null, null, null, (RuntimeType)GetProxiedType()); } else { // Extract the constructor message set in the first step of activation. ctorMsg = rp.ConstructorMessage; // If the proxy is a wellknown client proxy, we don't // need to run the c'tor. Identity id = rp.IdentityObject; if (id != null) { bIsWellKnown = id.IsWellKnown(); } } if ((null == ctorMsg) || bIsWellKnown) { // This is also used to short-circuit the activation path // when we have a well known proxy that has already been // initialized (there's a race condition if we don't do this). // // This is a special case, where we have a remoting proxy // but the constructormessage hasn't been setup. // so let us just bail out.. // this is currently used by ServicedComponent's for cross appdomain // pooling: <EMAIL>[....]</EMAIL> // ctorMsg = new ConstructorCallMessage(null, null, null, (RuntimeType)GetProxiedType()); // Set the constructor frame info in the CCM ctorMsg.SetFrame(msgData); reqMsg = ctorMsg; // If this was the default ctor, check that default .ctor was called. if (bIsWellKnown) { Contract.Assert(rp != null, "RemotingProxy expected here!"); // Clear any cached ctorMsg on the RemotingProxy rp.ConstructorMessage = null; // We did execute a Connect. Throw if the client // code is also trying to use a non-default constructor at // the same time. if (ctorMsg.ArgCount != 0) { throw new RemotingException( Environment.GetResourceString( "Remoting_Activation_WellKnownCTOR")); } } // Create a constructor return message retMsg = new ConstructorReturnMessage((MarshalByRefObject)GetTransparentProxy(), null, 0, null, ctorMsg); } else { // Set the constructor frame info in the CCM ctorMsg.SetFrame(msgData); reqMsg = ctorMsg; } } else { Contract.Assert(false, "Unknown call type"); } // Make sure that outgoing remote calls are counted. ChannelServices.IncrementRemoteCalls(); // For non-remoting proxies, EndAsync should not call Invoke() // because the proxy cannot support Async and the call has already // finished executing in BeginAsync if (!IsRemotingProxy() && ((msgFlags & Message.EndAsync) == Message.EndAsync)) { Message msg = reqMsg as Message; retMsg = EndInvokeHelper(msg, true); Contract.Assert(null != retMsg, "null != retMsg"); } // Invoke Contract.Assert(null != reqMsg, "null != reqMsg"); if (null == retMsg) { // NOTE: there are cases where we setup a return message // and we don't want the activation call to go through // refer to the note above for ServicedComponents and Cross Appdomain // pooling LogicalCallContext cctx = null; Thread currentThread = Thread.CurrentThread; // Pick up or clone the call context from the thread // and install it in the reqMsg as appropriate cctx = currentThread.GetMutableExecutionContext().LogicalCallContext; SetCallContextInMessage(reqMsg, msgFlags, cctx); // Add the outgoing "Header"'s to the message. cctx.PropagateOutgoingHeadersToMessage(reqMsg); retMsg = Invoke(reqMsg); // Get the call context returned and set it on the thread ReturnCallContextToThread(currentThread, retMsg, msgFlags, cctx); // Pull response "Header"'s out of the message Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext.PropagateIncomingHeadersToCallContext(retMsg); } if (!IsRemotingProxy() && ((msgFlags & Message.BeginAsync) == Message.BeginAsync)) { // This was a begin-async on a non-Remoting Proxy. For V-1 they // cannot support Async and end up doing a [....] call. We need // to fill up here to make the call look like async to // the caller. // Create the async result to return Message msg = reqMsg as Message; AsyncResult ar = new AsyncResult(msg); // Tell the async result that the call has actually completed // so it can hold on to the return message. ar.SyncProcessMessage(retMsg); // create a returnMessage to propagate just the asyncResult back // to the caller's stack. retMsg = new ReturnMessage(ar, null, 0, null /*cctx*/, msg); } // Propagate out parameters HandleReturnMessage(reqMsg, retMsg); // For constructor calls do some extra bookkeeping if (CallType.ConstructorCall == callType) { // NOTE: It is the responsiblity of the callee to propagate // the out parameters // Everything went well, we are ready to return // a proxy to the caller // Extract the return value MarshalByRefObject retObj = null; IConstructionReturnMessage ctorRetMsg = retMsg as IConstructionReturnMessage; if (null == ctorRetMsg) { throw new RemotingException( Environment.GetResourceString("Remoting_Proxy_BadReturnTypeForActivation")); } ConstructorReturnMessage crm = ctorRetMsg as ConstructorReturnMessage; if (null != crm) { // If return message is of type ConstructorReturnMessage // this is an in-appDomain activation. So no unmarshaling // needed. retObj = (MarshalByRefObject)crm.GetObject(); if (retObj == null) { throw new RemotingException( Environment.GetResourceString("Remoting_Activation_NullReturnValue")); } } else { // Fetch the objRef out of the returned message and unmarshal it retObj = (MarshalByRefObject)RemotingServices.InternalUnmarshal( (ObjRef)ctorRetMsg.ReturnValue, GetTransparentProxy(), true /*fRefine*/); if (retObj == null) { throw new RemotingException( Environment.GetResourceString("Remoting_Activation_NullFromInternalUnmarshal")); } } if (retObj != (MarshalByRefObject)GetTransparentProxy()) { throw new RemotingException( Environment.GetResourceString( "Remoting_Activation_InconsistentState")); } if (IsRemotingProxy()) { // Clear any cached ctorMsg on the RemotingProxy rp.ConstructorMessage = null; } } }
public void Dispose() { _target.Dispose(); RemotingServices.Disconnect(this); }
public static void Init(string[] args) { Engine.Engine.Init(); string channel = (string)Engine.Engine.Config["Server/Channel"]; string formatter = (string)Engine.Engine.Config["Server/Formatter"]; string host = (string)Engine.Engine.Config["Server/Host"]; string bindAddress = (string)Engine.Engine.Config["Server/BindAddress"]; int port = (int)Engine.Engine.Config["Server/Port"]; IDictionary props = new Hashtable(); props["port"] = port.ToString(); if (host != null) { props["machineName"] = host; } if (bindAddress != null) { props["bindTo"] = bindAddress; } switch (channel) { case "TCP": props["name"] = "TcpChannel"; BinaryClientFormatterSinkProvider cprovider = new BinaryClientFormatterSinkProvider(); BinaryServerFormatterSinkProvider sprovider = new BinaryServerFormatterSinkProvider(); // required for MS .NET 1.1 sprovider.TypeFilterLevel = TypeFilterLevel.Full; #if LOG4NET _Logger.Debug("Registering TcpChannel port: " + props["port"]); #endif try { ChannelServices.RegisterChannel(new TcpChannel(props, cprovider, sprovider), false); } catch (System.Net.Sockets.SocketException ex) { Console.WriteLine("Could not register remoting channel on port {0} " + "(server already running on that port?) Error: " + ex.Message, port); Environment.Exit(1); } break; #if CHANNEL_TCPEX case "TcpEx": props["name"] = "TcpExChannel"; #if LOG4NET _Logger.Debug("Registering TcpExChannel port: " + props["port"]); #endif ChannelServices.RegisterChannel(new TcpExChannel(props, null, null), false); break; #endif case "HTTP": props["name"] = "HttpChannel"; #if LOG4NET _Logger.Debug("Registering HttpChannel port: " + props["port"]); #endif ChannelServices.RegisterChannel(new HttpChannel(props, null, null), false); break; default: Console.WriteLine("Unknown channel (" + channel + "), aborting..."); Environment.Exit(1); break; } // register the SessionManager for .NET remoting RemotingServices.Marshal(Engine.Engine.SessionManager, "SessionManager"); #if LOG4NET _Logger.Info("Spawned remoting server with channel: " + channel + " formatter: " + formatter + " port: " + port); #endif Thread.CurrentThread.Join(); #if LOG4NET _Logger.Info("Shutting down remoting server..."); #endif }
static void Main(string[] args) { ChannelServices.RegisterChannel(new TcpClientChannel()); // ChannelServices.RegisterChannel(new HttpClientChannel()); // using the Activator class to create remote objects object[] attrs = { new UrlAttribute("tcp://localhost:8086/HelloServer") }; ObjectHandle handle = Activator.CreateInstance( "RemoteHello", "Wrox.ProfessionalCSharp.Hello", attrs); // Hello obj = (Hello)Activator.CreateInstance(typeof(Wrox.ProfessionalCSharp.Hello), // null, attrs); if (handle == null) { Console.WriteLine("could not locate server"); return; } Hello obj = (Hello)handle.Unwrap(); // using the new operator to create remote objects /* RemotingConfiguration.RegisterActivatedClientType( * typeof(Wrox.ProfessionalCSharp.Hello), * "tcp://localhost:8086/HelloServer"); * * Hello obj = new Hello(); */ if (RemotingServices.IsTransparentProxy(obj)) { //Console.WriteLine("Using a transparent proxy"); RealProxy proxy = RemotingServices.GetRealProxy(obj); // proxy.Invoke(message); } ILease lease = (ILease)obj.GetLifetimeService(); if (lease != null) { Console.WriteLine("Lease Configuration:"); Console.WriteLine("InitialLeaseTime: " + lease.InitialLeaseTime); Console.WriteLine("RenewOnCallTime: " + lease.RenewOnCallTime); Console.WriteLine("SponsorshipTimeout: " + lease.SponsorshipTimeout); Console.WriteLine(lease.CurrentLeaseTime); } Console.WriteLine(obj.Greeting("Christian")); /* * for (int i=0; i< 5; i++) * { * Console.WriteLine(obj.Greeting("Christian")); * }*/ }
internal static object GetObjectData(object serObj, out string typeName, out string assemName, out string[] fieldNames, out object[] fieldValues) { Type objectType = null; object retObj = null; if (RemotingServices.IsTransparentProxy(serObj)) { objectType = typeof(MarshalByRefObject); } else { objectType = serObj.GetType(); } SerializationInfo si = new SerializationInfo(objectType, s_converter); if (serObj is ObjRef) { s_ObjRefRemotingSurrogate.GetObjectData(serObj, si, s_cloneContext); } else if (RemotingServices.IsTransparentProxy(serObj) || serObj is MarshalByRefObject) { // We can only try to smuggle objref's for actual CLR objects // or for RemotingProxy's. if (!RemotingServices.IsTransparentProxy(serObj) || RemotingServices.GetRealProxy(serObj) is RemotingProxy) { ObjRef objRef = RemotingServices.MarshalInternal((MarshalByRefObject)serObj, null, null); if (objRef.CanSmuggle()) { if (RemotingServices.IsTransparentProxy(serObj)) { RealProxy rp = RemotingServices.GetRealProxy(serObj); objRef.SetServerIdentity(rp._srvIdentity); objRef.SetDomainID(rp._domainID); } else { ServerIdentity srvId = (ServerIdentity)MarshalByRefObject.GetIdentity((MarshalByRefObject)serObj); srvId.SetHandle(); objRef.SetServerIdentity(srvId.GetHandle()); objRef.SetDomainID(AppDomain.CurrentDomain.GetId()); } objRef.SetMarshaledObject(); retObj = objRef; } } if (retObj == null) { // Deal with the non-smugglable remoting objects s_RemotingSurrogate.GetObjectData(serObj, si, s_cloneContext); } } else if (serObj is ISerializable) { ((ISerializable)serObj).GetObjectData(si, s_cloneContext); } else { // Getting here means a bug in cloner throw new ArgumentException(Environment.GetResourceString("Arg_SerializationException")); } if (retObj == null) { typeName = si.FullTypeName; assemName = si.AssemblyName; fieldNames = si.MemberNames; fieldValues = si.MemberValues; } else { typeName = null; assemName = null; fieldNames = null; fieldValues = null; } return(retObj); }
internal static object GetObjectData(object serObj, out string typeName, out string assemName, out string[] fieldNames, out object[] fieldValues) { Type type = null; object obj2 = null; if (RemotingServices.IsTransparentProxy(serObj)) { type = typeof(MarshalByRefObject); } else { type = serObj.GetType(); } SerializationInfo info = new SerializationInfo(type, s_converter); if (serObj is ObjRef) { s_ObjRefRemotingSurrogate.GetObjectData(serObj, info, s_cloneContext); } else if (RemotingServices.IsTransparentProxy(serObj) || (serObj is MarshalByRefObject)) { if (!RemotingServices.IsTransparentProxy(serObj) || (RemotingServices.GetRealProxy(serObj) is RemotingProxy)) { ObjRef ref2 = RemotingServices.MarshalInternal((MarshalByRefObject)serObj, null, null); if (ref2.CanSmuggle()) { if (RemotingServices.IsTransparentProxy(serObj)) { RealProxy realProxy = RemotingServices.GetRealProxy(serObj); ref2.SetServerIdentity(realProxy._srvIdentity); ref2.SetDomainID(realProxy._domainID); } else { ServerIdentity identity = (ServerIdentity)MarshalByRefObject.GetIdentity((MarshalByRefObject)serObj); identity.SetHandle(); ref2.SetServerIdentity(identity.GetHandle()); ref2.SetDomainID(AppDomain.CurrentDomain.GetId()); } ref2.SetMarshaledObject(); obj2 = ref2; } } if (obj2 == null) { s_RemotingSurrogate.GetObjectData(serObj, info, s_cloneContext); } } else { if (!(serObj is ISerializable)) { throw new ArgumentException(Environment.GetResourceString("Arg_SerializationException")); } ((ISerializable)serObj).GetObjectData(info, s_cloneContext); } if (obj2 == null) { typeName = info.FullTypeName; assemName = info.AssemblyName; fieldNames = info.MemberNames; fieldValues = info.MemberValues; return(obj2); } typeName = null; assemName = null; fieldNames = null; fieldValues = null; return(obj2); }
static void Main(string[] args) { string[] conf; string myRemoteObject = null; string serverLoc = null; int maxDelay = 0, minDelay = 0; if (args.Length == 0) //le do ficheiro { conf = ReadConfFile(); //pos 0 is port -- pos 1 is type } else //le dos argumentos { conf = ReadArgs(args); minDelay = System.Convert.ToInt32(conf[3]); maxDelay = System.Convert.ToInt32(conf[4]); myRemoteObject = conf[5]; } if (!conf[2].Equals("null")) { serverLoc = conf[2]; //serverLoc = System.Configuration.ConfigurationManager.AppSettings["server"]; } Console.WriteLine("Port:{0}\nType:{1}\nObj:{2}", conf[0], conf[1], myRemoteObject); BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider(); provider.TypeFilterLevel = TypeFilterLevel.Full; IDictionary props = new Hashtable(); props["port"] = System.Convert.ToInt32(conf[0]); props["timeout"] = 100; props["connectionTimeout"] = 100; TcpChannel channel = new TcpChannel(props, null, provider); ChannelServices.RegisterChannel(channel, true); ServerService mo = new ServerService(System.Convert.ToInt32(conf[1]), minDelay, maxDelay, serverLoc, args[6]); Console.WriteLine(serverLoc); if (serverLoc != null) { mo.Init(serverLoc); } if (System.Convert.ToInt32(conf[1]) == 1) { mo.SetTimer(); } RemotingServices.Marshal(mo, myRemoteObject, typeof(ServerService)); System.Console.WriteLine("<enter> para sair..."); System.Console.ReadLine(); mo.Logout(); }