// used by the server when an exception is thrown
        // by the called function
        internal ServerFault CreateServerFault(Exception e)
        {
            // it's really strange here
            // a ServerFault object has a private System.Exception member called *exception*
            // (have a look at a MS Soap message when an exception occurs on the server)
            // but there is not public .ctor with an Exception as parameter...????....
            // (maybe an internal one). So I searched another way...
            ServerFault sf = (ServerFault)FormatterServices.GetUninitializedObject(typeof(ServerFault));

            MemberInfo[] mi = FormatterServices.GetSerializableMembers(typeof(ServerFault), new StreamingContext(StreamingContextStates.All));

            FieldInfo fi;

            object[] mv = new object[mi.Length];
            for (int i = 0; i < mi.Length; i++)
            {
                fi = mi[i] as FieldInfo;
                if (fi != null && fi.FieldType == typeof(Exception))
                {
                    mv[i] = e;
                }
            }
            sf = (ServerFault)FormatterServices.PopulateObjectMembers(sf, mi, mv);

            return(sf);
        }
예제 #2
0
        private void TransmitFaultMessage(ServerFault serverFault)
        {
            MultiPartMessage temp = new MultiPartMessage(new MemoryStream(4096));

            _exceptionSerializer.Serialize(temp.Data, serverFault);

            AppendEndOfFile(temp);

            TraceMessageData("Sending data: ", temp);

            SourceMessage.Metadata.Copy("ReceiveUri", temp.Metadata);
            temp.Metadata.Write("Loopback", true);

            if (Session != null)
            {
                Session.LastResponseMessage = temp;
            }

            try
            {
                MessageEngine.Instance.TransmitMessage(temp);
            }
            catch (AdapterException)
            {
            }
        }
예제 #3
0
        public ImageFileData GetImageByName(string request_file_name)
        {
            Log("GetImageByName");
            try
            {
                if (string.IsNullOrEmpty(request_file_name))
                {
                    throw new ArgumentException("Invalid requested file name!", request_file_name);
                }

                IEnumerable <FileInfo> allImageFilesList = GetAllImageFiles();
                FileInfo requestedImageFile = null;
                requestedImageFile = allImageFilesList.SingleOrDefault(f => f.Name == request_file_name);
                if (requestedImageFile == null)
                {
                    throw new ArgumentException("File that you has requested doesn't exist!", request_file_name);
                }

                ImageFileData imageFileData = new ImageFileData()
                {
                    FileName = requestedImageFile.Name, LastDateModified = requestedImageFile.LastWriteTime
                };
                byte[] imageBytes = File.ReadAllBytes(requestedImageFile.FullName);
                imageFileData.ImageData = imageBytes;
                return(imageFileData);
            }
            catch (Exception e)
            {
                ServerFault fault = new ServerFault();
                fault.FriendlyDiscription = "Some problems just has been occured on service host!";
                fault.Discription         = e.Message;
                throw new FaultException <ServerFault>(fault, new FaultReason(fault.Discription));
            }
        }
예제 #4
0
        public IEnumerable <ImageFileData> GetAllImagesList(bool withFilesData)
        {
            Log("GetAllImagesList");
            List <ImageFileData> images_collection = new List <ImageFileData>();

            try
            {
                foreach (FileInfo fileInfo in GetAllImageFiles())
                {
                    ImageFileData imageFileData = new ImageFileData()
                    {
                        FileName = fileInfo.Name, LastDateModified = fileInfo.LastWriteTime
                    };
                    byte[] imageBytes = null;
                    if (withFilesData)
                    {
                        imageBytes = File.ReadAllBytes(fileInfo.FullName);
                    }
                    imageFileData.ImageData = imageBytes;
                    images_collection.Add(imageFileData);
                }
            }
            catch (Exception e)
            {
                ServerFault fault = new ServerFault();
                fault.FriendlyDiscription = "Some problems just has been occured on server!";
                fault.Discription         = e.Message;
                throw new FaultException <ServerFault>(fault, new FaultReason(fault.Discription));
            }

            AddUpdateToSessionTable(images_collection.Count);
            return(images_collection);
        }
        internal IMessage FormatFault(SoapFault fault, IMethodCallMessage mcm)
        {
            ServerFault sf = fault.Detail as ServerFault;
            Exception   e  = null;

            if (sf != null)
            {
                if (_serverFaultExceptionField != null)
                {
                    e = (Exception)_serverFaultExceptionField.GetValue(sf);
                }
#if TARGET_JVM
                if (e == null && sf.ExceptionType != null)
                {
                    try
                    {
                        Type te = Type.GetType(sf.ExceptionType);
                        if (te != null)
                        {
                            ConstructorInfo ce = te.GetConstructor(
                                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance,
                                null, new Type[] { typeof(string) }, null);

                            if (ce != null)
                            {
                                e = (Exception)ce.Invoke(new object[] { sf.ExceptionMessage });
                            }
                            else
                            {
                                e = (Exception)Activator.CreateInstance(te);
                            }
                        }
                    }
                    catch
                    {
                        e = null;
                    }
                }
#endif
            }
            if (e == null)
            {
                e = new RemotingException(fault.FaultString);
            }

            return(new ReturnMessage((System.Exception)e, mcm));
        }
