Ejemplo n.º 1
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        internal bool CanCastToXmlType(String xmlTypeName, String xmlTypeNamespace)
        {
            Type castType = SoapServices.GetInteropTypeFromXmlType(xmlTypeName, xmlTypeNamespace);

            if (castType == null)
            {
                String typeNamespace;
                String assemblyName;
                if (!SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlTypeNamespace,
                                                                        out typeNamespace, out assemblyName))
                {
                    return(false);
                }

                String typeName;
                if ((typeNamespace != null) && (typeNamespace.Length > 0))
                {
                    typeName = typeNamespace + "." + xmlTypeName;
                }
                else
                {
                    typeName = xmlTypeName;
                }

                try
                {
                    Assembly asm = Assembly.Load(assemblyName);
                    castType = asm.GetType(typeName, false, false);
                }
                catch
                {
                    return(false);
                }
            }

            if (castType != null)
            {
                return(castType.IsAssignableFrom(this.GetType()));
            }

            return(false);
        } // CanCastToXmlType
Ejemplo n.º 2
0
        internal static bool CanCastToXmlTypeHelper(RuntimeType castType, MarshalByRefObject o)
        {
            if (castType == null)
            {
                throw new ArgumentNullException("castType");
            }
            if (!castType.IsInterface && !castType.IsMarshalByRef)
            {
                return(false);
            }
            string xmlType          = null;
            string xmlTypeNamespace = null;

            if (!SoapServices.GetXmlTypeForInteropType(castType, out xmlType, out xmlTypeNamespace))
            {
                xmlType          = castType.Name;
                xmlTypeNamespace = SoapServices.CodeXmlNamespaceForClrTypeNamespace(castType.Namespace, castType.GetRuntimeAssembly().GetSimpleName());
            }
            return(o.CanCastToXmlType(xmlType, xmlTypeNamespace));
        }
Ejemplo n.º 3
0
        public void TestGetInteropType()
        {
            Type t;

            // Manual registration

            t = SoapServices.GetInteropTypeFromXmlElement("aa", "bb");
            Assert.AreEqual(t, null, "M1");

            SoapServices.RegisterInteropXmlElement("aa", "bb", typeof(SoapTest));
            t = SoapServices.GetInteropTypeFromXmlElement("aa", "bb");
            Assert.AreEqual(typeof(SoapTest), t, "M2");


            t = SoapServices.GetInteropTypeFromXmlType("aa", "bb");
            Assert.AreEqual(null, t, "M3");

            SoapServices.RegisterInteropXmlType("aa", "bb", typeof(SoapTest));
            t = SoapServices.GetInteropTypeFromXmlType("aa", "bb");
            Assert.AreEqual(typeof(SoapTest), t, "M4");

            // Preload type

            SoapServices.PreLoad(typeof(SoapTest2));

            t = SoapServices.GetInteropTypeFromXmlElement("ename", ThisNamespace);
            Assert.AreEqual(typeof(SoapTest2), t, "T1");

            t = SoapServices.GetInteropTypeFromXmlType("tname", ThisNamespace);
            Assert.AreEqual(typeof(SoapTest2), t, "T2");

            // Preload assembly

            SoapServices.PreLoad(typeof(SoapTest).Assembly);

            t = SoapServices.GetInteropTypeFromXmlElement("SoapTest3", "ens");
            Assert.AreEqual(typeof(SoapTest3), t, "A1");

            t = SoapServices.GetInteropTypeFromXmlType("SoapTest3", "tns");
            Assert.AreEqual(typeof(SoapTest3), t, "A2");
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Create a session and login to UMarket
        /// </summary>
        /// <returns></returns>
        static string CreatAndLoginSession()
        {
            #region Config
            string init = ConfigurationManager.AppSettings["init"].ToString(); // "0277551990";//"0573449847";// "0278793422";
            string salt = ConfigurationManager.AppSettings["salt"].ToString(); //"0277551990";//"0278793422";
            string pin  = ConfigurationManager.AppSettings["pin"].ToString();  // "1212";//"1234";
            #endregion
            // Get
            string response = SoapServices.SendXMLRequest(GetXMLCommands.GetSessionXML());
            var    t        = XElement.Parse(response);

            string session = t.Value.Remove(t.Value.Length - 8);

            pin      = GeneralService.GetPin(session, salt, pin);
            response = GetXMLCommands.GetLoginXML(init, pin, session);
            response = SoapServices.SendXMLRequest(response);

            t = XElement.Parse(response);

            string transactionId = t.Value.Remove(t.Value.Length - 8);

            return(session);
        }
Ejemplo n.º 5
0
        internal static void ProcessTypeAttribute(Type type, SoapAttributeInfo attributeInfo)
        {
            string            str;
            string            str2;
            SoapTypeAttribute cachedSoapAttribute = (SoapTypeAttribute)InternalRemotingServices.GetCachedSoapAttribute(type);

            if (cachedSoapAttribute.Embedded)
            {
                attributeInfo.m_attributeType |= SoapAttributeType.Embedded;
            }
            if (SoapServices.GetXmlElementForInteropType(type, out str, out str2))
            {
                attributeInfo.m_attributeType |= SoapAttributeType.XmlElement;
                attributeInfo.m_elementName    = str;
                attributeInfo.m_nameSpace      = str2;
            }
            if (SoapServices.GetXmlTypeForInteropType(type, out str, out str2))
            {
                attributeInfo.m_attributeType |= SoapAttributeType.XmlType;
                attributeInfo.m_typeName       = str;
                attributeInfo.m_typeNamespace  = str2;
            }
        }
Ejemplo n.º 6
0
        } // AsyncProcessMessage

        //
        // end of IMessageSink implementation
        //


        // helper function to serialize the message
        private void SerializeMessage(IMethodCallMessage mcm,
                                      out ITransportHeaders headers, out Stream stream)
        {
            BaseTransportHeaders requestHeaders = new BaseTransportHeaders();

            headers = requestHeaders;

            // add SOAPAction header
            MethodBase mb = mcm.MethodBase;

            headers["SOAPAction"] =
                '"' +
                HttpEncodingHelper.EncodeUriAsXLinkHref(
                    SoapServices.GetSoapActionFromMethodBase(mb)) +
                '"';

            // add other http soap headers
            requestHeaders.ContentType = CoreChannel.SOAPContentType;
            if (_channelProtocol == SinkChannelProtocol.Http)
            {
                headers["__RequestVerb"] = "POST";
            }

            bool bMemStream = false;

            stream = _nextSink.GetRequestStream(mcm, headers);
            if (stream == null)
            {
                stream     = new ChunkedMemoryStream(CoreChannel.BufferPool);
                bMemStream = true;
            }
            CoreChannel.SerializeSoapMessage(mcm, stream, _includeVersioning);
            if (bMemStream)
            {
                stream.Position = 0;
            }
        } // SerializeMessage
