//==============================================================
//  版权所有：深圳杰文科技
//  文件名：RemotingProxyInterceptor.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Security.Permissions;
using Infrastructure.Log;

namespace Framework.RPC
{
	//Remoting调用拦截器。注意，此拦截器只能拦截本地客户端调用。未使用此拦截器。
	//[DebuggerStepThroughAttribute]
	public class RemotingProxyInterceptor : RealProxy
	{
		private string myUrl;
		private string myObjectURI;
		private IMessageSink myMessageSink;

		[PermissionSet(SecurityAction.LinkDemand)]
		public RemotingProxyInterceptor(Type myType, string myUrl1)
			: base(myType)
		{
			myUrl = myUrl1;

			IChannel[] myRegisteredChannels = ChannelServices.RegisteredChannels;
			foreach (IChannel channel in myRegisteredChannels)
			{
				if (channel is IChannelSender)
				{
					IChannelSender myChannelSender = (IChannelSender)channel;
					myMessageSink = myChannelSender.CreateMessageSink(myUrl, null, out myObjectURI);
					if (myMessageSink != null)
					{
						break;
					}
				}
			}

			if (myMessageSink == null)
			{
				throw new Exception("A supported channel could not be found for myUrl1:" + myUrl);
			}
		}

		[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
		public override IMessage Invoke(IMessage message)
		{
			IDictionary myDictionary = message.Properties;

			myDictionary["__Uri"] = myUrl;
			IMessage myRetMsg = myMessageSink.SyncProcessMessage(message);

			//if (myRetMsg is IMethodReturnMessage)
			//{
			//	IMethodReturnMessage myMethodReturnMessage = (IMethodReturnMessage)myRetMsg;
			//}
			IDictionaryEnumerator myEnum = (IDictionaryEnumerator)myDictionary.GetEnumerator();

			string s = "";
			while (myEnum.MoveNext())
			{
				switch (myEnum.Key.ToString())
				{
					case "__TypeName":
						break;

					case "__MethodName":
						string[] str = myUrl.Split('/');
						string action = str[str.Length - 1] + "." + myEnum.Value.ToString();
						s = s + action;
						break;

					case "__Args":
						Object[] myObjectArray = (Object[])myEnum.Value;
						for (int aIndex = 0; aIndex < myObjectArray.Length; aIndex++)
						{
							s = s + string.Format("\r\n\tArgs{0}：{1}", aIndex, myObjectArray[aIndex]);
						}
						break;
				}
			}

			SystemLogger.Instance.Write("", s);

			return myRetMsg;
		}
	}

}
