Exemplo n.º 1
0
        public string Handle(string requestBody)
        {
            var reader = new XmlReaderImpl();

            reader.SetString(requestBody);

            var writer = new XmlWriterImpl();

            writer.SetString();

            writer.WriteStartElement("Envelope", xmlns_soap);
            writer.WriteNamespaceMapping("soap", xmlns_soap);
            writer.WriteStartElement("Body", xmlns_soap);

            try
            {
                Handle(reader, writer);
            }
            catch (Exception exc)
            {
                WriteFault(writer, exc.Message);
            }

            writer.WriteEndElement();              // Body
            writer.WriteEndElement();              // Envelope

            var responseText = writer.Close().AsString();

            return(responseText);
        }
Exemplo n.º 2
0
        public void TestUnnamedComplexType()
        {
            var ss        = LoadSchema(@"TestData/Schema01.xsd");
            var f         = new XdtoFactory(ss);
            var t         = f.Type(uri: "unnamedComplexType", name: "TheComplexType") as XdtoObjectType;
            var v         = f.Create(t) as XdtoDataObject;
            var p         = t.Properties.Get("Element");
            var pv        = f.Create(p.Type) as XdtoDataObject;
            var var1Value = f.Create(f.Type(XmlNs.xs, "string"), ValueFactory.Create("value of var1"));

            pv.Set("var1", ValueFactory.Create(var1Value));

            v.Set("Element", pv);

            var w = new XmlWriterImpl();

            w.SetString();

            f.WriteXml(w, v, "value");

            var serialized = w.Close().AsString();

            Console.WriteLine(serialized);

            var r = new XmlReaderImpl();

            r.SetString(serialized);

            var checkObject = f.ReadXml(r) as XdtoDataObject;
            var checkValue  = (checkObject.Get("Element") as XdtoDataObject).Get("var1").AsString();

            Console.WriteLine($"got {checkValue}");
        }
Exemplo n.º 3
0
        public IXdtoValue ReadXml(XmlReaderImpl reader, IXdtoType expectedType, XdtoFactory factory)
        {
            var lexicalValue = reader.Value;
            var value        = ValueFactory.Create(lexicalValue);

            return(new XdtoDataValue(expectedType as XdtoValueType, lexicalValue, value));
        }
Exemplo n.º 4
0
        public IXdtoValue ReadXml(XmlReaderImpl reader, IXdtoType type, XdtoFactory factory)
        {
            var lexicalValue  = reader.Value;
            var internalValue = ValueFactory.Create(lexicalValue);

            return(new XdtoDataValue(this, lexicalValue, internalValue));
        }
Exemplo n.º 5
0
 /// <summary>
 /// Reads specified object from given xml string.
 /// </summary>
 /// <typeparam name="T">The object type.</typeparam>
 /// <param name="schema">Serialization schema.</param>
 /// <param name="xml">The xml string to parse.</param>
 /// <param name="obj">The object to deserialize.</param>
 public static void ReadXmlString <T>(this IScope schema, string xml, T obj)
 {
     using (var input = new StringReader(xml))
         using (var reader = XmlReaderImpl.Create(input))
         {
             Read(schema, reader, obj);
         }
 }
Exemplo n.º 6
0
        public IXdtoValue ReadXml(XmlReaderImpl reader, IXdtoType expectedType, XdtoFactory factory)
        {
            var lexicalValue     = reader.Value;
            var xmlDateTimeValue = XmlConvert.ToDateTime(lexicalValue, XmlDateTimeSerializationMode.Unspecified);
            var value            = ValueFactory.Create(xmlDateTimeValue);

            return(new XdtoDataValue(expectedType as XdtoValueType, lexicalValue, value));
        }
Exemplo n.º 7
0
        public IValue ReadXml(XmlReaderImpl reader, TypeTypeValue requestedType = null)
        {
            var xdtoValue = XdtoFactory.ReadXml(reader);

            if (xdtoValue is IXdtoValue)
            {
                return(ReadXdto(xdtoValue as IXdtoValue));
            }

            return(xdtoValue);
        }