Ejemplo n.º 7
0
        public void TestSoapActions()
        {
            string     act;
            MethodBase mb;

            mb  = typeof(SoapTest).GetMethod("FesAlgo");
            act = SoapServices.GetSoapActionFromMethodBase(mb);
            Assert.AreEqual("myaction", act, "S1");

            mb = typeof(SoapTest).GetMethod("FesAlgoMes");
            SoapServices.RegisterSoapActionForMethodBase(mb, "anotheraction");
            act = SoapServices.GetSoapActionFromMethodBase(mb);
            Assert.AreEqual("anotheraction", act, "S2");

            mb  = typeof(SoapTest).GetMethod("FesAlgoMesEspecial");
            act = SoapServices.GetSoapActionFromMethodBase(mb);
            Assert.AreEqual(GetClassNs(typeof(SoapTest)) + "#FesAlgoMesEspecial", act, "S3");

            string typeName, methodName;
            bool   res;

            res = SoapServices.GetTypeAndMethodNameFromSoapAction("myaction", out typeName, out methodName);
            Assert.IsTrue(res, "M1");
            Assert.AreEqual(GetSimpleTypeName(typeof(SoapTest)), typeName, "M2");
            Assert.AreEqual("FesAlgo", methodName, "M3");

            res = SoapServices.GetTypeAndMethodNameFromSoapAction("anotheraction", out typeName, out methodName);
            Assert.IsTrue(res, "M4");
            Assert.AreEqual(GetSimpleTypeName(typeof(SoapTest)), typeName, "M5");
            Assert.AreEqual("FesAlgoMes", methodName, "M6");

            res = SoapServices.GetTypeAndMethodNameFromSoapAction(GetClassNs(typeof(SoapTest)) + "#FesAlgoMesEspecial", out typeName, out methodName);
            Assert.IsTrue(res, "M7");
            Assert.AreEqual(GetSimpleTypeName(typeof(SoapTest)), typeName, "M8");
            Assert.AreEqual("FesAlgoMesEspecial", methodName, "M9");
        }
        // used by the server
        internal IMessage BuildMethodCallFromSoapMessage(SoapMessage soapMessage, string uri)
        {
            ArrayList headersList = new ArrayList();

            Type[] signature = null;

            headersList.Add(new Header("__Uri", uri));
            headersList.Add(new Header("__MethodName", soapMessage.MethodName));
            string typeNamespace, assemblyName;

            if (!SoapServices.DecodeXmlNamespaceForClrTypeNamespace(soapMessage.XmlNameSpace, out typeNamespace, out assemblyName))
            {
                throw new RemotingException("Could not decode SoapMessage");
            }

            // Note that we don't need to validate the type in
            // this place because MethodCall will do it anyway.

            if (assemblyName == null) // corlib
            {
                _serverType = Type.GetType(typeNamespace, true);
            }
            else
            {
                _serverType = Type.GetType(typeNamespace + ", " + assemblyName, true);
            }

            headersList.Add(new Header("__TypeName", _serverType.FullName, false));

            if (soapMessage.Headers != null)
            {
                foreach (Header h in soapMessage.Headers)
                {
                    headersList.Add(h);
                    if (h.Name == "__MethodSignature")
                    {
                        signature = (Type[])h.Value;
                    }
                }
            }

            _xmlNamespace = soapMessage.XmlNameSpace;
            //RemMessageType messageType;

            BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            if (signature == null)
            {
                _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags);
            }
            else
            {
                _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags, null, signature, null);
            }

            if (_methodCallInfo == null && (soapMessage.MethodName == "FieldSetter" || soapMessage.MethodName == "FieldGetter"))
            {
                _methodCallInfo = typeof(object).GetMethod(soapMessage.MethodName, bflags);
            }

            // the *out* parameters aren't serialized
            // have to add them here
            _methodCallParameters = _methodCallInfo.GetParameters();
            object[] args = new object[_methodCallParameters.Length];
            int      sn   = 0;

            for (int n = 0; n < _methodCallParameters.Length; n++)
            {
                ParameterInfo paramInfo = _methodCallParameters [n];
                Type          paramType = (paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType);

                if (paramInfo.IsOut && paramInfo.ParameterType.IsByRef)
                {
                    args [n] = GetNullValue(paramType);
                }
                else
                {
                    object val = soapMessage.ParamValues[sn++];
                    if (val is IConvertible)
                    {
                        args [n] = Convert.ChangeType(val, paramType);
                    }
                    else
                    {
                        args [n] = val;
                    }
                }
            }

            headersList.Add(new Header("__Args", args, false));

            Header[] headers = (Header[])headersList.ToArray(typeof(Header));

            // build the MethodCall from the headers
            MethodCall mthCall = new MethodCall(headers);

            return((IMessage)mthCall);
        }
