move FrameworkName from corlib to System
[mcs.git] / class / corlib / System.Runtime.Remoting.Channels / CrossAppDomainChannel.cs
blob2f00e5ff4069686a93a0444f4b7661d4f347c8c6
1 //
2 // System.Runtime.Remoting.Channels.CrossAppDomainChannel.cs
3 //
4 // Author: Patrik Torstensson (totte_mono@yahoo.com)
5 // Lluis Sanchez Gual (lluis@ximian.com)
6 //
7 // 2003 (C) Copyright, Ximian, Inc.
8 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 //
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 //
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
34 using System.IO;
35 using System.Threading;
36 using System.Runtime.Remoting;
37 using System.Runtime.Remoting.Messaging;
38 using System.Runtime.Remoting.Channels;
39 using System.Runtime.Remoting.Contexts;
40 using System.Runtime.Serialization;
41 using System.Runtime.Serialization.Formatters.Binary;
42 using System.Reflection;
44 namespace System.Runtime.Remoting.Channels
47 // Holds the cross appdomain channel data (used to get/create the correct sink)
48 [Serializable]
49 internal class CrossAppDomainData
51 // TODO: Add context support
52 // Required for .NET compatibility
53 private object _ContextID;
54 private int _DomainID;
55 private string _processGuid;
57 internal CrossAppDomainData(int domainId)
59 _ContextID = (int) 0;
60 _DomainID = domainId;
61 _processGuid = RemotingConfiguration.ProcessId;
64 internal int DomainID
66 get { return _DomainID; }
69 internal string ProcessID
71 get { return _processGuid; }
75 // Responsible for marshalling objects between appdomains
76 [Serializable]
77 internal class CrossAppDomainChannel : IChannel, IChannelSender, IChannelReceiver
79 private const String _strName = "MONOCAD";
81 private static Object s_lock = new Object();
83 internal static void RegisterCrossAppDomainChannel()
85 lock (s_lock)
87 // todo: make singleton
88 CrossAppDomainChannel monocad = new CrossAppDomainChannel();
89 ChannelServices.RegisterChannel ((IChannel) monocad);
93 // IChannel implementation
94 public virtual String ChannelName
96 get { return _strName; }
99 public virtual int ChannelPriority
101 get { return 100; }
104 public String Parse(String url, out String objectURI)
106 objectURI = url;
107 return null;
110 // IChannelReceiver
111 public virtual Object ChannelData
113 get { return new CrossAppDomainData(Thread.GetDomainID()); }
116 public virtual String[] GetUrlsForUri(String objectURI)
118 throw new NotSupportedException("CrossAppdomain channel dont support UrlsForUri");
121 // Dummies
122 public virtual void StartListening(Object data) {}
123 public virtual void StopListening(Object data) {}
125 // IChannelSender
126 public virtual IMessageSink CreateMessageSink(String url, Object data, out String uri)
128 uri = null;
130 if (data != null)
132 // Get the data and then get the sink
133 CrossAppDomainData cadData = data as CrossAppDomainData;
134 if (cadData != null && cadData.ProcessID == RemotingConfiguration.ProcessId)
135 // GetSink creates a new sink if we don't have any (use contexts here later)
136 return CrossAppDomainSink.GetSink(cadData.DomainID);
138 if (url != null && url.StartsWith(_strName))
139 throw new NotSupportedException("Can't create a named channel via crossappdomain");
141 return null;
145 [MonoTODO("Handle domain unloading?")]
146 internal class CrossAppDomainSink : IMessageSink
148 private static Hashtable s_sinks = new Hashtable();
150 private static MethodInfo processMessageMethod =
151 typeof (CrossAppDomainSink).GetMethod ("ProcessMessageInDomain", BindingFlags.NonPublic|BindingFlags.Static);
154 private int _domainID;
156 internal CrossAppDomainSink(int domainID)
158 _domainID = domainID;
161 internal static CrossAppDomainSink GetSink(int domainID)
163 // Check if we have a sink for the current domainID
164 // note, locking is not to bad here, very few class to GetSink
165 lock (s_sinks.SyncRoot)
167 if (s_sinks.ContainsKey(domainID))
168 return (CrossAppDomainSink) s_sinks[domainID];
169 else
171 CrossAppDomainSink sink = new CrossAppDomainSink(domainID);
172 s_sinks[domainID] = sink;
174 return sink;
179 internal int TargetDomainId {
180 get { return _domainID; }
183 private struct ProcessMessageRes {
184 public byte[] arrResponse;
185 public CADMethodReturnMessage cadMrm;
188 #pragma warning disable 169
189 private static ProcessMessageRes ProcessMessageInDomain (
190 byte[] arrRequest,
191 CADMethodCallMessage cadMsg)
193 ProcessMessageRes res = new ProcessMessageRes ();
195 try
197 AppDomain.CurrentDomain.ProcessMessageInDomain (arrRequest, cadMsg, out res.arrResponse, out res.cadMrm);
199 catch (Exception e)
201 IMessage errorMsg = new MethodResponse (e, new ErrorMessage());
202 res.arrResponse = CADSerializer.SerializeMessage (errorMsg).GetBuffer();
204 return res;
206 #pragma warning restore 169
208 public virtual IMessage SyncProcessMessage(IMessage msgRequest)
210 IMessage retMessage = null;
212 try
214 // Time to transit into the "our" domain
215 byte [] arrResponse = null;
216 byte [] arrRequest = null;
218 CADMethodReturnMessage cadMrm = null;
219 CADMethodCallMessage cadMsg;
221 cadMsg = CADMethodCallMessage.Create (msgRequest);
222 if (null == cadMsg) {
223 // Serialize the request message
224 MemoryStream reqMsgStream = CADSerializer.SerializeMessage(msgRequest);
225 arrRequest = reqMsgStream.GetBuffer();
228 Context currentContext = Thread.CurrentContext;
230 try {
231 // InternalInvoke can't handle out arguments, this is why
232 // we return the results in a structure
233 ProcessMessageRes res = (ProcessMessageRes)AppDomain.InvokeInDomainByID (_domainID, processMessageMethod, null, new object [] { arrRequest, cadMsg });
234 arrResponse = res.arrResponse;
235 cadMrm = res.cadMrm;
236 } finally {
237 AppDomain.InternalSetContext (currentContext);
241 if (null != arrResponse) {
242 // Time to deserialize the message
243 MemoryStream respMsgStream = new MemoryStream(arrResponse);
245 // Deserialize the response message
246 retMessage = CADSerializer.DeserializeMessage(respMsgStream, msgRequest as IMethodCallMessage);
247 } else
248 retMessage = new MethodResponse (msgRequest as IMethodCallMessage, cadMrm);
250 catch (Exception e)
254 retMessage = new ReturnMessage (e, msgRequest as IMethodCallMessage);
256 catch (Exception)
258 // this is just to be sure
262 return retMessage;
265 public virtual IMessageCtrl AsyncProcessMessage (IMessage reqMsg, IMessageSink replySink)
267 AsyncRequest req = new AsyncRequest (reqMsg, replySink);
268 ThreadPool.QueueUserWorkItem (new WaitCallback (SendAsyncMessage), req);
269 return null;
272 public void SendAsyncMessage (object data)
274 AsyncRequest req = (AsyncRequest)data;
275 IMessage response = SyncProcessMessage (req.MsgRequest);
276 req.ReplySink.SyncProcessMessage (response);
279 public IMessageSink NextSink { get { return null; } }
282 internal class CADSerializer
284 internal static IMessage DeserializeMessage(MemoryStream mem, IMethodCallMessage msg)
286 BinaryFormatter serializer = new BinaryFormatter();
288 serializer.SurrogateSelector = null;
289 mem.Position = 0;
291 if (msg == null)
292 return (IMessage) serializer.Deserialize(mem, null);
293 else
294 return (IMessage) serializer.DeserializeMethodResponse(mem, null, msg);
297 internal static MemoryStream SerializeMessage(IMessage msg)
299 MemoryStream mem = new MemoryStream ();
300 BinaryFormatter serializer = new BinaryFormatter ();
302 serializer.SurrogateSelector = new RemotingSurrogateSelector ();
303 serializer.Serialize (mem, msg);
305 mem.Position = 0;
307 return mem;
310 internal static MemoryStream SerializeObject(object obj)
312 MemoryStream mem = new MemoryStream ();
313 BinaryFormatter serializer = new BinaryFormatter ();
315 serializer.SurrogateSelector = new RemotingSurrogateSelector ();
316 serializer.Serialize (mem, obj);
318 mem.Position = 0;
320 return mem;
323 internal static object DeserializeObject(MemoryStream mem)
325 BinaryFormatter serializer = new BinaryFormatter();
327 serializer.SurrogateSelector = null;
328 mem.Position = 0;
330 return serializer.Deserialize (mem);
334 internal class AsyncRequest
336 internal IMessageSink ReplySink;
337 internal IMessage MsgRequest;
339 public AsyncRequest (IMessage msgRequest, IMessageSink replySink)
341 ReplySink = replySink;
342 MsgRequest = msgRequest;