Exemplo n.º 8
0
        public void Handle(XmlReaderImpl requestReader,
                           XmlWriterImpl responseWriter)
        {
            var F            = new XdtoFactory();
            var S            = XdtoSerializerImpl.Constructor(ValueFactory.Create(F)) as XdtoSerializerImpl;
            var inputMessage = F.ReadXml(requestReader) as XdtoDataObject;
            var body         = inputMessage.Get("Body") as XdtoDataObject;

            var requestProperty = body.Properties().Get(0);
            var methodName      = requestProperty.LocalName;

            if (!operations.ContainsKey(methodName))
            {
                // TODO: SoapException
                throw new RuntimeException($"method not found {methodName}");
            }

            var op = operations[methodName];

            // TODO: отдать разбор в операцию
            var args       = new List <IValue>();
            var callParams = body.Get(body.Properties().Get(0)) as XdtoDataObject;

            foreach (var pv in callParams.Properties())
            {
                var paramName = pv.LocalName;
                var p         = op.Parameters.Get(paramName);
                var xdtoValue = callParams.GetXdto(pv);
                var ivalue    = S.ReadXdto(xdtoValue);

                if (p.ParameterDirection != ParameterDirectionEnum.In)
                {
                    ivalue = Variable.Create(ivalue, paramName);
                }
                args.Add(ivalue);
            }

            var    handler   = operationsMapper[op];
            var    methodIdx = handler.FindMethod(methodName);
            var    mi        = handler.GetMethodInfo(methodIdx);
            IValue result    = null;

            if (mi.IsFunction)
            {
                handler.CallAsFunction(methodIdx, args.ToArray(), out result);
            }
            else
            {
                handler.CallAsProcedure(methodIdx, args.ToArray());
            }

            op.WriteResponseBody(responseWriter, S, result, args.ToArray());
        }
Exemplo n.º 9
0
        public static IReader CreateReader(TextReader input, Format format, XNamespace rootNamespace)
        {
            switch (format)
            {
            case Format.Xml:
                return(XmlReaderImpl.Create(input));

#if FULL
            case Format.Json:
                return(JsonReaderImpl.Create(rootNamespace, input));

            case Format.JsonML:
                return(JsonMLReader.Create(input));
#endif
            default:
                throw new NotSupportedException("format");
            }
        }
Exemplo n.º 10
0
        public void TestXdto()
        {
            const string anyXml = @"<number>1</number>";
            var          reader = XmlReaderImpl.Create() as XmlReaderImpl;

            reader.SetString(anyXml);

            var factory      = XdtoFactory.Constructor() as XdtoFactory;
            var expectedType = factory.Type(new XmlDataType("int"));
            var anyValue     = factory.ReadXml(reader, expectedType) as XdtoDataValue;

            if (anyValue == null)
            {
                throw new Exception("XDTO не разобрался!");
            }

            var writer = XmlWriterImpl.Create() as XmlWriterImpl;

            writer.SetString();

            factory.WriteXml(writer, anyValue, "number");
            var serializedResult = writer.Close().AsString();

            Console.WriteLine("Original : {0}", anyXml);
            Console.WriteLine("Generated: {0}", serializedResult);

            reader = XmlReaderImpl.Create() as XmlReaderImpl;
            reader.SetString(serializedResult);

            var anyValueTypeExtraction = factory.ReadXml(reader) as XdtoDataValue;

            if (anyValueTypeExtraction == null)
            {
                throw new Exception("Новый XDTO не разобрался!");
            }
            Console.WriteLine("Serialized:{0}", anyValueTypeExtraction.Value);
        }
