예제 #1
0
        public void CommitPartition(MapImpl offset)
        {
            var consumer = consumerAsync;

            var topicFix = offset.Retrieve(
                ValueFactory.Create("Канал")).AsString();
            var partFix = (int)offset.Retrieve(
                ValueFactory.Create("Раздел")).AsNumber();
            var offsetFix = (int)offset.Retrieve(
                ValueFactory.Create("Смещение")).AsNumber();

            TopicPartitionOffset[] topicsCommit =
            {
                new TopicPartitionOffset(
                    topicFix,
                    partFix,
                    offsetFix
                    )
            };

            var commiterList = new List <TopicPartitionOffset>();

            consumer.Commit(
                new List <TopicPartitionOffset>(topicsCommit)
                );
        }
예제 #2
0
        public ScriptedController(ControllerContext context, LoadedModule module) : base(module, true)
        {
            _ctx         = context;
            HttpRequest  = new HttpRequestImpl(_ctx.HttpContext.Request);
            HttpResponse = new HttpResponseImpl(_ctx.HttpContext.Response);

            if (_ctx.RouteData != null)
            {
                RouteValues = new MapImpl();
                foreach (var routeData in _ctx.RouteData.Values)
                {
                    var rv = RouteValues.AsObject();
                    rv.SetIndexedValue(
                        ValueFactory.Create(routeData.Key),
                        CustomMarshaller.ConvertToIValueSafe(routeData.Value, routeData.Value?.GetType())
                        );
                }
            }
            else
            {
                RouteValues = ValueFactory.Create();
            }

            var typeClr = (Type)context.ActionDescriptor.Properties["type"];
            var type    = TypeManager.RegisterType("Контроллер." + typeClr.Name, typeof(ScriptedController));

            DefineType(type);
            InitOwnData();
        }
예제 #3
0
        public HTTPServiceRequestImpl(System.Web.HttpContext ctx)
        {
            _httpContext = ctx;
            // Инициализируем объект для 1С
            // Заголовки
            MapImpl headers = new MapImpl();

            for (int i = 0; i < _httpContext.Request.Headers.Count; i++)
            {
                headers.Insert(ValueFactory.Create(_httpContext.Request.Headers.GetKey(i))
                               , ValueFactory.Create(_httpContext.Request.Headers.Get(i))
                               );
            }

            this._headers = new FixedMapImpl(headers);

            // ПараметрыURL будут пустыми
            _urlParams = new FixedMapImpl(new MapImpl());

            // Параметры запроса
            MapImpl queryOptions = new MapImpl();

            for (int i = 0; i < _httpContext.Request.Params.Count; i++)
            {
                queryOptions.Insert(ValueFactory.Create(_httpContext.Request.Params.GetKey(i))
                                    , ValueFactory.Create(_httpContext.Request.Params.Get(i))
                                    );
            }

            _queryOptions = new FixedMapImpl(queryOptions);

            _context = new HTTPServiceContextImpl(_httpContext);
        }
예제 #4
0
        public PostRequestData(string data)
        {
            MapImpl m_params = new MapImpl();

            var pairs = data.Split('&');

            foreach (var pair in pairs)
            {
                var nameVal = pair.Split(new Char[] { '=' }, 2);
                if (nameVal.Length == 2)
                {
                    IValue key = ValueFactory.Create(Decode(nameVal[0]));
                    IValue val = ValueFactory.Create(Decode(nameVal[1]));
                    m_params.Insert(key, val);
                }
                else if (pair.Length > 0)
                {
                    IValue val = ValueFactory.Create(Decode(pair));
                    m_params.Insert(val, ValueFactory.Create());
                }

                _params = new FixedMapImpl(m_params);
                _files  = new FixedMapImpl(new MapImpl());
            }
        }
        /// <summary>
        /// Строит объекты OneScript на основе результатов парсинга
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        private IValue BuildResults(object source)
        {
            if (source == null)
            {
                return(ValueFactory.Create());
            }

            if (source is List <object> )
            {
                ArrayImpl array = new ArrayImpl();

                foreach (object element in (List <object>)source)
                {
                    array.Add(BuildResults(element));
                }

                return(array);
            }

            if (source is Dictionary <object, object> )
            {
                MapImpl map = new MapImpl();

                foreach (var element in (Dictionary <object, object>)source)
                {
                    map.Insert(BuildResults(element.Key), BuildResults(element.Value));
                }

                return(map);
            }

            if (source is bool)
            {
                return(ValueFactory.Create(System.Convert.ToBoolean(source)));
            }

            if (source is sbyte ||
                source is byte ||
                source is short ||
                source is ushort ||
                source is int ||
                source is uint ||
                source is long ||
                source is ulong ||
                source is float ||
                source is double ||
                source is decimal
                )
            {
                return(ValueFactory.Create(System.Convert.ToDecimal(source)));
            }

            if (source is DateTime)
            {
                return(ValueFactory.Create(System.Convert.ToDateTime(source)));
            }

            // Строка или нечто другое
            return(ValueFactory.Create(System.Convert.ToString(source)));
        }
