public override IMessage Invoke(IMessage request)
    {
        IMethodCallMessage call = (IMethodCallMessage)request;

        Console.WriteLine("Invoke " + call.MethodName);

        Console.Write("ARGS(");
        for (int i = 0; i < call.ArgCount; i++)
        {
            if (i != 0)
            {
                Console.Write(", ");
            }
            Console.Write(call.GetArgName(i) + " " +
                          call.GetArg(i));
        }
        Console.WriteLine(")");
        Console.Write("INARGS(");
        for (int i = 0; i < call.InArgCount; i++)
        {
            if (i != 0)
            {
                Console.Write(", ");
            }
            Console.Write(call.GetInArgName(i) + " " +
                          call.GetInArg(i));
        }
        Console.WriteLine(")");

        ((R1)target).test_field = 1;

        IMethodReturnMessage res = RemotingServices.ExecuteMessage(target, call);

        Console.Write("RESARGS(");
        for (int i = 0; i < res.ArgCount; i++)
        {
            if (i != 0)
            {
                Console.Write(", ");
            }
            Console.Write(res.GetArgName(i) + " " +
                          res.GetArg(i));
        }
        Console.WriteLine(")");

        Console.Write("RESOUTARGS(");
        for (int i = 0; i < res.OutArgCount; i++)
        {
            if (i != 0)
            {
                Console.Write(", ");
            }
            Console.Write(res.GetOutArgName(i) + " " +
                          res.GetOutArg(i));
        }
        Console.WriteLine(")");

        return(res);
    }
Exemple #2
0
 protected void PreProcess(ref IMethodCallMessage msg)
 {
     Trace.WriteLine(String.Format("TracePreProcessor {0} is called", msg.MethodName));
     if (msg.InArgCount > 0) Trace.WriteLine(String.Format("In Argument Count {0}", msg.InArgCount));
     for (int idx = 0; idx < msg.InArgCount; idx++)
     {
         Trace.WriteLine(String.Format("{0}={1}", msg.GetInArgName(idx), msg.GetInArg(idx)));
     }
 }
Exemple #3
0
        private Dictionary <string, object> GetParameters(IMethodCallMessage mcm)
        {
            Dictionary <string, object> dictionary = new Dictionary <string, object>();

            for (int i = 0; i < mcm.InArgCount; i++)
            {
                dictionary.Add(mcm.GetInArgName(i), mcm.GetInArg(i));
            }
            return(dictionary);
        }
Exemple #4
0
 public static string FormatInMessage(IMethodCallMessage msg)
 {
     string message = String.Format("Trace {0}.{1} is called",msg.MethodBase.DeclaringType.FullName, msg.MethodName) + System.Environment.NewLine;
     if (msg.InArgCount > 0)
     {
         message += String.Format("In Argument Count {0}", msg.InArgCount) + System.Environment.NewLine;
         for (int idx = 0; idx < msg.InArgCount; idx++)
         {
             message += String.Format("{0} = {1}", msg.GetInArgName(idx), msg.GetInArg(idx)) + System.Environment.NewLine;
         }
     }
     return message;
 }
        private Action <object> FindCallbackMethod(IMethodCallMessage methodCall, string callbackMethodName)
        {
            var argCount = methodCall.InArgCount;

            for (var index = 0; index < argCount; ++index)
            {
                if (methodCall.GetInArgName(index) == callbackMethodName)
                {
                    return(methodCall.GetInArg(index) as Action <object>);
                }
            }
            return(null);
        }
Exemple #6
0
        private object FetchBody(IMethodCallMessage methodCall)
        {
            object body       = null;
            var    jsonBody   = new Dictionary <string, object>();
            var    parameters = methodCall.MethodBase.GetParameters();

            for (int i = 0; i < methodCall.ArgCount; i++)
            {
                var argName   = methodCall.GetInArgName(i);
                var arg       = methodCall.GetInArg(i);
                var parameter = parameters.First(p => p.Name == argName);

                var binding = parameter.GetCustomAttribute <ParameterBindingAttribute>();
                if (binding != null)
                {
                    if (binding.BindingType == "Body")
                    {
                        if (!ReferenceEquals(body, null))
                        {
                            var parameterName = string.Format("[{0}].[{1}]", typeof(T).Name, methodCall.MethodBase.Name);
                            throw new ArgumentException(parameterName, parameterName + " 有多个复杂类型传入,请更新全部参数使用 JsonBodyAttribute 参数绑定!");
                        }
                        body = arg;
                    }
                    else if (binding.BindingType == "JsonBody")
                    {
                        jsonBody.Add(argName, arg);
                    }
                }
                else
                {
                    jsonBody.Add(argName, arg);
                }
            }

            if (body != null && jsonBody.Count == 0)
            {
                return(body);
            }
            else if (body == null && jsonBody.Count == 1)
            {
                return(jsonBody.First().Value);
            }
            else if (body == null && jsonBody.Count != 0)
            {
                return(jsonBody);
            }

            return(null);
        }
Exemple #7
0
        private Dictionary <string, object> GetParams(IMethodCallMessage methodCall)
        {
            var res = new Dictionary <string, object>();

            for (var i = 0; i < methodCall.InArgCount; i++)
            {
                var key = methodCall.GetInArgName(i);
                var val = methodCall.GetInArg(i);

                var stringVal = Serialize(val);

                res.Add(key, stringVal);
            }

            return(res);
        }
Exemple #8
0
        public void SerializeRequest(IMethodCallMessage message, ITransportHeaders requestHeaders, Stream requestStream)
        {
            BinaryWriter writer = new BinaryWriter(requestStream, Encoding.UTF8);

            // method info
            writer.Write(message.MethodName);

            // arguments count
            writer.Write((byte)message.InArgCount);

            // arguments list
            for (int i = 0; i < message.InArgCount; ++i)
            {
                SerializeObject(writer, message.GetInArg(i));
            }
        }