예제 #6
0
        private void CheckAndThrowException(MemoryStream messageData)
        {
            byte[] temp = new byte[64];

            messageData.Seek(0, SeekOrigin.Begin);
            messageData.Read(temp, 0, 64);

            if (Encoding.UTF8.GetString(temp, 0, 64).Contains("<ServerFault"))
            {
                messageData.Seek(0, SeekOrigin.Begin);

                XmlSerializer serializer  = GetSerializer(typeof(ServerFault));
                ServerFault   serverFault = (ServerFault)serializer.Deserialize(messageData);

                throw new ServerFaultException(serverFault.Message, serverFault.Type, serverFault.ErrorCode, serverFault.ServerStackTrace);
            }
        }
예제 #7
0
        private int GetImagesCount()
        {
            int imagesCount = 0;

            try
            {
                imagesCount = (new List <FileInfo>(GetAllImageFiles())).Count;
            }
            catch (Exception e)
            {
                ServerFault fault = new ServerFault();
                fault.FriendlyDiscription = "Some problems just has been occured on server!";
                fault.Discription         = e.Message;
                throw new FaultException <ServerFault>(fault, new FaultReason(fault.Discription));
            }
            return(imagesCount);
        }
예제 #8
0
        internal IMessage FormatFault(SoapFault fault, IMethodCallMessage mcm)
        {
            ServerFault sf = fault.Detail as ServerFault;
            Exception   e  = null;

            if (sf != null)
            {
                if (_serverFaultExceptionField != null)
                {
                    e = (Exception)_serverFaultExceptionField.GetValue(sf);
                }
            }
            if (e == null)
            {
                e = new RemotingException(fault.FaultString);
            }

            return(new ReturnMessage((System.Exception)e, mcm));
        }