예제 #6
0
        private void OnContextChange()
        {
            HttpRequest  = new HttpRequestImpl(ComponentContext.ViewContext.HttpContext.Request);
            HttpResponse = new HttpResponseImpl(ComponentContext.ViewContext.HttpContext.Response);
            ViewData     = new ViewDataDictionaryWrapper(ComponentContext.ViewData);

            var routeData = _ctx.ViewContext.RouteData;

            if (routeData != null)
            {
                RouteValues = new MapImpl();
                var rv = RouteValues.AsObject();
                foreach (var routeValue in routeData.Values)
                {
                    rv.SetIndexedValue(
                        ValueFactory.Create(routeValue.Key),
                        CustomMarshaller.ConvertToIValueSafe(routeValue.Value, routeValue.Value.GetType())
                        );
                }
            }
            else
            {
                RouteValues = ValueFactory.Create();
            }
        }
예제 #7
0
        private void UpdateHeaders()
        {
            var mapHdrs = new MapImpl();

            foreach (var realObjectHeader in _realObject.Headers)
            {
                mapHdrs.SetIndexedValue(ValueFactory.Create(realObjectHeader.Key), ValueFactory.Create(realObjectHeader.Value));
            }
            Headers = new FixedMapImpl(mapHdrs);
        }
예제 #8
0
        public HttpRequestImpl(HttpRequest request)
        {
            _realObject = request;
            var mapHdrs = new MapImpl();

            foreach (var realObjectHeader in _realObject.Headers)
            {
                mapHdrs.SetIndexedValue(ValueFactory.Create(realObjectHeader.Key), ValueFactory.Create(realObjectHeader.Value));
            }
            Headers = new FixedMapImpl(mapHdrs);
        }
        public void Add(string name, string template, MapImpl defaults = null)
        {
            var route = new RouteDescriptionContext()
            {
                Name     = name,
                Template = template,
                Defaults = defaults
            };

            _routes.Add(route);
        }
        public MapImpl NamespaceMappings()
        {
            var result = MapImpl.Constructor() as MapImpl;

            foreach (var data in _nsmap)
            {
                result.Insert(ValueFactory.Create(data.Key), ValueFactory.Create(data.Value));
            }

            return(result);
        }
예제 #11
0
        public MapImpl QueryParameters()
        {
            MapImpl result = new MapImpl();

            foreach (var kv in _realObject.Query)
            {
                result.Insert(ValueFactory.Create(kv.Key),
                              ValueFactory.Create(kv.Value));
            }

            return(result);
        }
예제 #12
0
        private void FillEnvironmentVars()
        {
            MapImpl vars = new MapImpl();

            foreach (DictionaryEntry item in Environment.GetEnvironmentVariables())
            {
                vars.Insert(
                    ValueFactory.Create((string)item.Key),
                    ValueFactory.Create((string)item.Value));
            }

            _environmentVars = new FixedMapImpl(vars);
        }
