Exemplo n.º 1
0
        public async Task DefinitionOfInvocationOfUnknownFunctionOrMethodReturnsNoLocation()
        {
            var source       = @"
method DoIt() returns (x: int) {
  return GetX();
}".TrimStart();
            var documentItem = CreateTestDocument(source);

            _client.OpenDocument(documentItem);
            Assert.IsFalse((await RequestDefinition(documentItem, (1, 12)).AsTask()).Any());
        }
Exemplo n.º 2
0
        public async Task DefinitionOfFieldOfSystemTypeReturnsNoLocation()
        {
            var source       = @"
method DoIt() {
  var x := new int[0];
  var y := x.Length;
}".TrimStart();
            var documentItem = CreateTestDocument(source);

            _client.OpenDocument(documentItem);
            Assert.IsFalse((await RequestDefinition(documentItem, (2, 14)).AsTask()).Any());
        }
Exemplo n.º 3
0
        private static void SerializeWithContext <T>(string elementName, T value, uint dtoVersion, bool addEnvelope, Action <XRoadMessage, string> f)
        {
            var message = Globals.ServiceManager20.CreateMessage();

            message.IsMultipartContainer = true;
            message.BinaryMode           = BinaryMode.Attachment;

            using (message)
                using (var stream = new MemoryStream())
                    using (var tw = new StreamWriter(stream, Encoding.UTF8))
                        using (var writer = XmlWriter.Create(tw))
                        {
                            if (addEnvelope)
                            {
                                writer.WriteStartElement("Envelope");
                                writer.WriteAttributeString(PrefixConstants.XMLNS, PrefixConstants.SOAP_ENC, NamespaceConstants.XMLNS, NamespaceConstants.SOAP_ENC);
                                writer.WriteAttributeString(PrefixConstants.XMLNS, PrefixConstants.XSI, NamespaceConstants.XMLNS, NamespaceConstants.XSI);
                                writer.WriteAttributeString(PrefixConstants.XMLNS, PrefixConstants.XSD, NamespaceConstants.XMLNS, NamespaceConstants.XSD);
                                writer.WriteAttributeString(PrefixConstants.XMLNS, PrefixConstants.TARGET, NamespaceConstants.XMLNS, Globals.ServiceManager20.ProducerNamespace);
                            }

                            writer.WriteStartElement(elementName);

                            var propType   = typeof(X <>).MakeGenericType(typeof(T));
                            var methodInfo = propType.GetTypeInfo().GetMethod("Method");

                            var operationDefinition = new OperationDefinition("Method", null, methodInfo);
                            var requestDefinition   = new RequestDefinition(operationDefinition, _ => false);

                            var typeMap = Globals.ServiceManager20.GetSerializer(dtoVersion).GetTypeMap(typeof(T));
                            typeMap.Serialize(writer, XRoadXmlTemplate.EmptyNode, value, requestDefinition.Content, message);

                            writer.WriteEndElement();

                            if (addEnvelope)
                            {
                                writer.WriteEndElement();
                            }

                            writer.Flush();

                            stream.Position = 0;
                            using (var reader = new StreamReader(stream))
                            {
                                if (!addEnvelope)
                                {
                                    f(message, reader.ReadToEnd());
                                    return;
                                }

                                using (var xmlReader = XmlReader.Create(reader))
                                {
                                    xmlReader.MoveToElement(0, "Envelope");
                                    f(message, xmlReader.ReadInnerXml());
                                }
                            }
                        }
        }