예제 #9
0
        public void UploadImage(ImageFileData uploading_image)
        {
            Log("UploadImage");
            try
            {
                if (string.IsNullOrEmpty(uploading_image.FileName))
                {
                    throw new ArgumentException("Invalid upldoading file name", uploading_image.FileName);
                }

                if (uploading_image.ImageData == null || uploading_image.ImageData.Length == 0)
                {
                    throw new ArgumentException("Uploaded file-data is empty!");
                }

                string newImageFileName = uploading_image.FileName;
                string uploadFolder     = ConfigurationManager.AppSettings["UploadFolder"];
                string newImageFilePath = Path.Combine(uploadFolder, newImageFileName);

                try
                {
                    using (Stream targetStream = new FileStream(newImageFilePath, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        targetStream.Write(uploading_image.ImageData, 0, uploading_image.ImageData.Length);
                    }
                }
                catch (IOException)
                {
                    throw new IOException("Error writing new file or overwriting existed file");
                }
            }
            catch (Exception e)
            {
                ServerFault fault = new ServerFault();
                fault.FriendlyDiscription = "Some problems just has been occured on service host!";
                fault.Discription         = e.Message;
                throw new FaultException <ServerFault>(fault, new FaultReason(fault.Discription));
            }
        }
예제 #10
0
        public virtual void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }

            if ((obj != null) && (obj != _rootObj))
            {
                (new MessageSurrogate(_ss)).GetObjectData(obj, info, context);
            }
            else
            {
                IMethodReturnMessage msg = obj as IMethodReturnMessage;
                if (null != msg)
                {
                    if (msg.Exception == null)
                    {
                        String responseElementName;
                        String responseElementNS;
                        String returnElementName;

                        // obtain response element name namespace
                        MethodBase          mb   = msg.MethodBase;
                        SoapMethodAttribute attr = (SoapMethodAttribute)InternalRemotingServices.GetCachedSoapAttribute(mb);
                        responseElementName = attr.ResponseXmlElementName;
                        responseElementNS   = attr.ResponseXmlNamespace;
                        returnElementName   = attr.ReturnXmlElementName;

                        ArgMapper mapper = new ArgMapper(msg, true /*fOut*/);
                        Object[]  args   = mapper.Args;
                        info.FullTypeName = responseElementName;
                        info.AssemblyName = responseElementNS;
                        Type retType = ((MethodInfo)mb).ReturnType;
                        if (!((retType == null) || (retType == _voidType)))
                        {
                            info.AddValue(returnElementName, msg.ReturnValue, retType);
                        }
                        if (args != null)
                        {
                            Type[] types = mapper.ArgTypes;
                            for (int i = 0; i < args.Length; i++)
                            {
                                String name;
                                name = mapper.GetArgName(i);
                                if ((name == null) || (name.Length == 0))
                                {
                                    name = "__param" + i;
                                }
                                info.AddValue(
                                    name,
                                    args[i],
                                    types[i].IsByRef?
                                    types[i].GetElementType():types[i]);
                            }
                        }
                    }
                    else
                    {
                        Object oClientIsClr = CallContext.GetData("__ClientIsClr");
                        bool   bClientIsClr = (oClientIsClr == null) ? true:(bool)oClientIsClr;
                        info.FullTypeName = "FormatterWrapper";
                        info.AssemblyName = DefaultFakeRecordAssemblyName;

                        Exception     ex = msg.Exception;
                        StringBuilder sb = new StringBuilder();
                        bool          bMustUnderstandError = false;
                        while (ex != null)
                        {
                            if (ex.Message.StartsWith("MustUnderstand"))
                            {
                                bMustUnderstandError = true;
                            }

                            sb.Append(" **** ");
                            sb.Append(ex.GetType().FullName);
                            sb.Append(" - ");
                            sb.Append(ex.Message);

                            ex = ex.InnerException;
                        }

                        ServerFault serverFault = null;
                        if (bClientIsClr)
                        {
                            serverFault = new ServerFault(msg.Exception); // Clr is the Client use full exception
                        }
                        else
                        {
                            serverFault = new ServerFault(msg.Exception.GetType().AssemblyQualifiedName, sb.ToString(), msg.Exception.StackTrace);
                        }

                        String faultType = "Server";
                        if (bMustUnderstandError)
                        {
                            faultType = "MustUnderstand";
                        }

                        SoapFault soapFault = new SoapFault(faultType, sb.ToString(), null, serverFault);
                        info.AddValue("__WrappedObject", soapFault, _soapFaultType);
                    }
                }
                else
                {
                    IMethodCallMessage mcm = (IMethodCallMessage)obj;

                    // obtain method namespace
                    MethodBase mb = mcm.MethodBase;
                    String     methodElementNS = SoapServices.GetXmlNamespaceForMethodCall(mb);

                    Object[] args  = mcm.InArgs;
                    String[] names = GetInArgNames(mcm, args.Length);
                    Type[]   sig   = (Type[])mcm.MethodSignature;
                    info.FullTypeName = mcm.MethodName;
                    info.AssemblyName = methodElementNS;
                    RemotingMethodCachedData cache = (RemotingMethodCachedData)InternalRemotingServices.GetReflectionCachedData(mb);
                    int[] requestArgMap            = cache.MarshalRequestArgMap;


                    BCLDebug.Assert(
                        args != null || sig.Length == args.Length,
                        "Signature mismatch");

                    for (int i = 0; i < args.Length; i++)
                    {
                        String paramName = null;
                        if ((names[i] == null) || (names[i].Length == 0))
                        {
                            paramName = "__param" + i;
                        }
                        else
                        {
                            paramName = names[i];
                        }

                        int  sigPosition = requestArgMap[i];
                        Type argType     = null;

                        if (sig[sigPosition].IsByRef)
                        {
                            argType = sig[sigPosition].GetElementType();
                        }
                        else
                        {
                            argType = sig[sigPosition];
                        }

                        info.AddValue(paramName, args[i], argType);
                    }
                }
            }
        } // GetObjectData
        private async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger <ExceptionHandlingMiddleware> logger)
        {
            var statusCode = default(HttpStatusCode);

            object message = null;

            switch (exception)
            {
            case SecurityException security:
                statusCode = HttpStatusCode.Forbidden;

                var securityex = new ServerFault();
                securityex.message = "You shall not pass!";

                message = securityex;

                logger.LogWarning($"EXCEPTION HANDLING 403 | { security.Message }");
                break;

            case ArgumentNullException argumentNull:
                statusCode = HttpStatusCode.NotFound;

                var argumentex = new ServerFault();
                argumentex.message = "These aren't the droids you're looking for...";;

                message = argumentex;

                logger.LogInformation($"EXCEPTION HANDLING 404 | { argumentNull.Message }");
                break;

            case ValidationException validation:
                statusCode = HttpStatusCode.BadRequest;

                var client = new ClientFault();
                client.message = "Something is not right...";

                foreach (var erro in validation.Errors)
                {
                    var fault = new Fault()
                    {
                        code     = erro.ErrorCode,
                        error    = erro.ErrorMessage,
                        property = erro.PropertyName,
                        value    = erro.AttemptedValue == null ? "null" : erro.AttemptedValue.ToString()
                    };

                    client.faults.Add(fault);
                }

                message = client;

                logger.LogInformation($"EXCEPTION HANDLING 400 | { message }");
                break;

            case ArgumentOutOfRangeException argumentOutOfRange:
            case TaskCanceledException taskCanceled:
            default:
                statusCode = HttpStatusCode.InternalServerError;

                var defaultex = new ServerFault();
                defaultex.message = "Something is not right... Please, call one of our monkeys at [email protected]";

#if (DEBUG)
                defaultex.message = $"Exception: {exception.Message} - Inner: {exception.InnerException?.Message} - Stacktrace: {exception.StackTrace}";
#endif

                message = defaultex;

                logger.LogError($"EXCEPTION HANDLING 500 | { exception }");
                break;
            }

            var result = JsonConvert.SerializeObject(message);

            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.StatusCode  = (int)statusCode;

            await context.Response.WriteAsync(result, Encoding.UTF8);
        }
