**** Merged from MCS ****
[mono-project.git] / mcs / class / corlib / System.Runtime.Remoting.Channels / CrossAppDomainChannel.cs
blobb0c5392e76d2e810ad3a718c8d1321587cf0920d
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 private int _ContextID;
53 private int _DomainID;
54 private string _processGuid;
56 internal CrossAppDomainData(int domainId)
58 _DomainID = domainId;
59 _processGuid = RemotingConfiguration.ProcessId;
62 internal int DomainID
64 get { return _DomainID; }
67 internal string ProcessID
69 get { return _processGuid; }
73 // Responsible for marshalling objects between appdomains
74 [Serializable]
75 internal class CrossAppDomainChannel : IChannel, IChannelSender, IChannelReceiver
77 private const String _strName = "MONOCAD";
78 private const String _strBaseURI = "MONOCADURI";
80 private static Object s_lock = new Object();
82 internal static void RegisterCrossAppDomainChannel()
84 lock (s_lock)
86 // todo: make singleton
87 CrossAppDomainChannel monocad = new CrossAppDomainChannel();
88 ChannelServices.RegisterChannel ((IChannel) monocad);
92 // IChannel implementation
93 public virtual String ChannelName
95 get { return _strName; }
98 public virtual int ChannelPriority
100 get { return 100; }
103 public String Parse(String url, out String objectURI)
105 objectURI = url;
106 return null;
109 // IChannelReceiver
110 public virtual Object ChannelData
112 get { return new CrossAppDomainData(Thread.GetDomainID()); }
115 public virtual String[] GetUrlsForUri(String objectURI)
117 throw new NotSupportedException("CrossAppdomain channel dont support UrlsForUri");
120 // Dummies
121 public virtual void StartListening(Object data) {}
122 public virtual void StopListening(Object data) {}
124 // IChannelSender
125 public virtual IMessageSink CreateMessageSink(String url, Object data, out String uri)
127 uri = null;
129 if (data != null)
131 // Get the data and then get the sink
132 CrossAppDomainData cadData = data as CrossAppDomainData;
133 if (cadData != null && cadData.ProcessID == RemotingConfiguration.ProcessId)
134 // GetSink creates a new sink if we don't have any (use contexts here later)
135 return CrossAppDomainSink.GetSink(cadData.DomainID);
137 if (url != null && url.StartsWith(_strName))
138 throw new NotSupportedException("Can't create a named channel via crossappdomain");
140 return null;
144 [MonoTODO("Handle domain unloading?")]
145 internal class CrossAppDomainSink : IMessageSink
147 private static Hashtable s_sinks = new Hashtable();
149 private static MethodInfo processMessageMethod =
150 typeof (CrossAppDomainSink).GetMethod ("ProcessMessageInDomain", BindingFlags.NonPublic|BindingFlags.Static);
153 private int _domainID;
155 internal CrossAppDomainSink(int domainID)
157 _domainID = domainID;
160 internal static CrossAppDomainSink GetSink(int domainID)
162 // Check if we have a sink for the current domainID
163 // note, locking is not to bad here, very few class to GetSink
164 lock (s_sinks.SyncRoot)
166 if (s_sinks.ContainsKey(domainID))
167 return (CrossAppDomainSink) s_sinks[domainID];
168 else
170 CrossAppDomainSink sink = new CrossAppDomainSink(domainID);
171 s_sinks[domainID] = sink;
173 return sink;
178 private struct ProcessMessageRes {
179 public byte[] arrResponse;
180 public CADMethodReturnMessage cadMrm;
183 private static ProcessMessageRes ProcessMessageInDomain (
184 byte[] arrRequest,
185 CADMethodCallMessage cadMsg)
187 ProcessMessageRes res = new ProcessMessageRes ();
189 try
191 AppDomain.CurrentDomain.ProcessMessageInDomain (arrRequest, cadMsg, out res.arrResponse, out res.cadMrm);
193 catch (Exception e)
195 IMessage errorMsg = new MethodResponse (e, new ErrorMessage());
196 res.arrResponse = CADSerializer.SerializeMessage (errorMsg).GetBuffer();
198 return res;
201 public virtual IMessage SyncProcessMessage(IMessage msgRequest)
203 IMessage retMessage = null;
205 try
207 // Time to transit into the "our" domain
208 byte [] arrResponse = null;
209 byte [] arrRequest = null;
211 CADMethodReturnMessage cadMrm = null;
212 CADMethodCallMessage cadMsg;
214 cadMsg = CADMethodCallMessage.Create (msgRequest);
215 if (null == cadMsg) {
216 // Serialize the request message
217 MemoryStream reqMsgStream = CADSerializer.SerializeMessage(msgRequest);
218 arrRequest = reqMsgStream.GetBuffer();
221 object threadStatus = Thread.ResetDataStoreStatus ();
222 Context currentContext = Thread.CurrentContext;
224 try {
225 // InternalInvoke can't handle out arguments, this is why
226 // we return the results in a structure
227 ProcessMessageRes res = (ProcessMessageRes)AppDomain.InvokeInDomainByID (_domainID, processMessageMethod, null, new object [] { arrRequest, cadMsg });
228 arrResponse = res.arrResponse;
229 cadMrm = res.cadMrm;
231 finally {
232 AppDomain.InternalSetContext (currentContext);
233 Thread.RestoreDataStoreStatus (threadStatus);
237 if (null != arrResponse) {
238 // Time to deserialize the message
239 MemoryStream respMsgStream = new MemoryStream(arrResponse);
241 // Deserialize the response message
242 retMessage = CADSerializer.DeserializeMessage(respMsgStream, msgRequest as IMethodCallMessage);
243 } else
244 retMessage = new MethodResponse (msgRequest as IMethodCallMessage, cadMrm);
246 catch (Exception e)
250 retMessage = new ReturnMessage (e, msgRequest as IMethodCallMessage);
252 catch (Exception)
254 // this is just to be sure
258 return retMessage;
261 public virtual IMessageCtrl AsyncProcessMessage (IMessage reqMsg, IMessageSink replySink)
263 AsyncRequest req = new AsyncRequest (reqMsg, replySink);
264 ThreadPool.QueueUserWorkItem (new WaitCallback (SendAsyncMessage), req);
265 return null;
268 public void SendAsyncMessage (object data)
270 AsyncRequest req = (AsyncRequest)data;
271 IMessage response = SyncProcessMessage (req.MsgRequest);
272 req.ReplySink.SyncProcessMessage (response);
275 public IMessageSink NextSink { get { return null; } }
278 internal class CADSerializer
280 internal static IMessage DeserializeMessage(MemoryStream mem, IMethodCallMessage msg)
282 BinaryFormatter serializer = new BinaryFormatter();
284 serializer.SurrogateSelector = null;
285 mem.Position = 0;
287 if (msg == null)
288 return (IMessage) serializer.Deserialize(mem, null);
289 else
290 return (IMessage) serializer.DeserializeMethodResponse(mem, null, msg);
293 internal static MemoryStream SerializeMessage(IMessage msg)
295 MemoryStream mem = new MemoryStream ();
296 BinaryFormatter serializer = new BinaryFormatter ();
298 serializer.SurrogateSelector = new RemotingSurrogateSelector ();
299 serializer.Serialize (mem, msg);
301 mem.Position = 0;
303 return mem;
306 internal static MemoryStream SerializeObject(object obj)
308 MemoryStream mem = new MemoryStream ();
309 BinaryFormatter serializer = new BinaryFormatter ();
311 serializer.SurrogateSelector = new RemotingSurrogateSelector ();
312 serializer.Serialize (mem, obj);
314 mem.Position = 0;
316 return mem;
319 internal static object DeserializeObject(MemoryStream mem)
321 BinaryFormatter serializer = new BinaryFormatter();
323 serializer.SurrogateSelector = null;
324 mem.Position = 0;
326 return serializer.Deserialize (mem);
330 internal class AsyncRequest
332 internal IMessageSink ReplySink;
333 internal IMessage MsgRequest;
335 public AsyncRequest (IMessage msgRequest, IMessageSink replySink)
337 ReplySink = replySink;
338 MsgRequest = msgRequest;