예제 #13
0
        public IValue Consume(int WaitTime = 1000)
        {
            var consumer = consumerAsync;

            while (true)
            {
                try
                {
                    var consumeResult = consumer.Consume(WaitTime);
                    if (consumeResult != null)
                    {
                        if (consumeResult.IsPartitionEOF)
                        {
                            Console.WriteLine($"Reached end of topic {consumeResult.Topic}, partition {consumeResult.Partition}, offset {consumeResult.Offset}.");
                            return(ValueFactory.Create());
                        }

                        var obj = new MapImpl();

                        latestOffset = obj;

                        obj.Insert(
                            ValueFactory.Create("Канал"), ValueFactory.Create(
                                consumeResult.TopicPartitionOffset.Topic
                                )
                            );

                        obj.Insert(
                            ValueFactory.Create("Раздел"), ValueFactory.Create(
                                consumeResult.TopicPartitionOffset.Partition
                                )
                            );

                        obj.Insert(
                            ValueFactory.Create("Смещение"), ValueFactory.Create(
                                consumeResult.TopicPartitionOffset.Offset
                                )
                            );

                        return(ValueFactory.Create(consumeResult.Message.Value));
                    }
                } catch (ConsumeException e)
                {
                    throw new Exception(
                              $"Error occured: {e.Error.Reason}"
                              );
                }
            }
        }
예제 #14
0
        private void UpdateCookies()
        {
            var cookieMap = new MapImpl();

            if (_realObject.Cookies != null)
            {
                foreach (var cookie in _realObject.Cookies)
                {
                    cookieMap.SetIndexedValue(ValueFactory.Create(cookie.Key),
                                              ValueFactory.Create(cookie.Value));
                }
            }

            Cookies = new FixedMapImpl(cookieMap);
        }
        public void ContentTypeIsReflectedInHeadersAfterSetHeaders()
        {
            var response = MockRequestClass();

            var headers = new MapImpl();

            headers.SetIndexedValue(ValueFactory.Create("Content-Type"), ValueFactory.Create("text/plain"));

            var scriptRequest = new HttpResponseImpl(response);

            scriptRequest.SetHeaders(headers);
            Assert.Equal("text/plain", scriptRequest.Headers.GetIndexedValue(ValueFactory.Create("Content-Type")).AsString());
            Assert.Equal("text/plain", scriptRequest.RealObject.Headers["Content-Type"]);
            Assert.Equal("text/plain", scriptRequest.RealObject.ContentType);
        }
예제 #16
0
        public FormFileContext(IFormFile realObject)
        {
            _realObject = realObject;

            _headers = new Lazy <FixedMapImpl>(() =>
            {
                var mapHdrs = new MapImpl();
                foreach (var realObjectHeader in _realObject.Headers)
                {
                    mapHdrs.SetIndexedValue(ValueFactory.Create(realObjectHeader.Key), ValueFactory.Create(realObjectHeader.Value));
                }
                return(new FixedMapImpl(mapHdrs));
            }
                                               );
        }
예제 #17
0
        public MapImpl QueryParameters()
        {
            var result = new MapImpl();

            foreach (var(key, value) in _realObject.Query)
            {
                var valueToInsert = value.Count > 1 ?
                                    new ArrayImpl(value.Select(ValueFactory.Create)) :
                                    ValueFactory.Create(value);

                result.Insert(
                    ValueFactory.Create(key),
                    valueToInsert);
            }

            return(result);
        }
예제 #18
0
        public void ContentTypeIsReflectedInHeadersAfterSetHeaders()
        {
            lock (TestOrderingLock.Lock)
            {
                var se       = new MinimalTypeSystemHack();
                var context  = new DefaultHttpContext();
                var response = new DefaultHttpResponse(context);

                var headers = new MapImpl();
                headers.SetIndexedValue(ValueFactory.Create("Content-Type"), ValueFactory.Create("text/plain"));

                var scriptRequest = new HttpResponseImpl(response);
                scriptRequest.SetHeaders(headers);
                Assert.True(scriptRequest.Headers.GetIndexedValue(ValueFactory.Create("Content-Type")).AsString().Equals("text/plain"));
                Assert.Equal("text/plain", scriptRequest.RealObject.Headers["Content-Type"]);
                Assert.Equal("text/plain", scriptRequest.RealObject.ContentType);
            }
        }
예제 #19
0
        public void ResponseHeadersCanBeSetFrom_MapImpl()
        {
            var response = new Mock <HttpResponse>();
            var headers  = new MapImpl();

            headers.SetIndexedValue(ValueFactory.Create("Content-Length"), ValueFactory.Create("123456"));
            headers.SetIndexedValue(ValueFactory.Create("Content-Encoding"), ValueFactory.Create("utf-8"));

            var testedHeaders = new HeaderDictionary();

            response.SetupGet(x => x.Headers).Returns(testedHeaders);

            var scriptRequest = new HttpResponseImpl(response.Object);

            scriptRequest.SetHeaders(headers);

            Assert.Equal(testedHeaders["Content-Length"], "123456");
            Assert.Equal(testedHeaders["Content-Encoding"], "utf-8");
        }