Exemplo n.º 4
0
        public async Task <byte[]> ApplyAsync(RequestDefinition definition)
        {
            var message = new HttpRequestMessage
            {
                RequestUri = new Uri(definition.Url),
                Method     = new HttpMethod(definition.Method),
            };

            foreach (var(key, value) in definition.Headers)
            {
                message.Headers.TryAddWithoutValidation(key, value);
            }

            if (definition.Body != null)
            {
                message.Content = new ByteArrayContent(definition.Body);
                foreach (var(key, value) in definition.Headers)
                {
                    message.Content.Headers.TryAddWithoutValidation(key, value);
                }
            }

            var stopwatch = Stopwatch.StartNew();
            var response  = await this.client.SendAsync(message);

            stopwatch.Stop();
            var result = await response.Content.ReadAsByteArrayAsync();

            if (response.IsSuccessStatusCode)
            {
                this.logger.LogTrace($"Request: {definition.Method} {definition.Url}. Elapsed: {stopwatch.ElapsedMilliseconds}. ResponseCode: {response.StatusCode}.");
                return(result);
            }

            var strResult = Encoding.UTF8.GetString(result);

            this.logger.LogError($"Failure http status code: {response.StatusCode}. Message: {strResult}");
            var errorResponse =
                JsonConvert.DeserializeObject <ResponseBaseModel <ResponseWithoutResultsModel> >(strResult);

            if (errorResponse != null)
            {
                strResult = $"{errorResponse.Errors.Type}: {errorResponse.Errors.Message}";
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.BadRequest:
                throw new BadRequestException(strResult);

            case HttpStatusCode.NotFound:
                throw new NotFoundException(strResult);

            default:
                throw new ResponseException($"Api return not success code: {response.StatusCode}", strResult);
            }
            ;
        }
Exemplo n.º 5
0
        protected Task <byte[]> ApplyAsync(RequestDefinition definition)
        {
            definition.Headers.Add(new KeyValuePair <string, string>("Content-Type", "application/json"));
            definition.Headers.Add(new KeyValuePair <string, string>("Mechant-Id", this.configuration.MerchantId));
            definition.Headers.Add(new KeyValuePair <string, string>("Secret-Key", this.configuration.SecretKey));
            definition.Url = this.GetRequestUrl(definition);

            return(this.httpClient.ApplyAsync(definition));
        }
Exemplo n.º 6
0
 /// <summary>
 /// Converts a <see cref="RequestDefinition"/> to a <see cref="MockupRequest"/>.
 /// </summary>
 /// <param name="request">The request to convert.</param>
 /// <returns>The converted instance.</returns>
 public static MockupRequest ToMockupRequest(this RequestDefinition request) => new MockupRequest
 {
     Id         = request.Id,
     Route      = request.Route,
     HttpMethod = request.Method.ToMethodString(),
     ResponseId = request.MockupResponseId,
     Query      = request.Query,
     Body       = request.Body
 };
Exemplo n.º 7
0
        public async Task DefinitionOfFunctionInvocationOfFunctionDeclaredInForeignDocumentReturnsLocation()
        {
            var source       = @"
include ""foreign.dfy""

method DoIt() returns (x: int) {
  var a := new A();
  return a.GetX();
}".TrimStart();
            var documentItem = CreateTestDocument(source, Path.Combine(Directory.GetCurrentDirectory(), "Lookup/TestFiles/test.dfy"));

            _client.OpenDocument(documentItem);
            var definition = (await RequestDefinition(documentItem, (4, 13)).AsTask()).Single();
            var location   = definition.Location;

            Assert.AreEqual(DocumentUri.FromFileSystemPath(Path.Combine(Directory.GetCurrentDirectory(), "Lookup/TestFiles/foreign.dfy")), location.Uri);
            Assert.AreEqual(new Range((5, 18), (5, 22)), location.Range);
        }
Exemplo n.º 8
0
        public async Task DefinitionOfMethodInvocationOfMethodDeclaredInSameDocumentReturnsLocation()
        {
            var source       = @"
method DoIt() returns (x: int) {
}

method CallDoIt() returns () {
  var x := DoIt();
}".TrimStart();
            var documentItem = CreateTestDocument(source);

            _client.OpenDocument(documentItem);
            var definition = (await RequestDefinition(documentItem, (4, 14)).AsTask()).Single();
            var location   = definition.Location;

            Assert.AreEqual(documentItem.Uri, location.Uri);
            Assert.AreEqual(new Range((0, 7), (0, 11)), location.Range);
        }