Ejemplo n.º 9
0
    public static void Main(string[] args)
    {
        //<snippet101>
        // Convert a CLR namespace and assembly name into an XML namespace.
        string xmlNamespace =
            SoapServices.CodeXmlNamespaceForClrTypeNamespace(
                "ExampleNamespace", "AssemblyName");

        Console.WriteLine("The name of the XML namespace is {0}.",
                          xmlNamespace);
        //</snippet101>

        //<snippet102>
        // Extract a CLR namespace and assembly name from an XML namespace.
        string typeNamespace;
        string assemblyName;

        SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlNamespace,
                                                           out typeNamespace, out assemblyName);
        Console.WriteLine("The name of the CLR namespace is {0}.",
                          typeNamespace);
        Console.WriteLine("The name of the CLR assembly is {0}.",
                          assemblyName);
        //</snippet102>

        //<snippet103>
        // Get the XML element name and the XML namespace for
        // an Interop type.
        string xmlElement;
        bool   isSoapTypeAttribute =
            SoapServices.GetXmlElementForInteropType(
                typeof(ExampleNamespace.ExampleClass),
                out xmlElement, out xmlNamespace);

        // Print whether the requested value was flagged
        // with a SoapTypeAttribute.
        if (isSoapTypeAttribute)
        {
            Console.WriteLine(
                "The requested value was flagged " +
                "with the SoapTypeAttribute.");
        }
        else
        {
            Console.WriteLine(
                "The requested value was not flagged " +
                "with the SoapTypeAttribute.");
        }

        // Print the XML element and the XML namespace.
        Console.WriteLine(
            "The XML element for the type " +
            "ExampleNamespace.ExampleClass is {0}.",
            xmlElement);
        Console.WriteLine(
            "The XML namespace for the type " +
            "ExampleNamespace.ExampleClass is {0}.",
            xmlNamespace);
        //</snippet103>

        //<snippet104>
        // Get the XML type name and the XML type namespace for
        // an Interop type.
        string xmlTypeName;
        string xmlTypeNamespace;

        isSoapTypeAttribute =
            SoapServices.GetXmlTypeForInteropType(
                typeof(ExampleNamespace.ExampleClass),
                out xmlTypeName, out xmlTypeNamespace);

        // Print whether the requested value was flagged
        // with a SoapTypeAttribute.
        if (isSoapTypeAttribute)
        {
            Console.WriteLine(
                "The requested value was flagged " +
                "with the SoapTypeAttribute.");
        }
        else
        {
            Console.WriteLine(
                "The requested value was not flagged " +
                "with the SoapTypeAttribute.");
        }

        // Print the XML type name and the XML type namespace.
        Console.WriteLine(
            "The XML type for the type " +
            "ExampleNamespace.ExampleClass is {0}.",
            xmlTypeName);
        Console.WriteLine(
            "The XML type namespace for the type " +
            "ExampleNamespace.ExampleClass is {0}.",
            xmlTypeNamespace);
        //</snippet104>

        //<snippet105>
        // Print the XML namespace for a method invocation and its
        // response.
        System.Reflection.MethodBase getHelloMethod =
            typeof(ExampleNamespace.ExampleClass).GetMethod("GetHello");
        string methodCallXmlNamespace =
            SoapServices.GetXmlNamespaceForMethodCall(getHelloMethod);
        string methodResponseXmlNamespace =
            SoapServices.GetXmlNamespaceForMethodResponse(getHelloMethod);

        Console.WriteLine(
            "The XML namespace for the invocation of the method " +
            "GetHello in ExampleClass is {0}.",
            methodResponseXmlNamespace);
        Console.WriteLine(
            "The XML namespace for the response of the method " +
            "GetHello in ExampleClass is {0}.",
            methodCallXmlNamespace);
        //</snippet105>

        //<snippet106>
        // Determine whether an XML namespace represents a CLR namespace.
        string clrNamespace = SoapServices.XmlNsForClrType;

        if (SoapServices.IsClrTypeNamespace(clrNamespace))
        {
            Console.WriteLine(
                "The namespace {0} is a CLR namespace.",
                clrNamespace);
        }
        else
        {
            Console.WriteLine(
                "The namespace {0} is not a CLR namespace.",
                clrNamespace);
        }
        //</snippet106>

        //<snippet130>
        // Print the XML namespace for the CLR types.
        Console.WriteLine(
            "The XML namespace for the CLR types " +
            "is {0}.",
            SoapServices.XmlNsForClrType);
        //</snippet130>

        //<snippet131>
        // Print the XML namespace for the CLR types
        // that have an assembly but no common language runtime namespace.
        Console.WriteLine(
            "The XML namespace for the CLR types " +
            "that have an assembly but no namespace, is {0}.",
            SoapServices.XmlNsForClrTypeWithAssembly);
        //</snippet131>

        //<snippet132>
        // Print the XML namespace for the CLR types
        // that are a part of the Mscorlib.dll.
        Console.WriteLine(
            "The XML namespace for the CLR types " +
            "that are part of the Mscorlib.dll, is {0}.",
            SoapServices.XmlNsForClrTypeWithNs);
        //</snippet132>

        //<snippet133>
        // Print the XML namespace for the CLR types
        // that have both an assembly and a common language runtime
        // namespace.
        Console.WriteLine(
            "The XML namespace for the CLR types " +
            "that have both an assembly and a namespace, is {0}.",
            SoapServices.XmlNsForClrTypeWithNsAndAssembly);
        //</snippet133>

        //<snippet140>
        // Get the SOAP action for the method.
        System.Reflection.MethodBase getHelloMethodBase =
            typeof(ExampleNamespace.ExampleClass).GetMethod("GetHello");
        string getHelloSoapAction =
            SoapServices.GetSoapActionFromMethodBase(getHelloMethodBase);

        Console.WriteLine(
            "The SOAP action for the method " +
            "ExampleClass.GetHello is {0}.", getHelloSoapAction);
        bool isSoapActionValid = SoapServices.IsSoapActionValidForMethodBase(
            getHelloSoapAction,
            getHelloMethodBase);

        if (isSoapActionValid)
        {
            Console.WriteLine(
                "The SOAP action, {0}, " +
                "is valid for ExampleClass.GetHello",
                getHelloSoapAction);
        }
        else
        {
            Console.WriteLine(
                "The SOAP action, {0}, " +
                "is not valid for ExampleClass.GetHello",
                getHelloSoapAction);
        }

        // Register the SOAP action for the GetHello method.
        SoapServices.RegisterSoapActionForMethodBase(getHelloMethodBase);

        // Get the type and the method names encoded into the SOAP action.
        string encodedTypeName;
        string encodedMethodName;

        SoapServices.GetTypeAndMethodNameFromSoapAction(
            getHelloSoapAction,
            out encodedTypeName,
            out encodedMethodName);
        Console.WriteLine(
            "The type name encoded in this SOAP action is {0}.",
            encodedTypeName);
        Console.WriteLine(
            "The method name encoded in this SOAP action is {0}.",
            encodedMethodName);
        //</snippet140>

        //<snippet150>
        // Get the name and the type of the field using its XML
        // element name and its XML namespace. For this query to work,
        // the containing type must be preloaded, and the XML element
        // name and the XML namespace must be explicitly declared on
        // the field using a SoapFieldAttribute.

        // Preload the containing type.
        SoapServices.PreLoad(typeof(ExampleNamespace.ExampleClass));

        // Get the name and the type of a field that will be
        // serialized as an XML element.
        Type   containingType      = typeof(ExampleNamespace.ExampleClass);
        string xmlElementNamespace =
            "http://example.org/ExampleFieldNamespace";
        string xmlElementName = "ExampleFieldElementName";
        Type   fieldType;
        string fieldName;

        SoapServices.GetInteropFieldTypeAndNameFromXmlElement(
            containingType, xmlElementName, xmlElementNamespace,
            out fieldType, out fieldName);
        Console.WriteLine(
            "The type of the field is {0}.",
            fieldType);
        Console.WriteLine(
            "The name of the field is {0}.",
            fieldName);

        // Get the name and the type of a field that will be
        // serialized as an XML attribute.
        string xmlAttributeNamespace =
            "http://example.org/ExampleAttributeNamespace";
        string xmlAttributeName = "ExampleFieldAttributeName";

        SoapServices.GetInteropFieldTypeAndNameFromXmlAttribute(
            containingType, xmlAttributeName, xmlAttributeNamespace,
            out fieldType, out fieldName);
        Console.WriteLine(
            "The type of the field is {0}.",
            fieldType);
        Console.WriteLine(
            "The name of the field is {0}.",
            fieldName);
        //</snippet150>

        //<snippet160>
        string interopTypeXmlElementName =
            "ExampleClassElementName";
        string interopTypeXmlNamespace =
            "http://example.org/ExampleXmlNamespace";
        Type interopType = SoapServices.GetInteropTypeFromXmlElement(
            interopTypeXmlElementName,
            interopTypeXmlNamespace);

        Console.WriteLine("The interop type is {0}.", interopType);

        string interopTypeXmlTypeName =
            "ExampleXmlTypeName";
        string interopTypeXmlTypeNamespace =
            "http://example.org/ExampleXmlTypeNamespace";

        interopType = SoapServices.GetInteropTypeFromXmlType(
            interopTypeXmlTypeName, interopTypeXmlTypeNamespace);
        Console.WriteLine("The interop type is {0}.", interopType);
        //</snippet160>

        //<snippet170>
        // Get the method base object for the GetHello method.
        System.Reflection.MethodBase methodBase =
            typeof(ExampleNamespace.ExampleClass).GetMethod("GetHello");

        // Print its current SOAP action.
        Console.WriteLine(
            "The SOAP action for the method " +
            "ExampleClass.GetHello is {0}.",
            SoapServices.GetSoapActionFromMethodBase(methodBase));

        // Set the SOAP action of the GetHello method to a new value.
        string newSoapAction =
            "http://example.org/ExampleSoapAction#NewSoapAction";

        SoapServices.RegisterSoapActionForMethodBase(
            methodBase, newSoapAction);
        Console.WriteLine(
            "The SOAP action for the method " +
            "ExampleClass.GetHello is {0}.",
            SoapServices.GetSoapActionFromMethodBase(methodBase));

        // Reset the SOAP action of the GetHello method to its default
        // value, which is determined using its SoapMethod attribute.
        SoapServices.RegisterSoapActionForMethodBase(methodBase);
        Console.WriteLine(
            "The SOAP action for the method " +
            "ExampleClass.GetHello is {0}.",
            SoapServices.GetSoapActionFromMethodBase(methodBase));
        //</snippet170>

        //<snippet120>
        // Register all types in the assembly with the SoapType attribute.
        System.Reflection.Assembly executingAssembly =
            System.Reflection.Assembly.GetExecutingAssembly();
        SoapServices.PreLoad(executingAssembly);
        //</snippet120>

        //<snippet121>
        // Register a specific type with the SoapType attribute.
        Type exampleType = typeof(ExampleNamespace.ExampleClass);

        SoapServices.PreLoad(exampleType);
        //</snippet121>

        //<snippet180>
        // Get the currently registered type for the given XML element
        // and namespace.
        string registeredXmlElementName =
            "ExampleClassElementName";
        string registeredXmlNamespace =
            "http://example.org/ExampleXmlNamespace";
        Type registeredType =
            SoapServices.GetInteropTypeFromXmlElement(
                registeredXmlElementName,
                registeredXmlNamespace);

        Console.WriteLine(
            "The registered interop type is {0}.",
            registeredType);

        // Register a new type for the XML element and namespace.
        SoapServices.RegisterInteropXmlElement(
            registeredXmlElementName,
            registeredXmlNamespace,
            typeof(String));

        // Get the currently registered type for the given XML element
        // and namespace.
        registeredType =
            SoapServices.GetInteropTypeFromXmlElement(
                registeredXmlElementName,
                registeredXmlNamespace);
        Console.WriteLine(
            "The registered interop type is {0}.",
            registeredType);
        //</snippet180>

        //<snippet190>
        // Get the currently registered type for the given XML element
        // and namespace.
        string registeredXmlTypeName =
            "ExampleXmlTypeName";
        string registeredXmlTypeNamespace =
            "http://example.org/ExampleXmlTypeNamespace";

        registeredType =
            SoapServices.GetInteropTypeFromXmlType(
                registeredXmlTypeName,
                registeredXmlTypeNamespace);
        Console.WriteLine(
            "The registered interop type is {0}.",
            registeredType);

        // Register a new type for the XML element and namespace.
        SoapServices.RegisterInteropXmlType(
            registeredXmlTypeName,
            registeredXmlTypeNamespace,
            typeof(String));

        // Get the currently registered type for the given XML element
        // and namespace.
        registeredType =
            SoapServices.GetInteropTypeFromXmlType(
                registeredXmlTypeName,
                registeredXmlTypeNamespace);
        Console.WriteLine(
            "The registered interop type is {0}.",
            registeredType);
        //</snippet190>
    }