예제 #20
0
        private void ParseFormData(string data, MapImpl map)
        {
            var pairs = data.Split('&');

            foreach (var pair in pairs)
            {
                var nameVal = pair.Split(new Char[] { '=' }, 2);
                if (nameVal.Length == 2)
                {
                    IValue key = ValueFactory.Create(nameVal[0]);
                    IValue val = ValueFactory.Create(Decode(nameVal[1]));
                    map.Insert(key, val);
                }
                else if (pair.Length > 0)
                {
                    IValue val = ValueFactory.Create(Decode(pair));
                    map.Insert(val, ValueFactory.Create());
                }
            }
        }
예제 #21
0
        public string Handle(string requestBody)
        {
            var headers = new MapImpl();

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

            var request = HttpRequestContext.Constructor(ValueFactory.Create(Path), headers);

            request.SetBodyFromString(requestBody);

            var httpResponse = Connection.Post(request);

            if (httpResponse.StatusCode != 200)
            {
                throw new HttpTransportException(httpResponse);
            }

            var stringResponse = httpResponse.GetBodyAsString(ValueFactory.Create("UTF-8")).AsString();

            return(stringResponse);
        }
예제 #22
0
        public HTTPServiceRequestImpl(System.Web.HttpContext ctx)
        {
            _httpContext = ctx;
            // Инициализируем объект для 1С
            // Заголовки
            MapImpl headers = new MapImpl();

            for (int i = 0; i < _httpContext.Request.Headers.Count; i++)
            {
                headers.Insert(ValueFactory.Create(_httpContext.Request.Headers.GetKey(i))
                               , ValueFactory.Create(_httpContext.Request.Headers.Get(i))
                               );
            }

            this._headers = new FixedMapImpl(headers);

            // ПараметрыURL будут пустыми
            _urlParams = new FixedMapImpl(new MapImpl());

            // Параметры запроса
            MapImpl queryOptions = new MapImpl();

            // Изменено для совместимости. в 1С только параметры командной строки
            // Надо перенести в Контекст
            //for (int i = 0; i < _httpContext.Request.Params.Count; i++)
            //    queryOptions.Insert(ValueFactory.Create(_httpContext.Request.Params.GetKey(i))
            //                       , ValueFactory.Create(_httpContext.Request.Params.Get(i))
            //                       );
            for (int i = 0; i < _httpContext.Request.QueryString.Count; i++)
            {
                queryOptions.Insert(ValueFactory.Create(_httpContext.Request.QueryString.GetKey(i))
                                    , ValueFactory.Create(_httpContext.Request.QueryString.Get(i))
                                    );
            }

            _queryOptions = new FixedMapImpl(queryOptions);

            _context = new HTTPServiceContextImpl(_httpContext);
        }
예제 #23
0
        public PostRequestData(byte [] buffer, string boundary)
        {
            using (var stdin = new MemoryStream(buffer))
            {
                var     parser   = new MultipartFormDataParser(stdin, boundary, Encoding.UTF8);
                MapImpl m_params = new MapImpl();
                foreach (var param in parser.Parameters)
                {
                    m_params.Insert(ValueFactory.Create(param.Name), ValueFactory.Create(param.Data));
                }
                _params = new FixedMapImpl(m_params);

                MapImpl m_files = new MapImpl();
                foreach (var file in parser.Files)
                {
                    m_files.Insert(
                        ValueFactory.Create(file.Name),
                        ValueFactory.Create(new PostFileDescription(file))
                        );
                }
                _files = new FixedMapImpl(m_files);
            }
        }