Exemplo n.º 9
0
        public async Task DefinitionInConstructorInvocationOfUserDefinedTypeOfForeignFileReturnsLinkToForeignFile()
        {
            var source       = @"
include ""foreign.dfy""

method DoIt() returns (x: int) {
  var a := new A();
  return a.GetX();
}".TrimStart();
            var documentItem = CreateTestDocument(source, Path.Combine(Directory.GetCurrentDirectory(), "Lookup/TestFiles/test.dfy"));

            _client.OpenDocument(documentItem);
            var definition = (await RequestDefinition(documentItem, (3, 15)).AsTask()).Single();
            var location   = definition.Location;

            Assert.AreEqual(DocumentUri.FromFileSystemPath(Path.Combine(Directory.GetCurrentDirectory(), "Lookup/TestFiles/foreign.dfy")), location.Uri);
            Assert.AreEqual(new Range((0, 6), (0, 7)), location.Range);
        }
Exemplo n.º 10
0
        public TestSystemServiceMap(XName operationName)
        {
            var methodInfo = typeof(Implementation).GetTypeInfo().GetMethod("Execute");

            OperationDefinition = new OperationDefinition(operationName, null, methodInfo);
            RequestDefinition   = new RequestDefinition(OperationDefinition, _ => false);
            ResponseDefinition  = new ResponseDefinition(OperationDefinition, _ => false)
            {
                ContainsNonTechnicalFault = true
            };
        }
Exemplo n.º 11
0
        /// <summary>
        /// Adds a new request to the database.
        /// </summary>
        /// <param name="request">The request to add. Its id must be 0 (zero).</param>
        /// <param name="transactionId">An (optional) id for logging purpose.</param>
        /// <returns>The added request with an updated id.</returns>
        public static MockupRequest AddRequest(MockupRequest request, Guid?transactionId = null)
        {
            var  logId  = Guid.Empty;
            var  method = request.HttpMethod.ToMethodEnum();
            bool exists;
            RequestDefinition newData;

            if (transactionId.HasValue)
            {
                logId = transactionId.Value;
            }
            if (logId.Equals(Guid.Empty))
            {
                logId = Guid.NewGuid();
            }
            if (method == HttpMethodEnum.Unknown)
            {
                Program.Logger.Error($"Unknown HTTP method '{request.HttpMethod}'.");
                throw new WebApiMockException($"Unknown HTTP method '{request.HttpMethod}'.", 16);
            }
            if (request.ResponseId == 0)
            {
                Program.Logger.Error("No response set for the new request.");
                throw new WebApiMockException("No response set for the new request.", 17);
            }
            exists = ResponseExistsForId(request.ResponseId);
            if (!exists)
            {
                Program.Logger.Error($"No response with id #{request.ResponseId} found.");
                throw new WebApiMockException($"No response with id #{request.ResponseId} found.", 18);
            }
            if (request.Id != 0)
            {
                Program.Logger.Error("The id for a new request must be 0.");
                throw new WebApiMockException("The id for a new request must be 0.", 14);
            }
            if (RequestExists(request.HttpMethod, request.Route, request.Query, request.Body, logId))
            {
                Program.Logger.Error("The request already exists.");
                throw new WebApiMockException("The request already exists.", 15);
            }
            newData = new RequestDefinition {
                Method           = request.HttpMethod.ToMethodEnum(),
                Body             = request.Body,
                Query            = request.Query,
                Route            = request.Route,
                MockupResponseId = request.ResponseId
            };
            using var ctx = new DataContext();
            ctx.Requests.Add(newData);
            ctx.SaveChanges(true);
            Program.Logger.Info($"[{logId}] Successfully created request #{newData.Id} ({request.Route}) [{request.HttpMethod}].");
            return(newData.ToMockupRequest());
        }