예제 #12
0
        protected override void InternalInvoke(MultiPartMessage msg)
        {
            Session = null;
            bool hasLock = false;

            try
            {
                TraceMessageData("Data received: ", msg);

                SourceMessage = msg;
                Session       = GetSession(msg);

                if (Session != null)
                {
                    lock (Session.SyncLock)
                    {
                        Session.LastActivityTime = DateTime.Now;
                    }

                    Session.AbortEvent.Set();

                    Monitor.TryEnter(Session, _config.PendingOperationsTimeout, ref hasLock);

                    if (!hasLock)
                    {
                        if ((MessageEngine.Instance.Tracing.Switch.Level & SourceLevels.Verbose) == SourceLevels.Verbose)
                        {
                            MessageEngine.Instance.Tracing.TraceData(TraceEventType.Verbose, 0, "Application busy, request aborted.");
                        }

                        return;
                    }

                    CheckAndThrowException();

                    if (IsDuplicate(SourceMessage))
                    {
                        if ((MessageEngine.Instance.Tracing.Switch.Level & SourceLevels.Verbose) == SourceLevels.Verbose)
                        {
                            MessageEngine.Instance.Tracing.TraceData(TraceEventType.Verbose, 0, "Duplicate message detected, retransmitting last response...");
                        }

                        msg.Metadata.Copy("ReceiveUri", Session.LastResponseMessage.Metadata);
                        Session.LastResponseMessage.Metadata.Write("Loopback", true);

                        try
                        {
                            MessageEngine.Instance.TransmitMessage(Session.LastResponseMessage);
                        }
                        catch (AdapterException)
                        {
                        }

                        return;
                    }

                    if (Session.LastRequestMessage != null)
                    {
                        Session.LastRequestMessage.Dispose();
                    }

                    if (Session.LastResponseMessage != null)
                    {
                        Session.LastResponseMessage.Dispose();
                    }

                    Session.LastRequestMessage = msg;
                }

                msg.Data.Seek(0, SeekOrigin.Begin);

                TRequest requestMessage = (TRequest)_requestSerializer.Deserialize(msg.Data);

                Invoke(requestMessage);
            }
            catch (Exception ex)
            {
                ServerFault serverFault = new ServerFault();
                serverFault.Type    = ex.GetType().ToString();
                serverFault.Message = ex.Message;

                if (ex.Data.Contains("ErrorCode"))
                {
                    serverFault.ErrorCode = ex.Data["ErrorCode"].ToString();
                }

                serverFault.ServerStackTrace = ex.ToString();

                TransmitFaultMessage(serverFault);

                throw;
            }
            finally
            {
                if (hasLock)
                {
                    Monitor.Exit(Session);
                }
            }
        }