Exemplo n.º 11
0
        public void TestWsdl()
        {
            // var def = new Definitions("http://vm21297.hv8.ru:10080/httpservice/ws/complex.1cws?wsdl", "default");
            var def = new Definitions(@"D:\temp\Bases1C.wsdl", "default");

            Console.WriteLine("Def has {0} services.", def.Services.Count());
            foreach (var service in def.Services)
            {
                Console.WriteLine("\tService {0} has {1} endpoints", service.Name, service.Endpoints.Count());
                foreach (var endpoint in service.Endpoints)
                {
                    Console.WriteLine("\t\tEndpoint {0} as {1} operations", endpoint.Name, endpoint.Interface.Operations.Count());
                    foreach (var operation in endpoint.Interface.Operations)
                    {
                        Console.WriteLine("\t\t\tOperation {0}", operation.Name);
                    }
                }
            }

            var proxy = Proxy.Constructor(def, "http://xfit.local/1C/Bases1C", "Bases1C", "Bases1CSoap") as Proxy;

            proxy.User = "******";
            var methodIndex = proxy.FindMethod("getBasesList");

            Console.WriteLine($"Method `getBasesList` is {methodIndex}");

            var responseType = proxy.XdtoFactory.Type("http://xfit.local/1C/Bases1C", "getBasesListResponse");

            var xri = new XmlReaderImpl();

            xri.OpenFile(@"D:\temp\testresponse.xml");
            xri.Read();
            xri.Read();
            xri.Read();

            var response = proxy.XdtoFactory.ReadXml(xri, responseType);
        }
Exemplo n.º 12
0
        public IValue ReadXml(XmlReaderImpl reader, IXdtoType type = null)
        {
            if (reader.MoveToContent() == null)
            {
                // TODO: бросить исключение??
                return(null);
            }
            if (type == null)
            {
                var explicitType = reader.GetAttribute(ValueFactory.Create("type"), XmlNs.xsi);
                if (explicitType.DataType == DataType.Undefined)
                {
                    type = new XdtoObjectType();
                }
                else
                {
                    var defaultNamespace = reader.NamespaceContext.DefaultNamespace;

                    // Задан тип - пытаемся его распознать
                    var sType        = explicitType.AsString();
                    var nameElements = sType.Split(':');

                    var typeUri = nameElements.Count() > 1
                                                                  ? nameElements [0]
                                                                  : defaultNamespace;
                    var typeName = nameElements.Count() > 1
                                                                  ? nameElements [1]
                                                                  : nameElements [0];

                    var nsMapping = reader.NamespaceContext.LookupNamespaceUri(typeUri);
                    if (nsMapping != null && nsMapping.DataType == DataType.String)
                    {
                        typeUri = nsMapping.AsString();
                    }

                    type = this.Type(typeUri, typeName);
                }
            }

            if (type is XdtoObjectType)
            {
                return(ValueFactory.Create(type.Reader.ReadXml(reader, type, this)));
            }

            var xmlNodeTypeEnum = XmlNodeTypeEnum.CreateInstance();
            var xmlElementStart = xmlNodeTypeEnum.FromNativeValue(XmlNodeType.Element);
            var xmlElementEnd   = xmlNodeTypeEnum.FromNativeValue(XmlNodeType.EndElement);

            if (type is XdtoValueType)
            {
                if (reader.NodeType.Equals(xmlElementStart))
                {
                    reader.Read();
                }
                var result = type.Reader.ReadXml(reader, type, this);
                if (!reader.NodeType.Equals(xmlElementEnd))
                {
                    reader.Skip();
                }

                var pd = new PrimitiveValuesSerializer();
                return(pd.DeserializeXdto(result));
            }

            throw new NotSupportedException("Неожиданный тип XDTO!");
        }