Ejemplo n.º 10
0
        } // StrictBinding



        /// <include file='doc\SoapFormatterSinks.uex' path='docs/doc[@for="SoapServerFormatterSink.ProcessMessage"]/*' />
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg,
                                               ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders,
                                               out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return(_nextSink.ProcessMessage(
                           sinkStack,
                           requestMsg, requestHeaders, requestStream,
                           out responseMsg, out responseHeaders, out responseStream));
            }

            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }

            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;

            ServerProcessing processing;

            responseHeaders = null;
            responseStream  = null;

            String verb        = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;

            if (wkRequestHeaders != null)
            {
                contentTypeHeader = wkRequestHeaders.ContentType;
            }
            else
            {
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            }
            if (contentTypeHeader != null)
            {
                String charsetValue;
                HttpChannelHelper.ParseContentType(contentTypeHeader,
                                                   out contentType, out charsetValue);
            }

            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.Compare(contentType, CoreChannel.SOAPMimeType, false, CultureInfo.InvariantCulture) != 0))
            {
                bCanServiceRequest = false;
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {
                verb = (String)requestHeaders["__RequestVerb"];
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                {
                    bCanServiceRequest = false;
                }
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
            {
                // delegate to next sink if available
                if (_nextSink != null)
                {
                    return(_nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,
                                                    out responseMsg, out responseHeaders, out responseStream));
                }
                else
                {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"]   = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg    = null;
                        return(ServerProcessing.Complete);
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                                  CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }

            bool bClientIsClr = true;

            try
            {
                String objectUri = null;
                if (wkRequestHeaders != null)
                {
                    objectUri = wkRequestHeaders.RequestUri;
                }
                else
                {
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];
                }

                if (RemotingServices.GetServerTypeForUri(objectUri) == null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }


                if (_protocol == Protocol.Http)
                {
                    String userAgent = (String)requestHeaders["User-Agent"];
                    if (userAgent != null)
                    {
                        if (userAgent.IndexOf("MS .NET Remoting") == -1)
                        {
                            // user agent string did not contain ".NET Remoting", so it is someone else
                            bClientIsClr = false;
                        }
                    }
                    else
                    {
                        bClientIsClr = false;
                    }
                }



                // Deserialize Request - Stream to IMessage
                String   soapActionToVerify;
                Header[] h = GetChannelHeaders(requestHeaders, out soapActionToVerify);

                requestMsg = CoreChannel.DeserializeSoapRequestMessage(requestStream, h, _strictBinding);
                requestStream.Close();

                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }

                // verify soap action if necessary
                if ((soapActionToVerify != null) &&
                    (!SoapServices.IsSoapActionValidForMethodBase(
                         soapActionToVerify, ((IMethodMessage)requestMsg).MethodBase)))
                {
                    throw new RemotingException(
                              String.Format(
                                  CoreChannel.GetResourceString("Remoting_Soap_InvalidSoapAction"),
                                  soapActionToVerify)
                              );
                }

                // Dispatch Call
                sinkStack.Push(this, null);
                processing =
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                                             out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }

                switch (processing)
                {
                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }

                    sinkStack.Pop(this);

                    SerializeResponse(sinkStack, responseMsg, bClientIsClr,
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;
                } // case ServerProcessing.Async
                } // switch (processing)
            }
            catch (Exception e)
            {
                processing  = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg == null?new ErrorMessage():requestMsg));
                CallContext.SetData("__ClientIsClr", bClientIsClr);
                responseStream = (MemoryStream)CoreChannel.SerializeSoapMessage(responseMsg, _includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0;
                responseHeaders         = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["__HttpStatusCode"]   = "500";
                    responseHeaders["__HttpReasonPhrase"] = "Internal Server Error";
                    responseHeaders["Content-Type"]       = CoreChannel.SOAPContentType;
                }
            }

            return(processing);
        } // ProcessMessage
 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);
             }
         }
     }
 }