예제 #13
0
        internal void SetObjectFromSoapData(SerializationInfo info)
        {
            Hashtable keyToNamespaceTable = (Hashtable)info.GetValue("__keyToNamespaceTable", typeof(Hashtable));
            ArrayList list  = (ArrayList)info.GetValue("__paramNameList", typeof(ArrayList));
            SoapFault fault = (SoapFault)info.GetValue("__fault", typeof(SoapFault));

            if (fault != null)
            {
                ServerFault detail = fault.Detail as ServerFault;
                if (detail != null)
                {
                    if (detail.Exception != null)
                    {
                        this.fault = detail.Exception;
                    }
                    else
                    {
                        Type type = Type.GetType(detail.ExceptionType, false, false);
                        if (type == null)
                        {
                            StringBuilder builder = new StringBuilder();
                            builder.Append("\nException Type: ");
                            builder.Append(detail.ExceptionType);
                            builder.Append("\n");
                            builder.Append("Exception Message: ");
                            builder.Append(detail.ExceptionMessage);
                            builder.Append("\n");
                            builder.Append(detail.StackTrace);
                            this.fault = new ServerException(builder.ToString());
                        }
                        else
                        {
                            object[] args = new object[] { detail.ExceptionMessage };
                            this.fault = (System.Exception)Activator.CreateInstance(type, BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, args, null, null);
                        }
                    }
                }
                else if (((fault.Detail != null) && (fault.Detail.GetType() == typeof(string))) && (((string)fault.Detail).Length != 0))
                {
                    this.fault = new ServerException((string)fault.Detail);
                }
                else
                {
                    this.fault = new ServerException(fault.FaultString);
                }
            }
            else
            {
                MethodInfo mI  = this.MI as MethodInfo;
                int        num = 0;
                if (mI != null)
                {
                    Type returnType = mI.ReturnType;
                    if (returnType != typeof(void))
                    {
                        num++;
                        object obj2 = info.GetValue((string)list[0], typeof(object));
                        if (obj2 is string)
                        {
                            this.retVal = Message.SoapCoerceArg(obj2, returnType, keyToNamespaceTable);
                        }
                        else
                        {
                            this.retVal = obj2;
                        }
                    }
                }
                ParameterInfo[] parameters = this._methodCache.Parameters;
                object          obj3       = (this.InternalProperties == null) ? null : this.InternalProperties["__UnorderedParams"];
                if (((obj3 != null) && (obj3 is bool)) && ((bool)obj3))
                {
                    for (int i = num; i < list.Count; i++)
                    {
                        string name  = (string)list[i];
                        int    index = -1;
                        for (int j = 0; j < parameters.Length; j++)
                        {
                            if (name.Equals(parameters[j].Name))
                            {
                                index = parameters[j].Position;
                            }
                        }
                        if (index == -1)
                        {
                            if (!name.StartsWith("__param", StringComparison.Ordinal))
                            {
                                throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadSerialization"));
                            }
                            index = int.Parse(name.Substring(7), CultureInfo.InvariantCulture);
                        }
                        if (index >= this.argCount)
                        {
                            throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadSerialization"));
                        }
                        if (this.outArgs == null)
                        {
                            this.outArgs = new object[this.argCount];
                        }
                        this.outArgs[index] = Message.SoapCoerceArg(info.GetValue(name, typeof(object)), parameters[index].ParameterType, keyToNamespaceTable);
                    }
                }
                else
                {
                    if (this.argMapper == null)
                    {
                        this.argMapper = new ArgMapper(this, true);
                    }
                    for (int k = num; k < list.Count; k++)
                    {
                        string str2 = (string)list[k];
                        if (this.outArgs == null)
                        {
                            this.outArgs = new object[this.argCount];
                        }
                        int num6 = this.argMapper.Map[k - num];
                        this.outArgs[num6] = Message.SoapCoerceArg(info.GetValue(str2, typeof(object)), parameters[num6].ParameterType, keyToNamespaceTable);
                    }
                }
            }
        }
        // used by the server
        internal object BuildSoapMessageFromMethodResponse(IMethodReturnMessage mrm, out ITransportHeaders responseHeaders)
        {
            responseHeaders = new TransportHeaders();

            if (mrm.Exception == null)
            {
                // *normal* function return

                SoapMessage soapMessage = new SoapMessage();

                // fill the transport headers
                responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\"";

                // build the SoapMessage
                ArrayList paramNames  = new ArrayList();
                ArrayList paramValues = new ArrayList();
                ArrayList paramTypes  = new ArrayList();
                soapMessage.MethodName = mrm.MethodName + "Response";

                Type retType = ((MethodInfo)mrm.MethodBase).ReturnType;

                if (retType != typeof(void))
                {
                    paramNames.Add("return");
                    paramValues.Add(mrm.ReturnValue);
                    if (mrm.ReturnValue != null)
                    {
                        paramTypes.Add(mrm.ReturnValue.GetType());
                    }
                    else
                    {
                        paramTypes.Add(retType);
                    }
                }

                for (int i = 0; i < mrm.OutArgCount; i++)
                {
                    paramNames.Add(mrm.GetOutArgName(i));
                    paramValues.Add(mrm.GetOutArg(i));
                    if (mrm.GetOutArg(i) != null)
                    {
                        paramTypes.Add(mrm.GetOutArg(i).GetType());
                    }
                }
                soapMessage.ParamNames   = (string[])paramNames.ToArray(typeof(string));
                soapMessage.ParamValues  = (object[])paramValues.ToArray(typeof(object));
                soapMessage.ParamTypes   = (Type[])paramTypes.ToArray(typeof(Type));
                soapMessage.XmlNameSpace = _xmlNamespace;
                soapMessage.Headers      = BuildMessageHeaders(mrm);
                return(soapMessage);
            }
            else
            {
                // an Exception was thrown while executing the function
                responseHeaders["__HttpStatusCode"]   = "500";
                responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                // fill the transport headers
                responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\"";
                ServerFault serverFault = CreateServerFault(mrm.Exception);
                return(new SoapFault("Server", String.Format(" **** {0} - {1}", mrm.Exception.GetType().ToString(), mrm.Exception.Message), null, serverFault));
            }
        }
 public virtual void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
 {
     if (info == null)
     {
         throw new ArgumentNullException("info");
     }
     if ((obj != null) && (obj != this._rootObj))
     {
         new MessageSurrogate(this._ss).GetObjectData(obj, info, context);
     }
     else
     {
         IMethodReturnMessage mm = obj as IMethodReturnMessage;
         if (mm != null)
         {
             if (mm.Exception != null)
             {
                 object data = CallContext.GetData("__ClientIsClr");
                 bool   flag = (data == null) || ((bool)data);
                 info.FullTypeName = "FormatterWrapper";
                 info.AssemblyName = this.DefaultFakeRecordAssemblyName;
                 Exception     innerException = mm.Exception;
                 StringBuilder builder        = new StringBuilder();
                 bool          flag2          = false;
                 while (innerException != null)
                 {
                     if (innerException.Message.StartsWith("MustUnderstand", StringComparison.Ordinal))
                     {
                         flag2 = true;
                     }
                     builder.Append(" **** ");
                     builder.Append(innerException.GetType().FullName);
                     builder.Append(" - ");
                     builder.Append(innerException.Message);
                     innerException = innerException.InnerException;
                 }
                 ServerFault serverFault = null;
                 if (flag)
                 {
                     serverFault = new ServerFault(mm.Exception);
                 }
                 else
                 {
                     serverFault = new ServerFault(mm.Exception.GetType().AssemblyQualifiedName, builder.ToString(), mm.Exception.StackTrace);
                 }
                 string faultCode = "Server";
                 if (flag2)
                 {
                     faultCode = "MustUnderstand";
                 }
                 SoapFault fault2 = new SoapFault(faultCode, builder.ToString(), null, serverFault);
                 info.AddValue("__WrappedObject", fault2, _soapFaultType);
             }
             else
             {
                 MethodBase          methodBase          = mm.MethodBase;
                 SoapMethodAttribute cachedSoapAttribute = (SoapMethodAttribute)InternalRemotingServices.GetCachedSoapAttribute(methodBase);
                 string    responseXmlElementName        = cachedSoapAttribute.ResponseXmlElementName;
                 string    responseXmlNamespace          = cachedSoapAttribute.ResponseXmlNamespace;
                 string    returnXmlElementName          = cachedSoapAttribute.ReturnXmlElementName;
                 ArgMapper mapper = new ArgMapper(mm, true);
                 object[]  args   = mapper.Args;
                 info.FullTypeName = responseXmlElementName;
                 info.AssemblyName = responseXmlNamespace;
                 Type returnType = ((MethodInfo)methodBase).ReturnType;
                 if ((returnType != null) && !(returnType == _voidType))
                 {
                     info.AddValue(returnXmlElementName, mm.ReturnValue, returnType);
                 }
                 if (args != null)
                 {
                     Type[] argTypes = mapper.ArgTypes;
                     for (int i = 0; i < args.Length; i++)
                     {
                         string argName = mapper.GetArgName(i);
                         if ((argName == null) || (argName.Length == 0))
                         {
                             argName = "__param" + i;
                         }
                         info.AddValue(argName, args[i], argTypes[i].IsByRef ? argTypes[i].GetElementType() : argTypes[i]);
                     }
                 }
             }
         }
         else
         {
             IMethodCallMessage m  = (IMethodCallMessage)obj;
             MethodBase         mb = m.MethodBase;
             string             xmlNamespaceForMethodCall = SoapServices.GetXmlNamespaceForMethodCall(mb);
             object[]           inArgs          = m.InArgs;
             string[]           inArgNames      = this.GetInArgNames(m, inArgs.Length);
             Type[]             methodSignature = (Type[])m.MethodSignature;
             info.FullTypeName = m.MethodName;
             info.AssemblyName = xmlNamespaceForMethodCall;
             int[] marshalRequestArgMap = InternalRemotingServices.GetReflectionCachedData(mb).MarshalRequestArgMap;
             for (int j = 0; j < inArgs.Length; j++)
             {
                 string name = null;
                 if ((inArgNames[j] == null) || (inArgNames[j].Length == 0))
                 {
                     name = "__param" + j;
                 }
                 else
                 {
                     name = inArgNames[j];
                 }
                 int  index = marshalRequestArgMap[j];
                 Type type  = null;
                 if (methodSignature[index].IsByRef)
                 {
                     type = methodSignature[index].GetElementType();
                 }
                 else
                 {
                     type = methodSignature[index];
                 }
                 info.AddValue(name, inArgs[j], type);
             }
         }
     }
 }