Exemplo n.º 13
0
        public IXdtoValue ReadXml(XmlReaderImpl reader, IXdtoType expectedType, XdtoFactory factory)
        {
            // TODO: дублирование кода в трёх ветках

            var result = new XdtoDataObject(this, null, null);

            // TODO: Перевести XML на простые перечисления
            var xmlNodeTypeEnum = XmlNodeTypeEnum.CreateInstance();
            var xmlElementStart = xmlNodeTypeEnum.FromNativeValue(System.Xml.XmlNodeType.Element);
            var xmlText         = xmlNodeTypeEnum.FromNativeValue(System.Xml.XmlNodeType.Text);
            var xmlElementEnd   = xmlNodeTypeEnum.FromNativeValue(System.Xml.XmlNodeType.EndElement);

            while (reader.ReadAttribute())
            {
                if (reader.NamespaceURI.Equals("http://www.w3.org/2000/xmlns/") ||
                    reader.NamespaceURI.Equals(XmlNs.xsi) && reader.LocalName.Equals("type"))
                {
                    continue;
                }
                var propertyName       = reader.LocalName;
                var attributeNamespace = reader.NamespaceURI;
                var attributeProperty  =
                    AllProperties().FirstOrDefault(p => p.Form == XmlFormEnum.Attribute &&
                                                   p.LocalName.Equals(propertyName) &&
                                                   p.NamespaceURI.Equals(attributeNamespace));

                if (attributeProperty == null)
                {
                    if (!Open)
                    {
                        throw new XdtoException($"Ошиба разбора XDTO: Получили неизвестный атрибут {propertyName}");
                    }
                    var type = factory.Type(new XmlDataType("string"));
                    attributeProperty = new XdtoProperty(null, result, XmlFormEnum.Attribute,
                                                         NamespaceUri, propertyName,
                                                         1, -1, type); // TODO: lower / upper для открытого типа
                }

                var attributeValue = attributeProperty.Type.Reader.ReadXml(reader, attributeProperty.Type, factory);
                result.Set(attributeProperty, ValueFactory.Create(attributeValue));
            }

            while (reader.Read())
            {
                if (reader.NodeType.Equals(xmlElementEnd))
                {
                    // TODO: result.Validate()
                    return(result);
                }

                if (reader.NodeType.Equals(xmlText))
                {
                    // надо найти свойство с Form=Text
                    // оно должно быть одно

                    var       textProperty = AllProperties().FirstOrDefault((p) => p.Form == XmlFormEnum.Text);
                    IXdtoType type;
                    IValue    textValue;
                    if (textProperty == null)
                    {
                        if (!Open)
                        {
                            throw new XdtoException($"Ошибка разбора XDTO: Текст {reader.Value} в неположенном месте при разборе типа {this}!");
                        }

                        textProperty = new XdtoProperty(null, result, XmlFormEnum.Text, NamespaceUri, "#text");
                        type         = factory.Type(new XmlDataType("string"));
                        textValue    = ValueFactory.Create(reader.Value);
                    }
                    else
                    {
                        type      = textProperty.Type;
                        textValue = ValueFactory.Create(type.Reader.ReadXml(reader, type, factory));
                    }

                    if (Sequenced)
                    {
                        result.Sequence().Add(textValue.AsString());
                    }
                    else
                    {
                        result.Set(textProperty, textValue);
                    }
                }
                else if (reader.NodeType.Equals(xmlElementStart))
                {
                    var localName = reader.LocalName;
                    var ns        = reader.NamespaceURI;

                    var property = AllProperties().FirstOrDefault((p) => p.LocalName.Equals(localName) &&
                                                                  p.NamespaceURI.Equals(ns) &&
                                                                  p.Form == XmlFormEnum.Element);
                    if (property == null)
                    {
                        if (!Open)
                        {
                            throw new XdtoException($"Ошибка разбора XDTO: Получили неизвестный элемент {localName}");
                        }

                        // TODO: lower / upper для открытого типа
                        property = new XdtoProperty(null, result, XmlFormEnum.Element, ns, localName, 1, 1);
                    }

                    var elementValue = factory.ReadXml(reader, property.Type);

                    // TODO: Разбор anyType
                    if (property.UpperBound != 1)
                    {
                        // TODO: проверка на null - на отсутствие/наличие списка
                        (result.GetList(property) as XdtoList).Add(elementValue);
                    }
                    else
                    {
                        result.Set(property, elementValue);
                    }
                }
            }

            throw new XdtoException("Ошибка разбора XDTO!");
        }