예제 #24
0
        public void MapPresentation()
        {
            var obj = new MapImpl();

            obj.Insert(ValueFactory.Create("first"), ValueFactory.Create(1));
            obj.Insert(ValueFactory.Create("second"), ValueFactory.Create(2));

            var debuggerVar = Visualizer.GetVariable(Variable.Create(obj, "myVar"));

            Assert.That(debuggerVar.Presentation, Is.EqualTo("Соответствие"));
            Assert.That(debuggerVar.IsStructured, Is.True);

            var items = Visualizer.GetChildVariables(obj)
                        .Select(x => Visualizer.GetVariable(x))
                        .ToArray();

            Assert.That(items, Has.Length.EqualTo(2));
            Assert.That(items[0].Name, Is.EqualTo("0"));
            Assert.That(items[0].TypeName, Is.EqualTo("КлючИЗначение"));
            Assert.That(items[0].Presentation, Is.EqualTo("КлючИЗначение"));
            Assert.That(items[0].IsStructured, Is.True);

            Assert.That(items[1].Name, Is.EqualTo("1"));
            Assert.That(items[1].TypeName, Is.EqualTo("КлючИЗначение"));
            Assert.That(items[1].Presentation, Is.EqualTo("КлючИЗначение"));
            Assert.That(items[1].IsStructured, Is.True);

            var keyValue = Visualizer.GetChildVariables(obj.First())
                           .Select(x => Visualizer.GetVariable(x))
                           .ToArray();

            Assert.That(keyValue[0].Name, Is.EqualTo("Ключ"));
            Assert.That(keyValue[0].Presentation, Is.EqualTo("first"));
            Assert.That(keyValue[1].Name, Is.EqualTo("Значение"));
            Assert.That(keyValue[1].Presentation, Is.EqualTo("1"));
        }
예제 #25
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;
            }
        }
 private HttpRequestContext()
 {
     ResourceAddress = "";
     Headers         = new MapImpl();
 }
        public static HTTPServiceResponseImpl Constructor(IValue statusCode, IValue reason = null, MapImpl headers = null)
        {
            var response = new HTTPServiceResponseImpl();

            response._statusCode = System.Convert.ToInt16(statusCode.AsNumber());

            if (reason != null)
            {
                response._reason = reason.AsString();
            }

            if (headers != null)
            {
                response._headers = headers;
            }

            return(response);
        }
        public IValue ReadJSONInMap(JSONReader Reader, bool nestedArray = false)
        {
            if (nestedArray)
            {
                ArrayImpl NestedArray = new ArrayImpl();

                while (Reader.Read())
                {
                    if (Reader.CurrentJsonTokenType == JsonToken.EndArray)
                    {
                        break;
                    }
                    else if (Reader.CurrentJsonTokenType == JsonToken.StartObject)
                    {
                        NestedArray.Add(ReadJSONInMap(Reader));
                    }
                    else if (Reader.CurrentJsonTokenType == JsonToken.StartArray)
                    {
                        NestedArray.Add(ReadJSONInMap(Reader, true));
                    }
                    else
                    {
                        NestedArray.Add(Reader.CurrentValue);
                    }
                }
                return(NestedArray);
            }

            MapImpl ResStruct = new MapImpl();

            while ((Reader).Read())
            {
                if (Reader.CurrentJsonTokenType == JsonToken.PropertyName)
                {
                    string PropertyName = Reader.CurrentValue.AsString();
                    Reader.Read();

                    if (Reader.CurrentJsonTokenType == JsonToken.StartObject)
                    {
                        ResStruct.Insert(ValueFactory.Create(PropertyName), ReadJSONInMap(Reader));
                    }
                    else if (Reader.CurrentJsonTokenType == JsonToken.StartArray)
                    {
                        ResStruct.Insert(ValueFactory.Create(PropertyName), ReadJSONInMap(Reader, true));
                    }
                    else
                    {
                        ResStruct.Insert(ValueFactory.Create(PropertyName), Reader.CurrentValue);
                    }
                }
                else if (Reader.CurrentJsonTokenType == JsonToken.EndObject)
                {
                    break;
                }
                else if (Reader.CurrentJsonTokenType == JsonToken.StartArray)
                {
                    return(ReadJSONInMap(Reader, true));
                }
            }
            return(ResStruct);
        }
예제 #29
0
 public HttpRequestContext()
 {
     ResourceAddress = "";
     Headers         = new MapImpl();
     _body           = _emptyBody;
 }
예제 #30
0
 public void LoadGame(MapImpl map, PlayerImpl player)
 {
     this.Pg  = player;
     this.Map = map;
 }