예제 #16
0
        internal void SetObjectFromSoapData(SerializationInfo info)
        {
            Hashtable keyToNamespaceTable = (Hashtable)info.GetValue("__keyToNamespaceTable", typeof(Hashtable));
            ArrayList arrayList           = (ArrayList)info.GetValue("__paramNameList", typeof(ArrayList));
            SoapFault soapFault           = (SoapFault)info.GetValue("__fault", typeof(SoapFault));

            if (soapFault != null)
            {
                ServerFault serverFault = soapFault.Detail as ServerFault;
                if (serverFault != null)
                {
                    if (serverFault.Exception != null)
                    {
                        this.fault = serverFault.Exception;
                    }
                    else
                    {
                        Type type = Type.GetType(serverFault.ExceptionType, false, false);
                        if (type == (Type)null)
                        {
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.Append("\nException Type: ");
                            stringBuilder.Append(serverFault.ExceptionType);
                            stringBuilder.Append("\n");
                            stringBuilder.Append("Exception Message: ");
                            stringBuilder.Append(serverFault.ExceptionMessage);
                            stringBuilder.Append("\n");
                            stringBuilder.Append(serverFault.StackTrace);
                            this.fault = (Exception) new ServerException(stringBuilder.ToString());
                        }
                        else
                        {
                            object[] args = new object[1] {
                                (object)serverFault.ExceptionMessage
                            };
                            this.fault = (Exception)Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, (Binder)null, args, (CultureInfo)null, (object[])null);
                        }
                    }
                }
                else if (soapFault.Detail != null && soapFault.Detail.GetType() == typeof(string) && ((string)soapFault.Detail).Length != 0)
                {
                    this.fault = (Exception) new ServerException((string)soapFault.Detail);
                }
                else
                {
                    this.fault = (Exception) new ServerException(soapFault.FaultString);
                }
            }
            else
            {
                MethodInfo methodInfo = this.MI as MethodInfo;
                int        num        = 0;
                if (methodInfo != (MethodInfo)null)
                {
                    Type returnType = methodInfo.ReturnType;
                    if (returnType != typeof(void))
                    {
                        ++num;
                        object obj = info.GetValue((string)arrayList[0], typeof(object));
                        this.retVal = !(obj is string) ? obj : Message.SoapCoerceArg(obj, returnType, keyToNamespaceTable);
                    }
                }
                ParameterInfo[] parameters = this._methodCache.Parameters;
                object          obj1       = this.InternalProperties == null ? (object)null : this.InternalProperties[(object)"__UnorderedParams"];
                if (obj1 != null && obj1 is bool && (bool)obj1)
                {
                    for (int index1 = num; index1 < arrayList.Count; ++index1)
                    {
                        string name   = (string)arrayList[index1];
                        int    index2 = -1;
                        for (int index3 = 0; index3 < parameters.Length; ++index3)
                        {
                            if (name.Equals(parameters[index3].Name))
                            {
                                index2 = parameters[index3].Position;
                            }
                        }
                        if (index2 == -1)
                        {
                            if (!name.StartsWith("__param", StringComparison.Ordinal))
                            {
                                throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadSerialization"));
                            }
                            index2 = int.Parse(name.Substring(7), (IFormatProvider)CultureInfo.InvariantCulture);
                        }
                        if (index2 >= this.argCount)
                        {
                            throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadSerialization"));
                        }
                        if (this.outArgs == null)
                        {
                            this.outArgs = new object[this.argCount];
                        }
                        this.outArgs[index2] = Message.SoapCoerceArg(info.GetValue(name, typeof(object)), parameters[index2].ParameterType, keyToNamespaceTable);
                    }
                }
                else
                {
                    if (this.argMapper == null)
                    {
                        this.argMapper = new ArgMapper((IMethodMessage)this, true);
                    }
                    for (int index1 = num; index1 < arrayList.Count; ++index1)
                    {
                        string name = (string)arrayList[index1];
                        if (this.outArgs == null)
                        {
                            this.outArgs = new object[this.argCount];
                        }
                        int index2 = this.argMapper.Map[index1 - num];
                        this.outArgs[index2] = Message.SoapCoerceArg(info.GetValue(name, typeof(object)), parameters[index2].ParameterType, keyToNamespaceTable);
                    }
                }
            }
        }
 public SoapFault(string faultCode, string faultString, string faultActor, ServerFault serverFault)
 {
 }
        private async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger <ExceptionHandlingMiddleware> logger)
        {
            var statusCode = default(HttpStatusCode);

            object message = null;

            switch (exception)
            {
            case SecurityException security:
                logger.LogWarning($"EXCEPTION HANDLING 403 | { security.Message }");

                statusCode = HttpStatusCode.Forbidden;

                message = new ServerFault
                {
                    Message = "You shall not pass!"
                };
                break;

            case ValidationException validation:
                logger.LogDebug($"EXCEPTION HANDLING 400 | { message }");

                statusCode = HttpStatusCode.BadRequest;

                message = new ClientFault
                {
                    Message = "Your request contains bad syntax or cannot be fulfiled",
                    Faults  = validation.Errors.Select(x => new Fault()
                    {
                        Error    = x.ErrorMessage,
                        Property = x.PropertyName,
                        Value    = x.AttemptedValue == null ? "null" : x.AttemptedValue.ToString()
                    }).ToList()
                };
                break;

            case Newtonsoft.Json.JsonReaderException jsonReader:
                logger.LogDebug($"EXCEPTION HANDLING 400 | { message }");

                statusCode = HttpStatusCode.BadRequest;

                message = new ClientFault
                {
                    Message = "Our server failed to fulfill an apparently valid request",
                    Faults  = new List <Fault>()
                    {
                        new Fault()
                        {
                            Error    = "Could not cast value on property",
                            Property = jsonReader.Path,
                            Value    = jsonReader.Message
                        }
                    }
                };
                break;

            default:
                logger.LogError($"EXCEPTION HANDLING 500 | { exception }");

                statusCode = HttpStatusCode.InternalServerError;

                message = new ServerFault
                {
                    Message = "Something happend"
                };
                break;
            }

            var result = JsonSerializer.Serialize(message);

            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.StatusCode  = (int)statusCode;

            await context.Response.WriteAsync(result, Encoding.UTF8);
        }
 public virtual void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
 {
     if (info == null)
     {
         throw new ArgumentNullException("info");
     }
     if (obj != null && obj != this._rootObj)
     {
         new MessageSurrogate(this._ss).GetObjectData(obj, info, context);
     }
     else
     {
         IMethodReturnMessage methodReturnMessage = obj as IMethodReturnMessage;
         if (methodReturnMessage != null)
         {
             if (methodReturnMessage.Exception == null)
             {
                 MethodBase          methodBase          = methodReturnMessage.MethodBase;
                 SoapMethodAttribute soapMethodAttribute = (SoapMethodAttribute)InternalRemotingServices.GetCachedSoapAttribute((object)methodBase);
                 string    responseXmlElementName        = soapMethodAttribute.ResponseXmlElementName;
                 string    responseXmlNamespace          = soapMethodAttribute.ResponseXmlNamespace;
                 string    returnXmlElementName          = soapMethodAttribute.ReturnXmlElementName;
                 ArgMapper argMapper = new ArgMapper((IMethodMessage)methodReturnMessage, true);
                 object[]  args      = argMapper.Args;
                 info.FullTypeName = responseXmlElementName;
                 info.AssemblyName = responseXmlNamespace;
                 Type returnType = ((MethodInfo)methodBase).ReturnType;
                 if (!(returnType == (Type)null) && !(returnType == SoapMessageSurrogate._voidType))
                 {
                     info.AddValue(returnXmlElementName, methodReturnMessage.ReturnValue, returnType);
                 }
                 if (args == null)
                 {
                     return;
                 }
                 Type[] argTypes = argMapper.ArgTypes;
                 for (int argNum = 0; argNum < args.Length; ++argNum)
                 {
                     string name = argMapper.GetArgName(argNum);
                     if (name == null || name.Length == 0)
                     {
                         name = "__param" + (object)argNum;
                     }
                     info.AddValue(name, args[argNum], argTypes[argNum].IsByRef ? argTypes[argNum].GetElementType() : argTypes[argNum]);
                 }
             }
             else
             {
                 object data  = CallContext.GetData("__ClientIsClr");
                 bool   flag1 = data == null || (bool)data;
                 info.FullTypeName = "FormatterWrapper";
                 info.AssemblyName = this.DefaultFakeRecordAssemblyName;
                 Exception     exception     = methodReturnMessage.Exception;
                 StringBuilder stringBuilder = new StringBuilder();
                 bool          flag2         = false;
                 for (; exception != null; exception = exception.InnerException)
                 {
                     if (exception.Message.StartsWith("MustUnderstand", StringComparison.Ordinal))
                     {
                         flag2 = true;
                     }
                     stringBuilder.Append(" **** ");
                     stringBuilder.Append(exception.GetType().FullName);
                     stringBuilder.Append(" - ");
                     stringBuilder.Append(exception.Message);
                 }
                 ServerFault serverFault = !flag1 ? new ServerFault(methodReturnMessage.Exception.GetType().AssemblyQualifiedName, stringBuilder.ToString(), methodReturnMessage.Exception.StackTrace) : new ServerFault(methodReturnMessage.Exception);
                 string      faultCode   = "Server";
                 if (flag2)
                 {
                     faultCode = "MustUnderstand";
                 }
                 SoapFault soapFault = new SoapFault(faultCode, stringBuilder.ToString(), (string)null, serverFault);
                 info.AddValue("__WrappedObject", (object)soapFault, SoapMessageSurrogate._soapFaultType);
             }
         }
         else
         {
             IMethodCallMessage m                      = (IMethodCallMessage)obj;
             MethodBase         methodBase             = m.MethodBase;
             string             namespaceForMethodCall = SoapServices.GetXmlNamespaceForMethodCall(methodBase);
             object[]           inArgs                 = m.InArgs;
             string[]           inArgNames             = this.GetInArgNames(m, inArgs.Length);
             Type[]             typeArray              = (Type[])m.MethodSignature;
             info.FullTypeName = m.MethodName;
             info.AssemblyName = namespaceForMethodCall;
             int[] marshalRequestArgMap = InternalRemotingServices.GetReflectionCachedData(methodBase).MarshalRequestArgMap;
             for (int index1 = 0; index1 < inArgs.Length; ++index1)
             {
                 string name   = inArgNames[index1] == null || inArgNames[index1].Length == 0 ? "__param" + (object)index1 : inArgNames[index1];
                 int    index2 = marshalRequestArgMap[index1];
                 Type   type   = !typeArray[index2].IsByRef ? typeArray[index2] : typeArray[index2].GetElementType();
                 info.AddValue(name, inArgs[index1], type);
             }
         }
     }
 }