Exemplo n.º 14
0
        public IParsedResponse ParseResponse(XmlReaderImpl reader, XdtoSerializerImpl serializer)
        {
            var retValue     = ValueFactory.Create();
            var outputParams = new Dictionary <int, IValue> ();

            var xmlNodeTypeEnum = XmlNodeTypeEnum.CreateInstance();
            var xmlElementStart = xmlNodeTypeEnum.FromNativeValue(System.Xml.XmlNodeType.Element);

            if (!reader.Read() ||
                !reader.LocalName.Equals("Envelope") ||
                !reader.NodeType.Equals(xmlElementStart)
                // TODO: перевести XML на простые перечисления
                )
            {
                return(new SoapExceptionResponse("Wrong response!"));
            }

            reader.MoveToContent();

            if (!reader.Read() ||
                !reader.LocalName.Equals("Body") ||
                !reader.NodeType.Equals(xmlElementStart)
                // TODO: перевести XML на простые перечисления
                )
            {
                return(new SoapExceptionResponse("Wrong response!"));
            }

            if (!reader.Read())
            {
                return(new SoapExceptionResponse("Wrong response!"));
            }

            if (reader.LocalName.Equals("Fault") &&
                reader.NodeType.Equals(xmlElementStart))
            {
                reader.Read();
                while (!(reader.LocalName.Equals("faultString") &&
                         reader.NodeType.Equals(xmlElementStart)))
                {
                    if (!reader.Read())
                    {
                        return(new SoapExceptionResponse("Wrong response!"));
                    }
                }
                reader.Read();
                var faultString = reader.Value;
                return(new SoapExceptionResponse(faultString));
            }

            var xdtoResult = serializer.XdtoFactory.ReadXml(reader, ReturnValue.ResponseType ?? ReturnValue.Type) as XdtoDataObject;

            retValue = xdtoResult.Get("return");

            if (retValue is IXdtoValue)
            {
                retValue = serializer.ReadXdto(retValue as IXdtoValue);
            }

            foreach (var param in Parameters)
            {
                if (param.ParameterDirection == ParameterDirectionEnum.In)
                {
                    continue;
                }

                var    argumentIndex = _indexes [param.Name];
                IValue paramValue    = xdtoResult.Get(param.Name);
                if (paramValue is IXdtoValue)
                {
                    paramValue = serializer.ReadXdto(paramValue as IXdtoValue);
                }
                outputParams.Add(argumentIndex, paramValue);
            }

            return(new SuccessfulSoapResponse(retValue, outputParams));
        }