Exemple #9
0
        public DinazorResult CheckRequiredField(MethodInfo methodInfo, IMethodCallMessage msg)
        {
            DinazorResult result = new DinazorResult {
                Status = ResultStatus.Success
            };

            //try to find required attributes
            var requiredParameters =
                methodInfo.GetParameters()
                .Where(
                    l =>
                    l.GetCustomAttributes(false).FirstOrDefault(m => m is RequiredAttribute) != null).ToList();

            foreach (var parameterMessage in requiredParameters)
            {
                var parameter = msg.GetInArg(parameterMessage.Position);
                if (parameter == null)
                {
                    result.Message = parameterMessage.Name;
                    return(result);
                }
                if (parameter.GetType().IsPrimitive)
                {
                    continue;
                }

                Type type = parameter.GetType();
                var  requiredSubParameters = type.GetProperties().Where(l => l.GetCustomAttributes(false).FirstOrDefault(z => z.GetType() == typeof(RequiredAttribute)) != null).ToList();
                foreach (var propertyInfo in requiredSubParameters)
                {
                    var value = propertyInfo.GetValue(parameter);
                    if (value == null || value.ToString() == "")
                    {
                        string columnName   = propertyInfo.Name;
                        string errorMessage = propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), false).Cast <RequiredAttribute>().Single().ErrorMessage;
                        result.Message = LocaleManager.GetMessage(errorMessage, new string[1] {
                            columnName
                        });
                        result.Status = ResultStatus.MissingRequiredParamater;
                        _log.Error("Missing Required Parameter : " + columnName);
                        return(result);
                    }
                }
            }
            return(result);
        }
        private IMessage HandleRequestWithParameters(IMethodCallMessage methodCall, ParsedMethodInfo pmi)
        {
            var deliveredArguments = new string[methodCall.InArgCount];

            for (var i = 0; i < deliveredArguments.Length; ++i)
            {
                deliveredArguments[i] = methodCall.GetArgName(i);
            }

            var arguments = new object[pmi.ArgumentsOrder.Length];

            for (var i = 0; i < arguments.Length; ++i)
            {
                var arg   = pmi.ArgumentsOrder[i];
                var index = Array.FindIndex(deliveredArguments, expectedArgPosition => expectedArgPosition == arg);
                if (index >= 0)
                {
                    arguments[i] = methodCall.GetInArg(index);
                }
                else
                {
                    arguments[i] = null;
                }
            }

            Action <object> callback = FindCallbackMethod(methodCall, pmi.CallbackArgumentName);

            if (callback == null)
            {
                throw new SystemException("No callback reference found!");
            }
            var fullRequest = string.Format(pmi.RequestUrl, arguments);

            _context.StartCoroutine(DownloadDataCoroutine(callback, pmi.ReturnType, fullRequest));

            return(new ReturnMessage(null, null, 0, methodCall.LogicalCallContext, methodCall));
        }
Exemple #11
0
        private string ReplenishURL(IMethodCallMessage methodCall)
        {
            var data       = new List <string>();
            var parameters = methodCall.MethodBase.GetParameters();

            for (int i = 0; i < methodCall.ArgCount; i++)
            {
                var argName   = methodCall.GetInArgName(i);
                var arg       = methodCall.GetInArg(i);
                var parameter = parameters.First(p => p.Name == argName);

                var binding = parameter.GetCustomAttribute <ParameterBindingAttribute>();
                if (binding == null)
                {
                    continue;
                }

                if (binding.BindingType == "Uri")
                {
                    data.Add(string.Format("{0}={1}", argName, Uri.EscapeUriString(ReferenceEquals(arg, null) ? "null" : arg.ToString())));
                }
                else if (binding.BindingType == "ODataParameter" && !ReferenceEquals(arg, null))
                {
                    var dataParameter = new RemoteDataParameter();

                    var processor = RemoteObjectContext.DefaultObjectResolver.GetInstance <IExpressionProcessor>();
                    processor.Writer        = RemoteObjectContext.DefaultObjectResolver.GetInstance <IExpressionWriter>();
                    processor.DataParameter = dataParameter;

                    processor.Build((arg as LambdaExpression).Body as MethodCallExpression);

                    data.Add(dataParameter.BuildUri());
                }
            }

            return(string.Join("&", data));
        }
Exemple #12
0
        public void SerializeRequest(Stream serializationStream, object graph)
        {
            if (serializationStream == null)
            {
                throw new ArgumentNullException("serializationStream is null");
            }

            BinaryWriter writer = new BinaryWriter(serializationStream);

            IMethodCallMessage msg = graph as IMethodCallMessage;

            if (msg != null)
            {
                writer.Write(msg.MethodName);
                writer.Write((int)msg.InArgCount);
                for (int i = 0; i < msg.InArgCount; i++)
                {
                    SerializeObject(writer, msg.GetInArg(i));
                }
                return;
            }

            throw new NotSupportedException();
        }
 public object GetInArg(int argNum)
 {
     return(orig.GetInArg(argNum));
 }