Ejemplo n.º 12
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
 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);
             }
         }
     }
 }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            ServerProcessing complete;

            if (requestMsg != null)
            {
                return(this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
            }
            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }
            BaseTransportHeaders headers = requestHeaders as BaseTransportHeaders;

            responseHeaders = null;
            responseStream  = null;
            string str         = null;
            string str2        = null;
            bool   flag        = true;
            string contentType = null;

            if (headers != null)
            {
                contentType = headers.ContentType;
            }
            else
            {
                contentType = requestHeaders["Content-Type"] as string;
            }
            if (contentType != null)
            {
                string str4;
                HttpChannelHelper.ParseContentType(contentType, out str2, out str4);
            }
            if ((str2 != null) && (string.Compare(str2, "text/xml", StringComparison.Ordinal) != 0))
            {
                flag = false;
            }
            if (this._protocol == Protocol.Http)
            {
                str = (string)requestHeaders["__RequestVerb"];
                if (!str.Equals("POST") && !str.Equals("M-POST"))
                {
                    flag = false;
                }
            }
            if (!flag)
            {
                if (this._nextSink != null)
                {
                    return(this._nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
                }
                if (this._protocol != Protocol.Http)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                }
                responseHeaders = new TransportHeaders();
                responseHeaders["__HttpStatusCode"]   = "400";
                responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                responseStream = null;
                responseMsg    = null;
                return(ServerProcessing.Complete);
            }
            bool bClientIsClr = true;

            try
            {
                string str7;
                string uRI = null;
                if (headers != null)
                {
                    uRI = headers.RequestUri;
                }
                else
                {
                    uRI = (string)requestHeaders["__RequestUri"];
                }
                if (RemotingServices.GetServerTypeForUri(uRI) == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }
                if (this._protocol == Protocol.Http)
                {
                    string str6 = (string)requestHeaders["User-Agent"];
                    if (str6 != null)
                    {
                        if (str6.IndexOf("MS .NET Remoting") == -1)
                        {
                            bClientIsClr = false;
                        }
                    }
                    else
                    {
                        bClientIsClr = false;
                    }
                }
                bool   data = true;
                object obj2 = requestHeaders["__CustomErrorsEnabled"];
                if ((obj2 != null) && (obj2 is bool))
                {
                    data = (bool)obj2;
                }
                CallContext.SetData("__CustomErrorsEnabled", data);
                Header[]      channelHeaders = this.GetChannelHeaders(requestHeaders, out str7);
                PermissionSet set            = null;
                if (this.TypeFilterLevel != System.Runtime.Serialization.Formatters.TypeFilterLevel.Full)
                {
                    set = new PermissionSet(PermissionState.None);
                    set.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                }
                try
                {
                    if (set != null)
                    {
                        set.PermitOnly();
                    }
                    requestMsg = CoreChannel.DeserializeSoapRequestMessage(requestStream, channelHeaders, this._strictBinding, this.TypeFilterLevel);
                }
                finally
                {
                    if (set != null)
                    {
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
                requestStream.Close();
                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }
                if ((str7 != null) && !SoapServices.IsSoapActionValidForMethodBase(str7, ((IMethodMessage)requestMsg).MethodBase))
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Soap_InvalidSoapAction"), new object[] { str7 }));
                }
                sinkStack.Push(this, null);
                complete = this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
                if (responseStream != null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }
                switch (complete)
                {
                case ServerProcessing.Complete:
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }
                    break;

                case ServerProcessing.OneWay:
                    sinkStack.Pop(this);
                    return(complete);

                case ServerProcessing.Async:
                    sinkStack.Store(this, null);
                    return(complete);

                default:
                    return(complete);
                }
                sinkStack.Pop(this);
                this.SerializeResponse(sinkStack, responseMsg, bClientIsClr, ref responseHeaders, out responseStream);
                return(complete);
            }
            catch (Exception exception)
            {
                complete    = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(exception, (requestMsg == null) ? ((IMethodCallMessage) new System.Runtime.Remoting.Channels.Http.ErrorMessage()) : ((IMethodCallMessage)requestMsg));
                CallContext.SetData("__ClientIsClr", bClientIsClr);
                responseStream = (MemoryStream)CoreChannel.SerializeSoapMessage(responseMsg, this._includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0L;
                responseHeaders         = new TransportHeaders();
                if (this._protocol == Protocol.Http)
                {
                    responseHeaders["__HttpStatusCode"]   = "500";
                    responseHeaders["__HttpReasonPhrase"] = "Internal Server Error";
                    responseHeaders["Content-Type"]       = "text/xml; charset=\"utf-8\"";
                }
            }
            finally
            {
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }
            return(complete);
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            #region temp

            //            int iii=1;

//            Console.WriteLine("Testing--Pos- re-processing");
//            IList<TempModel> new_request1 = new List<TempModel>(MainRepository.TempGetAllRequests());

//            foreach(var req in new_request1)
//            {
//                string ttt = SoapServices.SendXMLRequest(GetXMLCommands.GetRegisterPayment(req.phoneNumber,req.amount));

//                MainRepository.TempUpdateNumber(req);
//                Console.WriteLine(ttt);
//                Console.WriteLine(iii++);
//// testing
            //            }
            #endregion
            Console.WriteLine("Tigo Cash Requests Count_v1.5");
            #region Constants
            string init       = ConfigurationManager.AppSettings["init"].ToString();       // "0277551990";//"0573449847";// "0278793422";
            string salt       = ConfigurationManager.AppSettings["salt"].ToString();       //"0277551990";//"0278793422";
            string pin        = ConfigurationManager.AppSettings["pin"].ToString();        // "1212";//"1234";
            string amount     = ConfigurationManager.AppSettings["amount"].ToString();     // "1212";//"1234";
            string fundsource = ConfigurationManager.AppSettings["fundsource"].ToString(); // "1212";//"1234";
            #endregion

            int i = 1;
            while (i > 0)
            {
                try
                {
                    IList <RequestModel> new_request = new List <RequestModel>(MainRepository.GetAllRequests());
                    int int_temp = 0;
                    foreach (RequestModel req in new_request)
                    {
                        if (MainRepository.OnWhileList(req))
                        {
                            MainRepository.UpdateTigoCashRequest(req, 3);

                            //SMSService.SendSMSMiddleware("Tigo", "0277443830", "Wc-request");

                            string session = CreatAndLoginSession();
                            //  int current_count = MainRepository.GetCurrentReceiptNumber() + 1;
                            string reponse = string.Empty;

                            // check if registered- to do;
                            reponse = SoapServices.SendXMLRequest(GetXMLCommands.GetAgentStatusXML(req.SubscriberNumber, session));


                            #region Registration
                            if (reponse.Contains("cashsubscriber"))
                            {
                            }
                            else
                            {
                                reponse = SoapServices.SendXMLRequest(GetXMLCommands.GetRegisterXML(req.RequestBy, session, req.SubscriberNumber, req.SubscriberName, req.SubscriberAddress, "Ghanaian", req.DOB, req.SubscriberIdType, req.SubscriberIdNumber));
                                LogService.AutoLog(req.SubscriberNumber, DbFriendly(reponse), "TigoCashWelcomePack");
                                Console.WriteLine("--log--");
                            }
                            #endregion

                            #region Activate
                            for (int x = 0; x < 10; x++)
                            {
                                string receiptNumber = GetReceiptNumber();
                                reponse = SoapServices.SendXMLRequest(GetXMLCommands.GetActivateXML(session, req.SubscriberNumber, init, pin, receiptNumber));
                                // MainRepository.UpdateReceiptNumber(current_count);

                                LogService.AutoLog(req.SubscriberNumber, DbFriendly(reponse), "TigoCashWelcomePack");
                                Console.WriteLine("--log--");

                                if (CheckIfSucessfull(reponse))
                                {
                                    MainRepository.UpdateReceiptNumber(receiptNumber, 1);
                                    MainRepository.UpdateTigoCashRequest(req, 4);
                                    break;
                                }
                                else
                                {
                                    if (reponse.Contains("10006"))
                                    {
                                        MainRepository.UpdateTigoCashRequest(req, 5); // already active
                                        break;
                                    }
                                    else
                                    {
                                        MainRepository.UpdateReceiptNumber(receiptNumber, 3); // already used
                                    }
                                }
                            }

                            #endregion

                            #region Donate 1GHC

                            //if (MainRepository.CheckIfAlreadyProcessed(req.SubscriberNumber))
                            //{
                            //MainRepository.UpdateTigoCashRequest(req, 3); // duplicate request
                            //SMSService.SendSMSMiddleware("Tigo", req.RequestBy, "This subscriber " +  req.SubscriberIdNumber + "  has already received the tigo cash welcome package.");
                            //}
                            //else
                            //{
                            //   reponse = SoapServices.SendXMLRequest(GetXMLCommands.GetAdjustWalletXML(session, fundsource,req.SubscriberNumber));
                            // LogService.AutoLog(req.SubscriberNumber, DbFriendly(reponse), "TigoCashWelcomePack");
                            #endregion

                            #region Check response
                            //if (CheckIfSucessfull(reponse))
                            //{
                            //    //SMSService.SendSMSMiddleware("Tigo", "0277443830", "WC-request-completed");
                            //    LogService.AutoLog(req.SubscriberNumber, "Operation Successful", "TigoCashWelcomePack");
                            //    MainRepository.UpdateTigoCashRequest(req, 1);
                            //    SMSService.SendSMSMiddleware("Tigo", req.SubscriberNumber, "Welcome to Tigo Cash, Your account has been credited with 1 GHC. Smile you've got Tigo");
                            //}
                            //else
                            //{
                            //    MainRepository.UpdateNumberOfTries(req);
                            //    SMSService.SendSMSMiddleware("Tigo", req.RequestBy, req.SubscriberNumber + ", Tigo cash registration was not successful");
                            //}
                            #endregion
                            //}

                            SMSService.SendSMSMiddleware("Tigo", req.SubscriberNumber, "Welcome to Tigo Cash, Your has been activated.");
                        }
                        else
                        {
                            MainRepository.UpdateTigoCashRequest(req, 2);
                            SMSService.SendSMSMiddleware("Tigo", req.RequestBy, "You are not permitted to undertake Tigo Cash transactions");
                        }
                        Console.WriteLine("Request No. " + int_temp++);
                    }
                }
                catch (Exception ex)
                {
                    LogService.AutoLog("Application Error", ex.Message, "TigoCashWelcomePack");
                    Console.WriteLine("--error--");
                }
            }
        }