Exemplo n.º 15
0
        public override void CallAsFunction(int methodNumber, IValue [] arguments, out IValue retValue)
        {
            var operation = _operations [methodNumber];

            retValue = ValueFactory.Create();

            ConnectIfNeeded();

            var headers = new MapImpl();

            headers.Insert(ValueFactory.Create("Content-Type"), ValueFactory.Create("application/xml"));

            var xmlBody = XmlWriterImpl.Create();

            xmlBody.SetString(ValueFactory.Create("UTF-8"));

            xmlBody.WriteStartElement("soap:Envelope");
            xmlBody.WriteNamespaceMapping("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xmlBody.WriteNamespaceMapping("xsd", "http://www.w3.org/2001/XMLSchema");
            xmlBody.WriteNamespaceMapping("soap", "http://schemas.xmlsoap.org/soap/envelope/");
            xmlBody.WriteNamespaceMapping("s", Endpoint.Interface.NamespaceURI);

            xmlBody.WriteStartElement("soap:Body");

            var serializer = XdtoSerializerImpl.Constructor(XdtoFactory) as XdtoSerializerImpl;

            operation.WriteRequestBody(xmlBody, serializer, arguments);

            xmlBody.WriteEndElement();              // soap:Body
            xmlBody.WriteEndElement();              // soap:Envelope

            var requestString = xmlBody.Close().ToString();

            if (DoDebug)
            {
                Console.WriteLine(requestString);
            }

            var responseText = _transport.Handle(requestString);
            var xmlResult    = XmlReaderImpl.Create() as XmlReaderImpl;

            if (DoDebug)
            {
                Console.WriteLine(responseText);
            }

            // TODO: Отдать на разбор фабрике
            xmlResult.SetString(responseText);

            var result = operation.ParseResponse(xmlResult, serializer);

            if (result is SoapExceptionResponse)
            {
                throw new ScriptEngine.Machine.RuntimeException((result as SoapExceptionResponse).FaultMessage);
            }

            var soapResponse = result as SuccessfulSoapResponse;

            retValue = soapResponse.RetValue;

            foreach (var outParamData in soapResponse.OutputParameters)
            {
                var argument = arguments [outParamData.Key] as IVariable;
                if (argument == null)
                {
                    continue;
                }

                argument.Value = outParamData.Value;
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Reads object with given reader.
 /// </summary>
 /// <typeparam name="T">The object type.</typeparam>
 /// <param name="schema">Serialization schema.</param>
 /// <param name="reader">The xml reader.</param>
 public static T Read <T>(this IScope schema, XmlReader reader)
 {
     using (var impl = XmlReaderImpl.Create(reader))
         return(Read <T>(schema, impl));
 }
Exemplo n.º 17
0
 /// <summary>
 /// Reads specified object with given reader.
 /// </summary>
 /// <typeparam name="T">The object type.</typeparam>
 /// <param name="schema">Serialization schema.</param>
 /// <param name="reader">The xml reader.</param>
 /// <param name="obj">The object to deserialize.</param>
 public static void Read <T>(this IScope schema, XmlReader reader, T obj)
 {
     using (var impl = XmlReaderImpl.Create(reader))
         Read(schema, impl, obj);
 }
Exemplo n.º 18
0
        public IValue ReadXML(XmlReaderImpl xmlReader, IValue valueType = null)
        {
            TypeTypeValue typeValue = null;

            if (valueType is TypeTypeValue typeTypeValue)
            {
                typeValue = typeTypeValue;
            }

            else if (xmlReader.NodeType == xmlNodeEnum.FromNativeValue(XmlNodeType.Element))
            {
                IValue xsiType = xmlReader.GetAttribute(ValueFactory.Create("type"), XmlSchema.InstanceNamespace);
                IValue xsiNil  = xmlReader.GetAttribute(ValueFactory.Create("nil"), XmlSchema.InstanceNamespace);

                if (xsiType.DataType == DataType.String)
                {
                    switch (xsiType.AsString())
                    {
                    case "string":
                        typeValue = new TypeTypeValue("String");
                        break;

                    case "decimal":
                        typeValue = new TypeTypeValue("Number");
                        break;

                    case "boolean":
                        typeValue = new TypeTypeValue("Boolean");
                        break;

                    case "dateTime":
                        typeValue = new TypeTypeValue("Date");
                        break;

                    default:
                        break;
                    }
                }
                else if (xsiNil.DataType == DataType.String)
                {
                    typeValue = new TypeTypeValue("Undefined");
                }
            }
            ;

            if (typeValue == null)
            {
                throw RuntimeException.InvalidArgumentValue();
            }

            Type implType = TypeManager.GetImplementingClass(typeValue.Value.ID);

            IValue result = ValueFactory.Create();

            if (typeValue.Equals(new TypeTypeValue("Undefined")))
            {
                result = ValueFactory.Create();
                xmlReader.Skip();
            }
            else if (implType == typeof(DataType))
            {
                xmlReader.Read();
                if (xmlReader.NodeType == xmlNodeEnum.FromNativeValue(XmlNodeType.Text))
                {
                    result = XMLValue(typeValue, xmlReader.Value);
                    xmlReader.Read();
                }
                else
                {
                    throw RuntimeException.InvalidArgumentValue();
                }
            }
            else if (typeof(IXDTOSerializableXML).IsAssignableFrom(implType))
            {
                result = Activator.CreateInstance(implType, new object[] { xmlReader, this }) as IValue;
            }

            xmlReader.Read();
            return(result);
        }