Exemplo n.º 12
0
        public async Task DefinitionOfVariableShadowingFieldReturnsTheFieldIfThisIsUsed()
        {
            var source       = @"
class Test {
  var x: int;

  method DoIt() {
    var x := 1;
    print this.x;
  }
}".TrimStart();
            var documentItem = CreateTestDocument(source);

            _client.OpenDocument(documentItem);
            var definition = (await RequestDefinition(documentItem, (5, 15)).AsTask()).Single();
            var location   = definition.Location;

            Assert.AreEqual(documentItem.Uri, location.Uri);
            Assert.AreEqual(new Range((1, 6), (1, 7)), location.Range);
        }
Exemplo n.º 13
0
        public async Task DefinitionOfVariableShadowingFieldReturnsTheVariable()
        {
            var source       = @"
class Test {
  var x: int;

  method DoIt() {
    var x := 1;
    print x;
  }
}".TrimStart();
            var documentItem = CreateTestDocument(source);
            await client.OpenDocumentAndWaitAsync(documentItem, CancellationToken);

            var definition = (await RequestDefinition(documentItem, (5, 10)).AsTask()).Single();
            var location   = definition.Location;

            Assert.AreEqual(documentItem.Uri, location.Uri);
            Assert.AreEqual(new Range((4, 8), (4, 9)), location.Range);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Initialize new `listMethods` service map.
        /// </summary>
        public ListMethodsServiceMap(XName operationName)
        {
            var methodInfo = typeof(Implementation).GetTypeInfo().GetMethod("Execute");

            OperationDefinition = new OperationDefinition(operationName, null, methodInfo);
            RequestDefinition   = new RequestDefinition(OperationDefinition);
            ResponseDefinition  = new ResponseDefinition(OperationDefinition)
            {
                ContainsNonTechnicalFault = true,
                ResponseElementName       = operationName.NamespaceName == NamespaceConstants.XTEE ? "keha" : "response"
            };
        }
    public void GenerateRequest()
    {
        ErrorText.text = "";

        if (!MaleToggle.isOn && !FemaleToggle.isOn)
        {
            ErrorText.text = "Vous devez spécifier au moins un genre";
            return;
        }

        //Hack pour prévenir d'attendre le timeout
        if ((int)MinAgeSlider.value == 9 && (int)MaxAgeSlider.value == 10 && MaleToggle.isOn && !FemaleToggle.isOn)
        {
            ErrorText.text = "Aucun résultat";
            return;
        }

        if (LoadImageCoroutine != null)
        {
            StopCoroutine(LoadImage(ImageFilePath));
        }

        RequestDefinition request = new RequestDefinition();

        request.minAge = (int)MinAgeSlider.value * 5 + 20;
        request.maxAge = (int)MaxAgeSlider.value * 5 + 20;
        if (MaleToggle.isOn)
        {
            request.gender += "M";
        }

        if (FemaleToggle.isOn)
        {
            request.gender += "F";
        }

        string alreadyGeneratedFilename = request.gender + "_" + request.minAge + "_" + request.maxAge + ".jpg";

        if (File.Exists(alreadyGeneratedFilename))
        {
            StartCoroutine(LoadImage(alreadyGeneratedFilename));
            return;
        }

        LoadingPanel.SetActive(true);

        File.Delete(ImageFilePath);

        File.WriteAllText(RequestFilePath, JsonUtility.ToJson(request, true));

        RequestPending = true;
        Timer          = Timeout;
    }
Exemplo n.º 16
0
        public async Task DefinitionOfVariableShadowedByAnotherReturnsTheOriginalVariable()
        {
            var source       = @"
class Test {
  var x: int;

  method DoIt() {
    var x := 1;
    {
      var x := 2;
    }
    print x;
  }
}".TrimStart();
            var documentItem = CreateTestDocument(source);

            _client.OpenDocument(documentItem);
            var definition = (await RequestDefinition(documentItem, (8, 10)).AsTask()).Single();
            var location   = definition.Location;

            Assert.AreEqual(documentItem.Uri, location.Uri);
            Assert.AreEqual(new Range((4, 8), (4, 9)), location.Range);
        }
        public async Task <PaymentStatusResponse> GetPaymentStatusAsync(PaymentStatusRequest request)
        {
            Guard.ArgumentNotNull(request, nameof(request));

            var definition = new RequestDefinition
            {
                Url    = $"/{request.TransactionId}/status",
                Method = HttpMethods.Get
            };

            this.logger.LogTrace($"Start send check status payment request to [{definition.Method}] {this.GetRequestUrl(definition)}");
            var rawResult = await this.ApplyAsync(definition);

            return(this.Deserialize <PaymentStatusResponse>(rawResult));
        }
        public async Task <ConfirmPaymentResponse> ConfirmPaymentAsync(ConfirmPaymentRequest request)
        {
            Guard.ArgumentNotNull(request, nameof(request));

            var definition = new RequestDefinition
            {
                Url    = "/confirm",
                Method = HttpMethods.Post,
                Body   = this.Serialize(request)
            };

            this.logger.LogTrace($"Start send confirm payment request to [{definition.Method}] {this.GetRequestUrl(definition)}");
            var rawResult = await this.ApplyAsync(definition);

            return(this.Deserialize <ConfirmPaymentResponse>(rawResult));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initializes new ServiceMap entity using settings specified in operationDefinition.
        /// <param name="serializer">Provides TypeMap lookup.</param>
        /// <param name="operationDefinition">Operation which this ServiceMap represents.</param>
        /// <param name="requestDefinition">Defines operation request message.</param>
        /// <param name="responseDefinition">Defines operation response message.</param>
        /// <param name="inputTypeMap">Default TypeMap of the operation request root element.</param>
        /// <param name="outputTypeMap"> Default TypeMap of the operation response root element.</param>
        /// </summary>
        public ServiceMap(ISerializer serializer, OperationDefinition operationDefinition, RequestDefinition requestDefinition, ResponseDefinition responseDefinition, ITypeMap inputTypeMap, ITypeMap outputTypeMap)
        {
            this.serializer = serializer;

            RequestDefinition   = requestDefinition;
            ResponseDefinition  = responseDefinition;
            OperationDefinition = operationDefinition;

            this.inputTypeMap = inputTypeMap is IContentTypeMap inputContentTypeMap && requestDefinition.Content.UseXop
                ? inputContentTypeMap.GetOptimizedContentTypeMap()
                : inputTypeMap;

            this.outputTypeMap = outputTypeMap is IContentTypeMap outputContentTypeMap && responseDefinition.Content.UseXop
                ? outputContentTypeMap.GetOptimizedContentTypeMap()
                : outputTypeMap;
        }
Exemplo n.º 20
0
 protected string GetRequestUrl(RequestDefinition definition) => this.configuration.ApiBaseUrl + definition.Url;
Exemplo n.º 21
0
        public ProtoBufServiceMap(ISerializer serializer, OperationDefinition operationDefinition, RequestDefinition requestDefinition, ResponseDefinition responseDefinition, ITypeMap inputTypeMap, ITypeMap outputTypeMap)
            : base(serializer, operationDefinition, requestDefinition, responseDefinition, inputTypeMap, outputTypeMap)
        {
            var requestType  = RequestDefinition.ParameterInfo?.ParameterType;
            var responseType = ResponseDefinition.ParameterInfo?.ParameterType;

            readRequestMethod   = BuildReadValueMethod(requestType);
            readResponseMethod  = BuildReadValueMethod(responseType);
            writeRequestMethod  = BuildWriteValueMethod(requestType);
            writeResponseMethod = BuildWriteValueMethod(responseType);
        }
Exemplo n.º 22
0
 public override void ExportRequestDefinition(RequestDefinition requestDefinition)
 {
     requestDefinition.Content.RuntimeType      = typeof(Stream);
     requestDefinition.Content.UseXop           = true;
     requestDefinition.Content.CustomAttributes = new[] { Tuple.Create(XName.Get("schema", XROAD_PROTOBUF_SCHEMA), GetPrototypeName()) };
 }