Ejemplo n.º 16
0
        String GetHeaders(ISmtpMessage smtpMessage, ref Smtp.Fields headers, ref String contentType, ref Header[] msgHeaders)
        {
            // Get the headers from the message object
            headers = smtpMessage.Fields;
#if _DEBUG
            long count = headers.Count;
            InternalRemotingServices.RemotingTrace(" Count of fields " + count);
            for (long i = 0; i < count; i++)
            {
                //InternalRemotingServices.RemotingTrace(" Field " + i + " " + headers[i].Name + " " + headers[i].Value);
            }
#endif

            // Get the content type string
            Field typeField = headers["urn:schemas:mailheader:contenttype"];
            if (null == typeField)
            {
                throw new FormatException(CoreChannel.GetResourceString("Remoting_MissingContentType"));
            }
            contentType = (String)(typeField.Value);
            InternalRemotingServices.RemotingTrace("Content type " + typeField.Name + " " + contentType);

            // Extract the requested uri from the mail header
            Field uriField = headers["urn:schemas:mailheader:requesteduri"];
            if (null == uriField)
            {
                throw new FormatException(CoreChannel.GetResourceString("Remoting_MissingRequestedURIHeader"));
            }
            String uriValue = (String)uriField.Value;
            if (null == uriValue)
            {
                throw new FormatException(CoreChannel.GetResourceString("Remoting_MissingRequestedURIHeader"));
            }

            // process SoapAction (extract the type and the name of the method to be invoked)
            Field actionField = headers["urn:schemas:mailheader:soapaction"];
            if (null == actionField)
            {
                throw new FormatException(CoreChannel.GetResourceString("Remoting_SoapActionMissing"));
            }
            String actionValue = (String)actionField.Value;
            if (null == actionValue)
            {
                throw new FormatException(CoreChannel.GetResourceString("Remoting_SoapActionMissing"));
            }

            String typeName, methodName;
            if (!SoapServices.GetTypeAndMethodNameFromSoapAction(actionValue, out typeName, out methodName))
            {
                // This means there are multiple methods for this soap action, so we will have to
                // settle for the type based off of the uri.
                Type type = RemotingServices.GetServerTypeForUri(uriValue);
                typeName = type.FullName + ", " + type.Module.Assembly.GetName().Name;
            }

            // BUGBUG: need code to verify soap action after the message has been deserialized.
            //   this will probably be done once we have the new activation scenario working.

            msgHeaders    = new Header[3];
            msgHeaders[0] = new Header("__Uri", uriValue);
            msgHeaders[1] = new Header("__TypeName", typeName);
            msgHeaders[2] = new Header("__MethodName", methodName);

            // Extract the message sequence number field from the
            // mail header
            Field seqField = headers["urn:schemas:mailheader:soapmsgseqnum"];
            if (null == seqField)
            {
                throw new FormatException(CoreChannel.GetResourceString("Remoting_MissingSoapMsgSeqNum"));
            }
            String seqValue = (String)(seqField.Value);
            InternalRemotingServices.RemotingTrace("Guid value " + seqValue);

            return(seqValue);
        }