Exemple #14
0
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage methodCall = msg as IMethodCallMessage;
            var invariantCulture          = System.Globalization.CultureInfo.InvariantCulture;

            if (null != methodCall)
            {
                try
                {
                    HttpMethod          httpMethod          = HttpMethod.Get;
                    HttpMethodAttribute httpMethodAttribute = methodCall.MethodBase.GetCustomAttribute <HttpMethodAttribute>(true);

                    if (null != httpMethodAttribute)
                    {
                        httpMethod = httpMethodAttribute.HttpMethod;
                    }

                    ResourceAttribute resourceUrlAttribute = methodCall.MethodBase.GetCustomAttribute <ResourceAttribute>(true);

                    string actionUrl = string.Empty;

                    if (null != resourceUrlAttribute)
                    {
                        actionUrl = resourceUrlAttribute.Relative;
                    }

                    Type expectedReturn = ((MethodInfo)methodCall.MethodBase).ReturnType;

                    object   retVal  = null;
                    object[] outArgs = null;

                    Dictionary <string, object> toSerialize   = new Dictionary <string, object>();
                    Dictionary <string, string> toQueryString = new Dictionary <string, string>();

                    // Determines which arguments should be used in the querystring parameters, and which arguments will be serialized and posted.
                    for (int argIndex = 0, argCount = methodCall.InArgCount; argIndex < argCount; argIndex++)
                    {
                        object value = methodCall.GetInArg(argIndex);

                        if (null == value || value.GetType().IsPrimitiveOrBasicStruct())
                        {
                            if (null != value && value is DateTime)
                            {
                                value = ((DateTime)value).ToLocalTime();

                                StringBuilder sb = new StringBuilder();
                                using (TextWriter writer = new StringWriter(sb, invariantCulture))
                                {
                                    this.m_jsonSerializer.Serialize(writer, value);
                                }

                                value = sb.ToString();
                                value = ((string)value).Substring(1, ((string)value).Length - 2);

                                toQueryString.Add(methodCall.GetInArgName(argIndex), (value != null) ? value.ToString() : string.Empty);
                            }
                            else
                            {
                                toQueryString.Add(methodCall.GetInArgName(argIndex), (value != null) ? HttpUtility.UrlEncode(value.ToString()) : string.Empty);
                            }
                        }
                        else
                        {
                            toSerialize.Add(methodCall.GetInArgName(argIndex), value);
                        }
                    }

                    {
                        // Prepare the post content.
                        byte[] postData = null;

                        string responseData;

                        if (toSerialize.Count > 0)
                        {
                            StringBuilder sb = new StringBuilder();
                            using (TextWriter writer = new StringWriter(sb, invariantCulture))
                            {
                                if (toSerialize.Count == 1)
                                {
                                    this.m_jsonSerializer.Serialize(writer, toSerialize.Values.First());
                                }
                                else
                                {
                                    this.m_jsonSerializer.Serialize(writer, toSerialize);
                                }
                            }

                            postData = Encoding.UTF8.GetBytes(sb.ToString());
                        }

                        if ((postData == null || postData.Length == 0) && httpMethod != HttpMethod.Get)
                        {
                            postData = Encoding.UTF8.GetBytes("{}");
                        }

                        // Assemble the querystring.
                        object[] urlParameters = null;

                        if (null != resourceUrlAttribute && resourceUrlAttribute.ParameterNames.Count() > 0)
                        {
                            urlParameters = new object[resourceUrlAttribute.ParameterNames.Count()];

                            for (int i = 0, total = resourceUrlAttribute.ParameterNames.Count(); i < total; i++)
                            {
                                string parameterName = resourceUrlAttribute.ParameterNames[i];

                                if (toQueryString.ContainsKey(parameterName))
                                {
                                    urlParameters[i] = toQueryString[parameterName];
                                    toQueryString.Remove(parameterName);
                                }
                                else if (toSerialize.ContainsKey(parameterName))
                                {
                                    urlParameters[i] = toSerialize[parameterName];
                                    toSerialize.Remove(parameterName);
                                }
                            }
                        }

                        var queryString = string.Empty;

                        if (toQueryString.Count > 0)
                        {
                            queryString = "?" + string.Join("&", (from kvp in toQueryString select kvp.Key + "=" + kvp.Value).ToArray());
                        }

                        // Determine the final url
                        if (null != urlParameters)
                        {
                            actionUrl = string.Format(invariantCulture, actionUrl, urlParameters);
                        }

                        string serviceUrl = this.Configuration.Root + this.Configuration.Relative + actionUrl + queryString;

                        // Create the request context
                        RequestContext context = this.Context.CreateRequestContext();

                        context.RequestUrl = new Uri(serviceUrl);

                        // Create and configure the HTTP request
                        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(context.RequestUrl);
                        {
                            webRequest.Method  = httpMethod.ToString().ToUpper();
                            webRequest.Timeout = this.Configuration.RequestTimeout ?? (5 * 60 * 1000);

                            if (null != this.Configuration.RequestHeaders)
                            {
                                foreach (var kvp in this.Configuration.RequestHeaders)
                                {
                                    webRequest.Headers[kvp.Key] = kvp.Value;
                                }
                            }

                            if (null != postData && postData.Length > 0)
                            {
                                webRequest.ContentLength = postData.Length;
                                webRequest.ContentType   = "application/json; charset=UTF-8";

                                Stream postStream = webRequest.GetRequestStream();
                                postStream.Write(postData, 0, postData.Length);
                                postStream.Close();
                            }
                        }

                        HttpWebResponse response = null;

                        {
                            Stopwatch timer = Stopwatch.StartNew();

                            try
                            {
                                // Add a HTTP header with a random number to help tracking the request here and on the remote server
                                int randomNumber = new Random().Next(int.MaxValue);

                                webRequest.Headers["X-SP-Unique-Identifier"] = randomNumber.ToString(invariantCulture);

                                // Send the request
                                response = (HttpWebResponse)webRequest.GetResponse();
                            }
                            catch (WebException ex)
                            {
                                string errorContent = null;

                                if (ex.Response != null)
                                {
                                    context.ResponseStatus = (int)((HttpWebResponse)ex.Response).StatusCode;

                                    if (ex.Response.ContentLength != 0)
                                    {
                                        using (var stream = ex.Response.GetResponseStream())
                                        {
                                            if (null != stream)
                                            {
                                                using (var reader = new StreamReader(stream))
                                                {
                                                    errorContent = reader.ReadToEnd();

                                                    context.ResponseSize = errorContent.Length;
                                                }
                                            }
                                        }

                                        string errorResult = null;

                                        if (null != errorContent)
                                        {
                                            using (StringReader r = new StringReader(errorContent))
                                            {
                                                errorResult = r.ReadToEnd();
                                            }
                                        }

                                        if (!string.IsNullOrWhiteSpace(errorResult))
                                        {
                                            context.ResponseContent = errorResult;

                                            throw new ProxyException(errorResult, (HttpWebResponse)ex.Response);
                                        }
                                    }
                                }

                                throw new ProxyException(string.Format(invariantCulture, "Exception caught while performing a {0} request to url '{1}'. {2}: {3}", httpMethod.ToString(), serviceUrl, ex.GetType().Name, ex.Message), ex);
                            }
                            finally
                            {
                                var elapsedMilliseconds = timer.ElapsedMilliseconds;

                                timer.Stop();

                                context.RequestElapsedMilliseconds = elapsedMilliseconds;
                                context.RequestElapsedTime         = new TimeSpan(0, 0, 0, 0, (int)elapsedMilliseconds);
                            }

                            context.ResponseHeaders.Clear();

                            // Add the response information to the context
                            for (int index = 0, total = response.Headers.Count; index < total; index++)
                            {
                                context.ResponseHeaders[response.Headers.GetKey(index)] = response.Headers.Get(index);
                            }

                            context.ResponseStatus = (int)response.StatusCode;

                            if ((int)response.StatusCode >= 400)
                            {
                                throw new ProxyException("Invalid HTTP status code.", response);
                            }

                            // Read the response contents
                            Stream responseStream = response.GetResponseStream();

                            using (StreamReader responseReader = new StreamReader(responseStream))
                            {
                                responseData = responseReader.ReadToEnd();

                                // note: context.ResponseSize should be in bytes, not string length
                                // ContentLength should be length reported in the Content-Length header (number of octets)
                                context.ResponseSize = response.ContentLength;

                                context.ResponseContent = responseData;

                                responseReader.Close();
                            }

                            responseStream.Close();
                            response.Close();
                        }

                        // Attempt to deserialize the response contents
                        if (context.ResponseHeaders.ContainsKey("Content-Type"))
                        {
                            string contentType = (context.ResponseHeaders["Content-Type"] ?? string.Empty).Split(';').FirstOrDefault(h => !h.Trim().StartsWith("charset", StringComparison.OrdinalIgnoreCase));

                            string temp = contentType.Split('/').Last();

                            if (temp.EndsWith("json", StringComparison.OrdinalIgnoreCase) || temp.EndsWith("javascript", StringComparison.OrdinalIgnoreCase))
                            {
                                using (StringReader r = new StringReader(responseData))
                                {
                                    using (JsonReader r2 = new JsonTextReader(r))
                                    {
                                        r2.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

                                        if (expectedReturn != typeof(void))
                                        {
                                            retVal = this.m_jsonSerializer.Deserialize(r2, expectedReturn);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                throw new ProxyException("Unknown response content type: " + contentType, response);
                            }
                        }
                    }

                    int outArgsCount = null != outArgs ? outArgs.Length : 0;

                    IMethodReturnMessage callResult = new ReturnMessage(retVal, outArgs, outArgsCount, methodCall.LogicalCallContext, methodCall);

                    return(callResult);
                }
                catch (Exception e)
                {
                    return(new ReturnMessage(e, methodCall));
                }
            }
            else
            {
                throw new NotSupportedException();
            }
        }
        public override IMessage Invoke(IMessage msg)
        {
            #region 日志准备

            List <string> opObjPerporty = UtilitysForT <SSY_LOGENTITY> .GetAllColumns(new SSY_LOGENTITY()); //要操作的属性名

            List <string> opWherePerporty = new List <string>();                                            //where条件属性名
            opWherePerporty.Add("LOGID");
            List <string> mainProperty = new List <string>();                                               //主键属性名
            mainProperty.Add("LOGID");

            //string errStr = string.Empty;
            List <string>        errStr  = new List <string>();
            List <SSY_LOGENTITY> opList  = new List <SSY_LOGENTITY>();
            SSY_LOGENTITY        logenti = null;

            BizExectuteCommon recordLog = new BizExectuteCommon(ManagerSysEnvironment.GetSysEnvironmentSerialize()); //其他工厂记录日志也利用该公共方法

            //日志固定部分
            string USERNAMES = string.Empty;
            if (FrameCommon.SysEnvironment.SysUserDict != null)
            {
                if (FrameCommon.SysEnvironment.SysUserDict.USERNAME != null)
                {
                    USERNAMES = FrameCommon.SysEnvironment.SysUserDict.USERNAME.ToString();
                }
            }
            string IPS = string.Empty;
            if (!string.IsNullOrEmpty(FrameCommon.SysEnvironment.Ips))
            {
                IPS = FrameCommon.SysEnvironment.Ips;
            }
            string SYSTEMNAME = string.Empty;
            if (!string.IsNullOrEmpty(FrameCommon.SysEnvironment.distManagerParam.DistributeDataNodes[0].Systemname))
            {
                SYSTEMNAME = FrameCommon.SysEnvironment.distManagerParam.DistributeDataNodes[0].Systemname;
            }

            #endregion

            IMethodCallMessage mcall = (IMethodCallMessage)msg; //劫持方法,准备执行
            var resResult            = new ReturnMessage(new Exception(), mcall);

            #region 获取必要参数

            //distributeActionIden  分布式动作识别, 必须存在
            //distributeDataNodes 分布式数据节点集合, 必须存在
            //distributeDataNode 分布式数据节点参数, 必须存在
            //distriActionSql 分布式操作sql集合,必须存在,包括sql正文和参数
            //ddnmParams

            //singleActionList  单点操作失败集合, out参数 非必须存在,传入空的参数即可

            //TODO 检查必须的参数,若不存在不进行执行业务方法,返回执行异常

            //获取分布式管理参数
            DistributeDataNodeManagerParams distManagerParam = new  DistributeDataNodeManagerParams();
            for (int i = 0; i < mcall.InArgs.Length; i++)
            {
                if (mcall.GetInArgName(i).ToUpper() == "ddnmParams".ToUpper())
                {
                    distManagerParam = ((DistributeDataNodeManagerParams)mcall.GetInArg(i));
                    //SYSTEMNAME = distManagerParam.DistributeDataNodes[0].Systemname;
                    break;
                }
            }

            //获取分布式动作识别参数
            DistributeActionIden distBAC = distManagerParam.DistributeActionIden;

            //加载数据节点集合,然后根据节点数量及分布式动作识别初始化分布式数据节点及分布式事务处理
            //数据节点集合由服务方法传入
            //获取数据节点集合参数
            List <SSY_DATANODE_ADDR> dataNodes = distManagerParam.DistributeDataNodes;

            //获取数据节点参数
            DistributeDataNode ddn = distManagerParam.DistributeDataNode;

            //单点操作失败集合,最后要报告给节点中心,out参数
            bool permitSingleDataOperation = false; //是否支持单点操作失败后进行报告
            List <SSY_DATA_ACTION_TASK> data_action_task = new List <SSY_DATA_ACTION_TASK>();
            for (int i = 0; i < mcall.InArgs.Length; i++)
            {
                if (mcall.GetInArgName(i).ToUpper() == "singleActionList".ToUpper())
                {
                    permitSingleDataOperation = true;
                    data_action_task          = mcall.GetInArg(i) as List <SSY_DATA_ACTION_TASK>;
                    break;
                }
            }

            #endregion

            if (distBAC == DistributeActionIden.Query)
            {
                //处理数据节点
                //distManagerParam.DistributeDataNode
                distManagerParam.DistributeDataNode.Connectionstring = string.Format(dataNodes[0].Data_conn, dataNodes[0].Url_addr,
                                                                                     dataNodes[0].Data_user, dataNodes[0].Data_password);
                distManagerParam.DistributeDataNode.DbSchema = dataNodes[0].Data_schema;

                //只执行一次即可
                #region 执行业务方法

                try
                {
                    object objRv = mcall.MethodBase.Invoke(this.Target, mcall.Args);

                    #region 记录业务日志

                    //执行方法后记录正常业务日志,内容来自方法ListBizLog参数
                    //若要记录日志,要求该方法必须传入该参数,且名字必须为ListBizLog,内容为要记录的业务日志内容
                    SSY_LOGENTITY tempLog = null;
                    for (int i = 0; i < mcall.InArgs.Length; i++)
                    {
                        if (mcall.GetInArgName(i).ToUpper() == "ListBizLog".ToUpper())
                        {
                            List <SSY_LOGENTITY> dictBizLog = mcall.GetInArg(i) as List <SSY_LOGENTITY>;

                            for (int j = 0; j < dictBizLog.Count; j++)
                            {
                                //遍历记录业务日志
                                tempLog = dictBizLog[j] as SSY_LOGENTITY;

                                //获取日志控制,确定是否记录该类日志
                                if (recordLog.CheckIsRecord(tempLog.DOMAINNAME.ToString(), tempLog.OPTIONNAME.ToString(), distManagerParam))
                                {
                                    tempLog.LOGID = recordLog.GetID(MakeIDType.YMDHMS_3, string.Empty, null, distManagerParam);

                                    //业务直接使用业务端提交的数据,不在读取框架环境变量,因为登录时这部分数据滞后,导致不能记入日志
                                    //tempLog.USERNAMES = USERNAMES;
                                    //tempLog.IPS = IPS;
                                    //tempLog.SYSTEMNAME = SYSTEMNAME;

                                    opList.Add(tempLog);
                                }
                            }
                            if (opList.Count > 0)
                            {
                                //记录日志
                                bool flag = recordLog.OpBizObjectSingle <SSY_LOGENTITY>(opList, opObjPerporty, opWherePerporty, mainProperty, errStr, distManagerParam);
                            }
                            break;
                        }
                    }

                    #endregion

                    resResult = new ReturnMessage(objRv, mcall.Args, mcall.Args.Length, mcall.LogicalCallContext, mcall);
                }
                catch (Exception ex)
                {
                    Common.Utility.RecordLog("工厂 Query 模式发生异常!原因" + ex.Message + ex.Source, this.logpathForDebug, this.isLogpathForDebug);

                    #region 记录异常日志

                    if (ex.InnerException != null)
                    {
                        //获取日志控制,确定是否记录该类日志
                        if (recordLog.CheckIsRecord("ExceptionErr", "ExceptionErr", distManagerParam))
                        {
                            //处理异常类相关信息
                            string CLASSNAME   = mcall.TypeName;
                            string METHORDNAME = mcall.MethodName;

                            //异常时这部分可没有内容
                            string TABLENAME            = "";
                            string RECORDIDENCOLS       = "";
                            string RECORDIDENCOLSVALUES = "";
                            string FUNCTIONNAME         = "";

                            logenti = LogCommon.CreateLogDataEnt(LogTypeDomain.ExceptionErr, LogLevelOption.ExecptionErr, recordLog.GetSystemDateTime(distManagerParam),
                                                                 CLASSNAME, METHORDNAME, LogAction.ExecptionErr, TABLENAME, RECORDIDENCOLS, RECORDIDENCOLSVALUES, USERNAMES, IPS, FUNCTIONNAME,
                                                                 ex.InnerException.Message, SYSTEMNAME, "");
                            logenti.LOGID = recordLog.GetID(MakeIDType.YMDHMS_3, string.Empty, null, distManagerParam);

                            opList.Add(logenti);

                            if (opList.Count > 0)
                            {
                                //记录日志
                                bool flag = recordLog.OpBizObjectSingle <SSY_LOGENTITY>(opList, opObjPerporty, opWherePerporty, mainProperty, errStr, distManagerParam);
                            }
                        }

                        resResult = new ReturnMessage(ex.InnerException, mcall);
                    }

                    #endregion

                    resResult = new ReturnMessage(ex, mcall);
                }

                #endregion
            }
            else if (distBAC == DistributeActionIden.SingleAction)
            {
                //数据节点有几个执行几次,单次提交,发现执行异常,将异常报告给节点中心,继续执行,直到完毕
                for (int m = 0; m < dataNodes.Count; m++)
                {
                    //ddn.DbFactoryName  数据库工厂取配置文件,目前不考虑同构不同种类的数据库
                    distManagerParam.DistributeDataNode.Connectionstring = string.Format(dataNodes[m].Data_conn, dataNodes[m].Url_addr, dataNodes[m].Data_user,
                                                                                         dataNodes[m].Data_password);
                    distManagerParam.DistributeDataNode.DbSchema = dataNodes[m].Data_schema;

                    #region 执行业务方法

                    try
                    {
                        object objRv = mcall.MethodBase.Invoke(this.Target, mcall.Args);

                        #region 记录业务日志

                        //执行方法后记录正常业务日志,内容来自方法ListBizLog参数
                        //若要记录日志,要求该方法必须传入该参数,且名字必须为ListBizLog,内容为要记录的业务日志内容
                        SSY_LOGENTITY tempLog = null;
                        for (int i = 0; i < mcall.InArgs.Length; i++)
                        {
                            if (mcall.GetInArgName(i).ToUpper() == "ListBizLog".ToUpper())
                            {
                                List <SSY_LOGENTITY> dictBizLog = mcall.GetInArg(i) as List <SSY_LOGENTITY>;

                                for (int j = 0; j < dictBizLog.Count; j++)
                                {
                                    //遍历记录业务日志
                                    tempLog = dictBizLog[j] as SSY_LOGENTITY;

                                    //获取日志控制,确定是否记录该类日志
                                    if (recordLog.CheckIsRecord(tempLog.DOMAINNAME.ToString(), tempLog.OPTIONNAME.ToString(), distManagerParam))
                                    {
                                        tempLog.LOGID = recordLog.GetID(MakeIDType.YMDHMS_3, string.Empty, null, distManagerParam);

                                        //业务直接使用业务端提交的数据,不在读取框架环境变量,因为登录时这部分数据滞后,导致不能记入日志
                                        //tempLog.USERNAMES = USERNAMES;
                                        //tempLog.IPS = IPS;
                                        //tempLog.SYSTEMNAME = SYSTEMNAME;

                                        opList.Add(tempLog);
                                    }
                                }
                                if (opList.Count > 0)
                                {
                                    //记录日志
                                    bool flag = recordLog.OpBizObjectSingle <SSY_LOGENTITY>(opList, opObjPerporty, opWherePerporty, mainProperty, errStr, distManagerParam);
                                }
                                break;
                            }
                        }

                        #endregion

                        resResult = new ReturnMessage(objRv, mcall.Args, mcall.Args.Length, mcall.LogicalCallContext, mcall);
                    }
                    catch (Exception ex)
                    {
                        SSY_DATA_ACTION_TASK tempDataTask = null;

                        #region 记录异常日志

                        if (ex.InnerException != null)
                        {
                            //获取日志控制,确定是否记录该类日志
                            if (recordLog.CheckIsRecord("ExceptionErr", "ExceptionErr", distManagerParam))
                            {
                                //处理异常类相关信息
                                string CLASSNAME   = mcall.TypeName;
                                string METHORDNAME = mcall.MethodName;

                                //异常时这部分可没有内容
                                string TABLENAME            = "";
                                string RECORDIDENCOLS       = "";
                                string RECORDIDENCOLSVALUES = "";
                                string FUNCTIONNAME         = "";

                                logenti = LogCommon.CreateLogDataEnt(LogTypeDomain.ExceptionErr, LogLevelOption.ExecptionErr, recordLog.GetSystemDateTime(distManagerParam),
                                                                     CLASSNAME, METHORDNAME, LogAction.ExecptionErr, TABLENAME, RECORDIDENCOLS, RECORDIDENCOLSVALUES, USERNAMES, IPS, FUNCTIONNAME,
                                                                     ex.InnerException.Message, SYSTEMNAME, "");
                                logenti.LOGID = recordLog.GetID(MakeIDType.YMDHMS_3, string.Empty, null, distManagerParam);

                                opList.Add(logenti);

                                if (opList.Count > 0)
                                {
                                    //记录日志
                                    bool flag = recordLog.OpBizObjectSingle <SSY_LOGENTITY>(opList, opObjPerporty, opWherePerporty, mainProperty, errStr, distManagerParam);
                                }
                            }
                            if (permitSingleDataOperation)
                            {
                                #region 获取失败操作sql

                                //获取失败记录,以便将任务报告给节点中心
                                //获取操作sql  List<DistActionSql> DistriActionSqlParams

                                for (int task = 0; task < distManagerParam.DistriActionSqlParams.Count; task++)
                                {
                                    tempDataTask            = new SSY_DATA_ACTION_TASK();
                                    tempDataTask.Action_sql = distManagerParam.DistriActionSqlParams[task].ActionSqlText;
                                    string tempSqlParamSeq = string.Empty;
                                    bool   temddddd        = JsonSerializer.Serialize(distManagerParam.DistriActionSqlParams[task].ActionSqlTextParams, out tempSqlParamSeq);
                                    //保存sql参数序列化结果
                                    tempDataTask.Action_sql_params = tempSqlParamSeq;
                                    tempDataTask.Data_real_conn    = ddn.Connectionstring;
                                    data_action_task.Add(tempDataTask);
                                }
                                //执行完毕后,清除本次的sql记录
                                distManagerParam.DistriActionSqlParams.Clear();

                                //TODO 报告单点异常给节点中心,暂时不支持,后续扩展
                                #endregion
                            }
                        }

                        #endregion

                        continue; //继续执行
                    }

                    #endregion
                }
            }
            else if (distBAC == DistributeActionIden.TransAction)
            {
                try
                {
                    //分布式事务执行, 按数据节点数量执行,同步提交
                    using (var ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, TimeSpan.FromHours(1)))
                    {
                        for (int m = 0; m < dataNodes.Count; m++)
                        {
                            //ddn.DbFactoryName  数据库工厂取配置文件,目前不考虑同构不同种类的数据库
                            distManagerParam.DistributeDataNode.Connectionstring = string.Format(dataNodes[m].Data_conn, dataNodes[m].Url_addr, dataNodes[m].Data_user,
                                                                                                 dataNodes[m].Data_password);
                            distManagerParam.DistributeDataNode.DbSchema = dataNodes[m].Data_schema;

                            #region 执行业务方法

                            object objRv = mcall.MethodBase.Invoke(this.Target, mcall.Args);

                            #region 记录业务日志

                            //执行方法后记录正常业务日志,内容来自方法ListBizLog参数
                            //若要记录日志,要求该方法必须传入该参数,且名字必须为ListBizLog,内容为要记录的业务日志内容
                            SSY_LOGENTITY tempLog = null;
                            for (int i = 0; i < mcall.InArgs.Length; i++)
                            {
                                if (mcall.GetInArgName(i).ToUpper() == "ListBizLog".ToUpper())
                                {
                                    List <SSY_LOGENTITY> dictBizLog = mcall.GetInArg(i) as List <SSY_LOGENTITY>;

                                    for (int j = 0; j < dictBizLog.Count; j++)
                                    {
                                        //遍历记录业务日志
                                        tempLog = dictBizLog[j] as SSY_LOGENTITY;

                                        //获取日志控制,确定是否记录该类日志
                                        if (recordLog.CheckIsRecord(tempLog.DOMAINNAME.ToString(), tempLog.OPTIONNAME.ToString(), distManagerParam))
                                        {
                                            tempLog.LOGID = recordLog.GetID(MakeIDType.YMDHMS_3, string.Empty, null, distManagerParam);

                                            //业务直接使用业务端提交的数据,不在读取框架环境变量,因为登录时这部分数据滞后,导致不能记入日志
                                            //tempLog.USERNAMES = USERNAMES;
                                            //tempLog.IPS = IPS;
                                            //tempLog.SYSTEMNAME = SYSTEMNAME;

                                            opList.Add(tempLog);
                                        }
                                    }
                                    //这里事物不能同时记录日志,需要放到业务方法提交完成后单独记录日志
                                    if (opList.Count > 0)
                                    {
                                        //记录日志
                                        bool flag = recordLog.OpBizObjectSingle <SSY_LOGENTITY>(opList, opObjPerporty, opWherePerporty, mainProperty, errStr, distManagerParam);
                                    }
                                    break;
                                }
                            }

                            #endregion

                            resResult = new ReturnMessage(objRv, mcall.Args, mcall.Args.Length, mcall.LogicalCallContext, mcall);

                            #endregion
                        }

                        ts.Complete();
                        ts.Dispose();
                    }

                    //同时记录日志,因为日志记录去掉事物方式
                    ////恢复事物默认标识
                    //distManagerParam.DistributeActionIden = DistributeActionIden.Query;
                    ////启用事物日志需要独立记录,不能和业务操作混在一个事物里
                    //for (int m = 0; m < dataNodes.Count; m++)
                    //{
                    //    //ddn.DbFactoryName  数据库工厂取配置文件,目前不考虑同构不同种类的数据库
                    //    distManagerParam.DistributeDataNode.Connectionstring = string.Format(dataNodes[m].Data_conn, dataNodes[m].Url_addr, dataNodes[m].Data_user,
                    //    dataNodes[m].Data_password);
                    //    distManagerParam.DistributeDataNode.DbSchema = dataNodes[m].Data_schema;

                    //    if (opList.Count > 0)
                    //    {
                    //        //记录日志
                    //        bool flag = recordLog.OpBizObjectSingle<SSY_LOGENTITY>(opList, opObjPerporty, opWherePerporty, mainProperty, errStr, distManagerParam);

                    //    }
                    //}
                }
                catch (Exception ex)
                {
                    Common.Utility.RecordLog("工厂 TransAction 模式发生异常!原因" + ex.Message + ex.Source, this.logpathForDebug, this.isLogpathForDebug);
                }
            }

            //最终返回结果,循环处理数据节点时,只返回最后一个执行成功的数据节点的执行情况
            return(resResult);
        }
        public override IMessage Invoke(IMessage reqMsg)
        {
            this.AssertValid();
            IMessage message = null;

            if (reqMsg is IConstructionCallMessage)
            {
                if (((IConstructionCallMessage)reqMsg).ArgCount > 0)
                {
                    throw new ServicedComponentException(Resource.FormatString("ServicedComponentException_ConstructorArguments"));
                }
                MarshalByRefObject transparentProxy = (MarshalByRefObject)this.GetTransparentProxy();
                return(EnterpriseServicesHelper.CreateConstructionReturnMessage((IConstructionCallMessage)reqMsg, transparentProxy));
            }
            MethodBase methodBase = ((IMethodMessage)reqMsg).MethodBase;
            MemberInfo mi         = methodBase;

            if (methodBase == _getTypeMethod)
            {
                IMethodCallMessage mcm = (IMethodCallMessage)reqMsg;
                return(new ReturnMessage(this.ProxiedType, null, 0, mcm.LogicalCallContext, mcm));
            }
            if (methodBase == _getHashCodeMethod)
            {
                int hashCode = this.GetHashCode();
                IMethodCallMessage message3 = (IMethodCallMessage)reqMsg;
                return(new ReturnMessage(hashCode, null, 0, message3.LogicalCallContext, message3));
            }
            if (methodBase == _isInstanceOfTypeMethod)
            {
                IMethodCallMessage message4 = (IMethodCallMessage)reqMsg;
                Type inArg = (Type)message4.GetInArg(0);
                return(new ReturnMessage(inArg.IsInstanceOfType(this.ProxiedType), null, 0, message4.LogicalCallContext, message4));
            }
            MemberInfo m = ReflectionCache.ConvertToClassMI(this.ProxiedType, mi);

            try
            {
                int num2;
                if ((this._fUseIntfDispatch || (((num2 = ServicedComponentInfo.MICachedLookup(m)) & 4) != 0)) || ((num2 & 8) != 0))
                {
                    MemberInfo info3 = ReflectionCache.ConvertToInterfaceMI(mi);
                    if (info3 == null)
                    {
                        throw new ServicedComponentException(Resource.FormatString("ServicedComponentException_SecurityMapping"));
                    }
                    MethodCallMessageWrapperEx ex = new MethodCallMessageWrapperEx((IMethodCallMessage)reqMsg, (MethodBase)info3);
                    message = RemotingServices.ExecuteMessage((MarshalByRefObject)this._server, ex);
                }
                else
                {
                    string          str2;
                    bool            flag     = (num2 & 2) != 0;
                    string          s        = ComponentServices.ConvertToString(reqMsg);
                    IRemoteDispatch dispatch = (IRemoteDispatch)this._server;
                    if (flag)
                    {
                        str2 = dispatch.RemoteDispatchAutoDone(s);
                    }
                    else
                    {
                        str2 = dispatch.RemoteDispatchNotAutoDone(s);
                    }
                    message = ComponentServices.ConvertToReturnMessage(str2, reqMsg);
                }
            }
            catch (COMException exception)
            {
                if ((exception.ErrorCode != -2147164158) && (exception.ErrorCode != -2147164157))
                {
                    throw;
                }
                if (!this.IsDisposeRequest(reqMsg))
                {
                    throw;
                }
                IMethodCallMessage message5 = reqMsg as IMethodCallMessage;
                message = new ReturnMessage(null, null, 0, message5.LogicalCallContext, message5);
            }
            if (this.IsDisposeRequest(reqMsg))
            {
                this.Dispose(true);
            }
            return(message);
        }
        public void SerializeRequest(IMethodCallMessage message, ITransportHeaders requestHeaders, Stream requestStream)
        {
            var writer = new BinaryWriter(requestStream, Encoding.UTF8);

            // method info
            writer.Write(message.MethodName);

            // arguments count
            writer.Write((byte)message.InArgCount);

            // arguments list
            for (int i = 0; i < message.InArgCount; ++i)
            {
                SerializeObject(writer, message.GetInArg(i));
            }
        }
Exemple #18
0
        public override IMessage Invoke(IMessage myIMessage)
        {
            Console.WriteLine("**********************************************************************************");

            IDictionary myIDictionary = myIMessage.Properties;

            // Set the '__Uri' property of 'IMessage' to 'URI' property of 'ObjRef'.
            myIDictionary["__Uri"] = stringUri;
            IDictionaryEnumerator myIDictionaryEnumerator = (IDictionaryEnumerator)myIDictionary.GetEnumerator();

            while (myIDictionaryEnumerator.MoveNext())
            {
                Object myKey     = myIDictionaryEnumerator.Key;
                String myKeyName = myKey.ToString();
                Object myValue   = myIDictionaryEnumerator.Value;

                Console.WriteLine("\t{0} : {1}", myKeyName, myIDictionaryEnumerator.Value);
                if (myKeyName == "__Args")
                {
                    Object[] objs = (Object[])myValue;
                    for (int aIndex = 0; aIndex < objs.Length; aIndex++)
                    {
                        Console.WriteLine("\t\targ: {0} myValue: {1}", aIndex, objs[aIndex]);
                    }
                }

                if ((myKeyName == "__MethodSignature") && (null != myValue))
                {
                    Object[] objs = (Object[])myValue;
                    for (int aIndex = 0; aIndex < objs.Length; aIndex++)
                    {
                        Console.WriteLine("\t\targ: {0} myValue: {1}", aIndex, objs[aIndex]);
                    }
                }
            }

            Console.WriteLine("**********************************************************************************");

            Console.WriteLine("ChannelServices.SyncDispatchMessage");
            IMessage myReturnMessage = ChannelServices.SyncDispatchMessage(myIMessage);

            // Push return value and OUT parameters back onto stack.
            IMethodReturnMessage myMethodReturnMessage = (IMethodReturnMessage)myReturnMessage;

            Console.WriteLine("IMethodReturnMessage.ReturnValue: {0}", myMethodReturnMessage.ReturnValue);

            Console.WriteLine("**********************************************************************************");
            IMethodCallMessage   myIMethodCallMessage   = (IMethodCallMessage)myIMessage;
            IMethodReturnMessage myIMethodReturnMessage = RemotingServices.ExecuteMessage(myMarshalByRefObject, myIMethodCallMessage);

            Console.WriteLine("Method name : " + myIMethodReturnMessage.MethodName);
            Console.WriteLine("The return value is : " + myIMethodReturnMessage.ReturnValue);

            Console.WriteLine("**********************************************************************************");

            int myArgOutCount = myIMethodReturnMessage.OutArgCount;

            Console.WriteLine("The number of 'ref', 'out' parameters are : " + myIMethodReturnMessage.OutArgCount);
            // Gets name and values of 'ref' and 'out' parameters.
            for (int i = 0; i < myArgOutCount; i++)
            {
                Console.WriteLine("Name of argument {0} is '{1}'.", i, myIMethodReturnMessage.GetOutArgName(i));
                Console.WriteLine("Value of argument {0} is '{1}'.", i, myIMethodReturnMessage.GetOutArg(i));
            }
            Console.WriteLine();
            object[] myObjectArray = myIMethodReturnMessage.OutArgs;
            for (int i = 0; i < myObjectArray.Length; i++)
            {
                Console.WriteLine("Value of argument {0} is '{1}' in OutArgs", i, myObjectArray[i]);
            }

            Console.WriteLine("**********************************************************************************");
            Console.WriteLine("Message is of type 'IMethodCallMessage'.");
            Console.WriteLine("InArgCount is  : " + myIMethodCallMessage.InArgCount);
            foreach (object arg in myIMethodCallMessage.InArgs)
            {
                Console.WriteLine("InArgs is : " + arg);
            }
            for (int i = 0; i < myIMethodCallMessage.InArgCount; i++)
            {
                Console.WriteLine("GetArgName(" + i + ") is : " + myIMethodCallMessage.GetArgName(i));
                Console.WriteLine("GetInArg(" + i + ") is : " + myIMethodCallMessage.GetInArg(i));
            }
            Console.WriteLine("**********************************************************************************");
            var message = new ReturnMessage(5, null, 0, null, (IMethodCallMessage)myIMessage);

            return(message);
        }
Exemple #19
0
 public virtual Object GetInArg(int argNum)
 {
     return(mcm.GetInArg(argNum));
 }