예제 #20
0
 public SoapFault(string faultCode, string faultString, string faultActor, ServerFault serverFault)
 {
 }
        // Token: 0x06005A89 RID: 23177 RVA: 0x0013CEA8 File Offset: 0x0013B0A8
        internal void SetObjectFromSoapData(SerializationInfo info)
        {
            Hashtable keyToNamespaceTable = (Hashtable)info.GetValue("__keyToNamespaceTable", typeof(Hashtable));
            ArrayList arrayList           = (ArrayList)info.GetValue("__paramNameList", typeof(ArrayList));
            SoapFault soapFault           = (SoapFault)info.GetValue("__fault", typeof(SoapFault));

            if (soapFault != null)
            {
                ServerFault serverFault = soapFault.Detail as ServerFault;
                if (serverFault != null)
                {
                    if (serverFault.Exception != null)
                    {
                        this.fault = serverFault.Exception;
                        return;
                    }
                    Type type = Type.GetType(serverFault.ExceptionType, false, false);
                    if (type == null)
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append("\nException Type: ");
                        stringBuilder.Append(serverFault.ExceptionType);
                        stringBuilder.Append("\n");
                        stringBuilder.Append("Exception Message: ");
                        stringBuilder.Append(serverFault.ExceptionMessage);
                        stringBuilder.Append("\n");
                        stringBuilder.Append(serverFault.StackTrace);
                        this.fault = new ServerException(stringBuilder.ToString());
                        return;
                    }
                    object[] args = new object[]
                    {
                        serverFault.ExceptionMessage
                    };
                    this.fault = (Exception)Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, args, null, null);
                    return;
                }
                else
                {
                    if (soapFault.Detail != null && soapFault.Detail.GetType() == typeof(string) && ((string)soapFault.Detail).Length != 0)
                    {
                        this.fault = new ServerException((string)soapFault.Detail);
                        return;
                    }
                    this.fault = new ServerException(soapFault.FaultString);
                    return;
                }
            }
            else
            {
                MethodInfo methodInfo = this.MI as MethodInfo;
                int        num        = 0;
                if (methodInfo != null)
                {
                    Type returnType = methodInfo.ReturnType;
                    if (returnType != typeof(void))
                    {
                        num++;
                        object value = info.GetValue((string)arrayList[0], typeof(object));
                        if (value is string)
                        {
                            this.retVal = Message.SoapCoerceArg(value, returnType, keyToNamespaceTable);
                        }
                        else
                        {
                            this.retVal = value;
                        }
                    }
                }
                ParameterInfo[] parameters = this._methodCache.Parameters;
                object          obj        = (this.InternalProperties == null) ? null : this.InternalProperties["__UnorderedParams"];
                if (obj != null && obj is bool && (bool)obj)
                {
                    for (int i = num; i < arrayList.Count; i++)
                    {
                        string text = (string)arrayList[i];
                        int    num2 = -1;
                        for (int j = 0; j < parameters.Length; j++)
                        {
                            if (text.Equals(parameters[j].Name))
                            {
                                num2 = parameters[j].Position;
                            }
                        }
                        if (num2 == -1)
                        {
                            if (!text.StartsWith("__param", StringComparison.Ordinal))
                            {
                                throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadSerialization"));
                            }
                            num2 = int.Parse(text.Substring(7), CultureInfo.InvariantCulture);
                        }
                        if (num2 >= this.argCount)
                        {
                            throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadSerialization"));
                        }
                        if (this.outArgs == null)
                        {
                            this.outArgs = new object[this.argCount];
                        }
                        this.outArgs[num2] = Message.SoapCoerceArg(info.GetValue(text, typeof(object)), parameters[num2].ParameterType, keyToNamespaceTable);
                    }
                    return;
                }
                if (this.argMapper == null)
                {
                    this.argMapper = new ArgMapper(this, true);
                }
                for (int k = num; k < arrayList.Count; k++)
                {
                    string name = (string)arrayList[k];
                    if (this.outArgs == null)
                    {
                        this.outArgs = new object[this.argCount];
                    }
                    int num3 = this.argMapper.Map[k - num];
                    this.outArgs[num3] = Message.SoapCoerceArg(info.GetValue(name, typeof(object)), parameters[num3].ParameterType, keyToNamespaceTable);
                }
                return;
            }
        }