Ejemplo n.º 17
0
 string GetSoapAction(MethodInfo mb)
 {
     return(SoapServices.GetSoapActionFromMethodBase(mb));
 }
Ejemplo n.º 18
0
        private bool DeserializeMessage(ISoapMessage message)
        {
            string typeNamespace, assemblyName;

            if (xmlReader.Name == SoapTypeMapper.SoapEnvelopePrefix + ":Fault")
            {
                Deserialize();
                return(false);
            }
#if FIXED
            SoapServices.DecodeXmlNamespaceForClrTypeNamespace(
                xmlReader.NamespaceURI,
                out typeNamespace,
                out assemblyName);
#endif

            message.MethodName   = xmlReader.LocalName;
            message.XmlNameSpace = xmlReader.NamespaceURI;

            ArrayList paramNames    = new ArrayList();
            ArrayList paramValues   = new ArrayList();
            long      paramValuesId = NextAvailableId;
            int[]     indices       = new int[1];

            if (!xmlReader.IsEmptyElement)
            {
                int initialDepth = xmlReader.Depth;
                xmlReader.Read();
                int i = 0;
                while (xmlReader.Depth > initialDepth)
                {
                    long   paramId, paramHref;
                    object objParam = null;
                    paramNames.Add(xmlReader.Name);
                    Type paramType = null;

                    if (message.ParamTypes != null)
                    {
                        if (i >= message.ParamTypes.Length)
                        {
                            throw new SerializationException("Not enough parameter types in SoapMessages");
                        }
                        paramType = message.ParamTypes [i];
                    }

                    indices[0] = i;
                    objParam   = DeserializeComponent(
                        paramType,
                        out paramId,
                        out paramHref,
                        paramValuesId,
                        null,
                        indices);
                    indices[0] = paramValues.Add(objParam);
                    if (paramHref != 0)
                    {
                        RecordFixup(paramValuesId, paramHref, paramValues.ToArray(), null, null, null, indices);
                    }
                    else if (paramId != 0)
                    {
//						RegisterObject(paramId, objParam, null, paramValuesId, null, indices);
                    }
                    else
                    {
                    }
                    i++;
                }
                xmlReader.ReadEndElement();
            }
            else
            {
                xmlReader.Read();
            }

            message.ParamNames  = (string[])paramNames.ToArray(typeof(string));
            message.ParamValues = paramValues.ToArray();
            RegisterObject(paramValuesId, message.ParamValues, null, 0, null, null);
            return(true);
        }
Ejemplo n.º 19
0
        public Element GetXmlElement(string typeFullName, string assemblyName)
        {
            Element element;
            string  typeNamespace = string.Empty;
            string  typeName      = typeFullName;

            if (_assemblyFormat == FormatterAssemblyStyle.Simple)
            {
                string[] items = assemblyName.Split(',');
                assemblyName = items[0];
            }
            string assemblyQualifiedName = typeFullName + ", " + assemblyName;

            element = (Element)typeToXmlNodeTable[assemblyQualifiedName];
            if (element == null)
            {
                int typeNameIndex = typeFullName.LastIndexOf('.');
                if (typeNameIndex != -1)
                {
                    typeNamespace = typeFullName.Substring(0, typeNameIndex);
                    typeName      = typeFullName.Substring(typeNamespace.Length + 1);
                }
#if FIXED
                string namespaceURI =
                    SoapServices.CodeXmlNamespaceForClrTypeNamespace(
                        typeNamespace,
                        (!assemblyName.StartsWith("mscorlib")) ? assemblyName : String.Empty);
#else
                string namespaceURI = null;
#endif
                string prefix = (string)namespaceToPrefixTable[namespaceURI];
                if (prefix == null || prefix == string.Empty)
                {
                    prefix = "a" + (_prefixNumber++).ToString();
                    namespaceToPrefixTable[namespaceURI] = prefix;
                }

                int i = typeName.IndexOf("[");
                if (i != -1)
                {
                    typeName = XmlConvert.EncodeName(typeName.Substring(0, i)) + typeName.Substring(i);
                }
                else
                {
                    int j = typeName.IndexOf("&");
                    if (j != -1)
                    {
                        typeName = XmlConvert.EncodeName(typeName.Substring(0, j)) + typeName.Substring(j);
                    }
                    else
                    {
                        typeName = XmlConvert.EncodeName(typeName);
                    }
                }

                element = new Element(
                    prefix,
                    typeName,
                    namespaceURI);
            }
            return(element);
        }