Example #1
0
        public static async Task <JObject> RetrieveSObjectsAsync(DnfClient client)
        {
            var describeGlobalResult = await client.GetObjectsAsync()
                                       .ConfigureAwait(false);

            var request = new CompositeRequest();

            if (describeGlobalResult?.SObjects != null)
            {
                foreach (var sObject in describeGlobalResult.SObjects)
                {
                    var objectName = sObject["name"]?.ToString() ?? string.Empty;
                    if ((bool?)sObject["deprecatedAndHidden"] == true)
                    {
                        continue;
                    }
                    request.Describe(objectName, objectName);
                }
            }

            var describeResult = await client.Composite.PostAsync(request)
                                 .ConfigureAwait(false);

            var objects = JObject.FromObject(describeResult.Results());

            return(objects);
        }
Example #2
0
        public void MultipleRequestAsync_Success()
        {
            // Arrange
            var mockRequests = new CompositeRequest()
            {
                composites = new List <Composite>()
                {
                    new Composite(HttpMethods.PATCH, new { LastName = "Nome de Teste" }, "R1", "Account")
                }
            };

            var headers = new Dictionary <string, string>();

            headers.Add("Location", "/services/data/v48.0/sobjects/Account/R1");

            var mockResponses = new
            {
                compositeResponse = new List <CompositeResponse>()
                {
                    new CompositeResponse()
                    {
                        Body = new {
                            Id      = "R1",
                            Success = true,
                            Errors  = new List <ErroDetail>(),
                            Cretead = false
                        },
                        HttpHeaders    = headers,
                        HttpStatusCode = HttpStatusCode.OK,
                        ReferenceId    = "R1"
                    }
                }
            };

            var messageHandler = new MockHttpMessageHandler <object>(mockResponses, HttpStatusCode.OK);
            var httpClient     = new HttpClient(messageHandler);

            MockServer.Setup(config => config.GetHttpCliente()).Returns(httpClient);

            //Action
            List <CompositeResponse> retorno = CrmWebApi.MultipleRequestAsync(mockRequests).GetAwaiter().GetResult();

            //Assert
            Assert.Equal(1, messageHandler.NumberOfCalls);
            Assert.NotNull(retorno);
            Assert.Single(retorno);

            Assert.Equal(HttpStatusCode.OK, retorno.First().HttpStatusCode);
            Assert.Equal("R1", retorno.First().ReferenceId);
            Assert.NotNull(retorno.First().HttpHeaders);
            Assert.Single(retorno.First().HttpHeaders);

            Assert.NotNull(retorno.First().Sucess);
            Assert.Equal("R1", retorno.First().Sucess.Id);
            Assert.True(retorno.First().Sucess.Success);
            Assert.Null(retorno.First().Errors);

            Assert.Equal("Location", retorno.First().HttpHeaders.First().Key);
            Assert.Equal("/services/data/v48.0/sobjects/Account/R1", retorno.First().HttpHeaders.First().Value);
        }
Example #3
0
 public void Handle(CompositeRequest <TFor> request)
 {
     foreach (var r in request.Requests)
     {
         this.handler.Handle(r);
     }
 }
Example #4
0
        private void button1_Click(object sender, EventArgs e)
        {
            var solicitudes = new CompositeRequest()
            {
                Requests =
                {
                    new SystemInfoRequest(),
                    new ListProductsRequest(),
                    new ListCustomersRequest(),
                    new ListInvoicesRequest()
                }
            };

            /*
             * var solicitudes = new CompositeRequest();
             *
             * var solicitud0 = new SystemInfoRequest();
             * var solicitud1 = new ListProductsRequest();
             * var solicitud2 = new ListCustomersRequest();
             *
             * solicitudes.Requests.Add(solicitud0);
             * solicitudes.Requests.Add(solicitud1);
             * solicitudes.Requests.Add(solicitud2);
             */

            var respuesta = this.checkBox1.Checked
                ? solicitudes.RunMock()
                : solicitudes.Run();


            var systemInfoResponse = respuesta.Responses[0] as SystemInfoResponse;

            Console.WriteLine("*systemInfoResponse*");
            Console.WriteLine(systemInfoResponse.ToString());


            var listProductsResponse = respuesta.Responses[1] as ListProductsResponse;

            Console.WriteLine("*listProductsResponse*");
            Console.WriteLine(listProductsResponse.ToString());


            var listCustomersResponse = respuesta.Responses[2] as ListCustomersResponse;

            Console.WriteLine("*listCustomersResponse*");
            Console.WriteLine(listCustomersResponse.ToString());

            var listInvoicesResponse = respuesta.Responses[3] as ListInvoicesResponse;

            Console.WriteLine("*ListInvoicesResponse*");
            Console.WriteLine(listInvoicesResponse.ToString());

            this.articuloBindingSource.DataSource         = listProductsResponse.Items;
            this.clienteBindingSource.DataSource          = listCustomersResponse.Items;
            this.invoicesListItemBindingSource.DataSource = listInvoicesResponse.Items;

            ActualizarItems();
        }
        public async Task CompositeUrlInjectionTest()
        {
            var client = await LoginTask()
                         .ConfigureAwait(false);

            await DeleteTestingRecords(client)
            .ConfigureAwait(false);

            try
            {
                await Assert
                .ThrowsAsync <ForceException>(async() =>
                {
                    var request = new CompositeRequest(true);
                    request.Create("create", "Product2", Dnf.Assign(GetTestProduct2(), new JObject
                    {
                        ["Name"]            = "UnitTest/",
                        ["ProductCode"]     = "UnitTest/",
                        ["CurrencyIsoCode"] = "USD"
                    }));
                    request.Query("query", @"
SELECT Id, Name, ProductCode FROM Product2 WHERE Id = '@{create.id}'");
                    request.Query("query2", @"
SELECT Id, Name, ProductCode FROM Product2
WHERE Id = '@{query.records[0].Id}'
AND ProductCode = '@{query.records[0].ProductCode}'");
                    request.Update("update", "Product2", new JObject
                    {
                        ["Id"]          = "@{query2.records[0].Id}",
                        ["ProductCode"] = "@{query2.records[0].ProductCode}2"
                    });
                    request.Query("updated", @"
SELECT Id, Name, ProductCode FROM Product2
WHERE Id = '@{query2.records[0].Id}'
AND ProductCode = '@{query2.records[0].ProductCode}2");
                    request.UpsertExternal("upsert", "Product2", "Id", "@{query.records[0].Id}", new JObject
                    {
                        ["Name"] = "@{query.records[0].Name}"
                    });
                    request.Delete("delete", "Product2", "@{updated.records[0].Id}");
                    var result = await client.Composite.PostAsync(request)
                                 .ConfigureAwait(false);
                    result.Assert();
                })
                .ConfigureAwait(false);
            }
            finally
            {
                await DeleteTestingRecords(client)
                .ConfigureAwait(false);
            }
        }
        public async Task CompositeUrlParamInjectionTest()
        {
            var client = await LoginTask()
                         .ConfigureAwait(false);

            await DeleteTestingRecords(client)
            .ConfigureAwait(false);

            try
            {
                var request = new CompositeRequest(true);
                request.Create("create", "Product2", Dnf.Assign(GetTestProduct2(), new JObject
                {
                    ["Name"]            = "UnitTest' AND Name != '",
                    ["ProductCode"]     = "UnitTest' AND Name != '",
                    ["CurrencyIsoCode"] = "USD"
                }));
                request.Query("query", @"
SELECT Id, Name, ProductCode FROM Product2 WHERE Id = '@{create.id}'");
                request.Query("query2", @"
SELECT Id, Name, ProductCode FROM Product2
WHERE Id = '@{query.records[0].Id}'
AND ProductCode = '@{query.records[0].ProductCode}'");
                request.Update("update", "Product2", new JObject
                {
                    ["Id"]          = "@{query.records[0].Id}",
                    ["ProductCode"] = "@{query.records[0].ProductCode}2"
                });
                request.Query("updated", $@"
SELECT Id, Name, ProductCode FROM Product2
WHERE Id = '@{{query.records[0].Id}}'
AND ProductCode = {Dnf.SoqlString("UnitTest' AND Name != '2")}");
                //request.UpsertExternal("upsert", "Product2", "Id", "@{updated.records[0].Id}' AND Name != '2", new JObject
                //{
                //    ["Name"] = "@{query.records[0].Name}"
                //});
                request.Delete("delete", "Product2", "@{updated.records[0].Id}");
                var result = await client.Composite.PostAsync(request)
                             .ConfigureAwait(false);

                result.Assert();
                Assert.Equal(0, result.Queries("query2").TotalSize);
            }
            finally
            {
                await DeleteTestingRecords(client)
                .ConfigureAwait(false);
            }
        }
        public async Task <List <CompositeResponse> > MultipleRequestAsync(CompositeRequest compositeRequest)
        {
            httpClient = _baseAuthorization.GetHttpCliente();
            var url     = $"{ApiUrl}services/data/v{ApiCofiguration.Version}/composite";
            var context = JsonConvert.SerializeObject(compositeRequest);
            var content = new StringContent(context, Encoding.UTF8, "application/json");
            var result  = await httpClient.PostAsync(url, content);

            var resultContent = await result.Content.ReadAsStringAsync();

            if (!result.IsSuccessStatusCode)
            {
                throw new Exception($"Error=>> {resultContent} Token Expired In: {ComvertToDateTimeUnixTimestamp(_baseAuthorization.Timeout)}");
            }
            result.EnsureSuccessStatusCode();
            var json = JsonConvert.DeserializeObject <dynamic>(resultContent);

            return(json["compositeResponse"].ToObject <List <CompositeResponse> >());
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_consumerKey) && string.IsNullOrEmpty(_consumerSecret) && string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_password) && string.IsNullOrEmpty(_organizationId))
            {
                _consumerKey    = Environment.GetEnvironmentVariable("ConsumerKey");
                _consumerSecret = Environment.GetEnvironmentVariable("ConsumerSecret");
                _username       = Environment.GetEnvironmentVariable("Username");
                _password       = Environment.GetEnvironmentVariable("Password");
                _organizationId = Environment.GetEnvironmentVariable("OrganizationId");
            }

            // Use TLS 1.2 (instead of defaulting to 1.0)
            const int SecurityProtocolTypeTls11 = 768;
            const int SecurityProtocolTypeTls12 = 3072;

            ServicePointManager.SecurityProtocol |= (SecurityProtocolType)(SecurityProtocolTypeTls12 | SecurityProtocolTypeTls11);

            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, _token).Wait();

            _client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);

            CompositeRequestRoot _requestRoot = new CompositeRequestRoot();

            _requestRoot.allOrNone = true;
            Account _account1 = new Account();

            _account1.Name = "This for Composite 2 - Composite";
            CompositeRequest _request = new CompositeRequest();

            _request.body        = _account1;
            _request.method      = "PATCH";
            _request.referenceId = "UpdateAccountRef";
            _request.url         = "/services/data/v37.0/sobjects/Account/0012C000008WyxNQAS";

            List <CompositeRequest> _requestList = new List <CompositeRequest>();

            _requestList.Add(_request);
            _requestRoot.compositeRequest = _requestList;

            var successResponse = _client.CreateCompositeAsync(_requestRoot);
        }
Example #9
0
        /// <summary>
        /// Generic send request
        /// </summary>
        /// <param name="request">Request to send</param>
        /// <returns>Response model</returns>
        public virtual WebServiceResponse SendRequest(WebServiceRequest request)
        {
            this.request = request;

            XmlDocument xmlRequest = RequestFactory.CreateRequest(request);

            this.xmlRequest = xmlRequest;

            XmlDocument xmlResponse = SendRequest(xmlRequest);

            this.xmlResponse = xmlResponse;

            WebServiceResponse response = ResponseFactory.CreateResponse(request.GetWebServiceResponseModel(), xmlResponse);

            if ((response is CompositeResponse) && (request is CompositeRequest))
            {
                CompositeResponse compositeResponse = (CompositeResponse)response;
                CompositeRequest  compositeRequest  = (CompositeRequest)request;

                if (compositeResponse.GetResponsesCount() > 0)
                {
                    List <WebServiceResponse> responses  = compositeResponse.GetResponses();
                    List <Operation>          operations = compositeRequest.GetOperations();

                    for (int i = 0; i < responses.Count; i++)
                    {
                        WebServiceResponse tempResponse = responses[i];
                        WebServiceRequest  temRequest   = operations[i].WebService;
                        tempResponse.WebServiceType = temRequest.WebServiceType;
                    }
                }
            }

            response.WebServiceType = request.WebServiceType;
            return(response);
        }
        /// <summary>
        /// Generates the xml operation for request
        /// </summary>
        /// <param name="webService">Web service model</param>
        /// <returns>Xml for operation</returns>
        private static XmlElement BuildXmlModel(WebServiceRequest webService)
        {
            XmlDocument doc = new XmlDocument();

            if (webService.GetWebServiceRequestModel() == WebServiceRequestModel.CompositeRequest)
            {
                CompositeRequest request = (CompositeRequest)webService;

                XmlElement xmlModel = CreateXmlElement_0(doc, "operations");

                foreach (Operation operation in request.GetOperations())
                {
                    xmlModel.AppendChild(doc.ImportNode(BuildXmlOperation(operation), true));
                }

                return(xmlModel);
            }
            else if (webService.GetWebServiceRequestModel() == WebServiceRequestModel.ModelCRUDRequest)
            {
                ModelCRUDRequest request = (ModelCRUDRequest)webService;

                XmlElement xmlModel = CreateXmlElement_0(doc, "ModelCRUD");

                XmlElement xmlServiceType = CreateXmlElement_0(doc, "serviceType");
                xmlServiceType.InnerText = webService.WebServiceType;
                xmlModel.AppendChild(xmlServiceType);

                if (!string.IsNullOrEmpty(request.TableName))
                {
                    XmlElement xmlTableName = CreateXmlElement_0(doc, "TableName");
                    xmlTableName.InnerText = request.TableName;
                    xmlModel.AppendChild(xmlTableName);
                }

                if (request.RecordID != null)
                {
                    XmlElement xmlRecordID = CreateXmlElement_0(doc, "RecordID");
                    xmlRecordID.InnerText = request.RecordID.ToString();
                    xmlModel.AppendChild(xmlRecordID);
                }

                if (request.RecordIDVariable != null)
                {
                    XmlElement xmlRecordIDVariable = CreateXmlElement_0(doc, "recordIDVariable");
                    xmlRecordIDVariable.InnerText = request.RecordIDVariable;
                    xmlModel.AppendChild(xmlRecordIDVariable);
                }

                if (request.Action != null)
                {
                    XmlElement xmlAction = CreateXmlElement_0(doc, "Action");
                    xmlAction.InnerText = request.Action.ToString();
                    xmlModel.AppendChild(xmlAction);
                }

                if (!string.IsNullOrEmpty(request.Filter))
                {
                    XmlElement xmlFilter = CreateXmlElement_0(doc, "Filter");
                    xmlFilter.InnerText = request.Filter;
                    xmlModel.AppendChild(xmlFilter);
                }

                if (request.Limit != null)
                {
                    XmlElement xmlLimit = CreateXmlElement_0(doc, "Limit");
                    xmlLimit.InnerText = request.Limit.ToString();
                    xmlModel.AppendChild(xmlLimit);
                }

                if (request.Offset != null)
                {
                    XmlElement xmlOffset = CreateXmlElement_0(doc, "Offset");
                    xmlOffset.InnerText = request.Offset.ToString();
                    xmlModel.AppendChild(xmlOffset);
                }

                if (request.DataRow != null && request.DataRow.GetFieldsCount() > 0)
                {
                    xmlModel.AppendChild(doc.ImportNode(BuildXmlFieldsContainer(request.DataRow), true));
                }

                return(xmlModel);
            }
            else if (webService.GetWebServiceRequestModel() == WebServiceRequestModel.ModelGetListRequest)
            {
                ModelGetListRequest request = (ModelGetListRequest)webService;

                XmlElement xmlModel = CreateXmlElement_0(doc, "ModelGetList");

                XmlElement xmlServiceType = CreateXmlElement_0(doc, "serviceType");
                xmlServiceType.InnerText = request.WebServiceType;
                xmlModel.AppendChild(xmlServiceType);

                if (request.AD_Reference_ID != null)
                {
                    XmlElement xmlReferenceID = CreateXmlElement_0(doc, "AD_Reference_ID");
                    xmlReferenceID.InnerText = request.AD_Reference_ID.ToString();
                    xmlModel.AppendChild(xmlReferenceID);
                }

                if (!string.IsNullOrEmpty(request.Filter))
                {
                    XmlElement xmlFilter = CreateXmlElement_0(doc, "Filter");
                    xmlFilter.InnerText = request.Filter;
                    xmlModel.AppendChild(xmlFilter);
                }

                return(xmlModel);
            }
            else if (webService.GetWebServiceRequestModel() == WebServiceRequestModel.ModelRunProcessRequest)
            {
                ModelRunProcessRequest request = (ModelRunProcessRequest)webService;

                XmlElement xmlModel = CreateXmlElement_0(doc, "ModelRunProcess");

                XmlElement xmlServiceType = CreateXmlElement_0(doc, "serviceType", request.WebServiceType);
                xmlModel.AppendChild(xmlServiceType);

                if (request.AD_Process_ID != null)
                {
                    xmlModel.SetAttribute("AD_Process_ID", request.AD_Process_ID.ToString());
                }

                if (request.AD_Menu_ID != null)
                {
                    xmlModel.SetAttribute("AD_Menu_ID", request.AD_Menu_ID.ToString());
                }

                if (request.AD_Record_ID != null)
                {
                    xmlModel.SetAttribute("AD_Record_ID", request.AD_Record_ID.ToString());
                }

                if (request.DocAction != null)
                {
                    DocAction?docAction = request.DocAction;
                    xmlModel.SetAttribute("DocAction", docAction.GetValue());
                }

                if (request.ParamValues != null && request.ParamValues.GetFieldsCount() > 0)
                {
                    xmlModel.AppendChild(doc.ImportNode(BuildXmlFieldsContainer(request.ParamValues), true));
                }

                return(xmlModel);
            }
            else if (webService.GetWebServiceRequestModel() == WebServiceRequestModel.ModelSetDocActionRequest)
            {
                ModelSetDocActionRequest request = (ModelSetDocActionRequest)webService;

                XmlElement xmlModel = CreateXmlElement_0(doc, "ModelSetDocAction");

                XmlElement xmlServiceType = CreateXmlElement_0(doc, "serviceType");
                xmlServiceType.InnerText = request.WebServiceType;
                xmlModel.AppendChild(xmlServiceType);

                if (!string.IsNullOrEmpty(request.TableName))
                {
                    XmlElement xmlTableName = CreateXmlElement_0(doc, "tableName");
                    xmlTableName.InnerText = request.TableName;
                    xmlModel.AppendChild(xmlTableName);
                }

                if (request.RecordID != null)
                {
                    XmlElement xmlRecordID = CreateXmlElement_0(doc, "recordID");
                    xmlRecordID.InnerText = request.RecordID.ToString();
                    xmlModel.AppendChild(xmlRecordID);
                }

                if (!string.IsNullOrEmpty(request.RecordIDVariable))
                {
                    XmlElement xmlRecordIDVariable = CreateXmlElement_0(doc, "recordIDVariable");
                    xmlRecordIDVariable.InnerText = request.RecordIDVariable;
                    xmlModel.AppendChild(xmlRecordIDVariable);
                }

                if (request.DocAction != null)
                {
                    XmlElement xmlDocAction = CreateXmlElement_0(doc, "docAction");
                    xmlDocAction.InnerText = request.DocAction.GetValue();
                    xmlModel.AppendChild(xmlDocAction);
                }

                return(xmlModel);
            }
            return(doc.CreateElement("NoModel"));
        }
Example #11
0
 /// <inheritdoc />
 public async Task <CompositeResponse> StandartizationQueryComposite(CompositeRequest queries) =>
 (CompositeResponse) await ExecuteCommand(new CompositeCommand(),
                                          queries);
        // POST
        public async Task <CompositeResponse> HttpCompositeAsync(CompositeRequest request)
        {
            var url = Common.FormatUrl("composite/", InstanceUrl, ApiVersion);

            return(await HttpPostAsync <CompositeResponse>(request, url));
        }
Example #13
0
        public void MultipleRequestAsync_Error()
        {
            // Arrange
            var mockRequests = new CompositeRequest()
            {
                composites = new List <Composite>()
                {
                    new Composite(HttpMethods.PATCH, new { Name = "Nome de Teste" }, "R1", "Account")
                }
            };

            var mockResponses = new
            {
                compositeResponse = new List <CompositeResponse>()
                {
                    new CompositeResponse()
                    {
                        Body = new List <object>()
                        {
                            new {
                                Message   = "Unable to create/update fields: Name.",
                                ErrorCode = "INVALID_FIELD_FOR_INSERT_UPDATE",
                                Fields    = new List <string> {
                                    "Name"
                                }
                            }
                        },
                        HttpHeaders    = new Dictionary <string, string>(),
                        HttpStatusCode = HttpStatusCode.BadRequest,
                        ReferenceId    = "R1"
                    }
                }
            };

            var messageHandler = new MockHttpMessageHandler <object>(mockResponses, HttpStatusCode.OK);
            var httpClient     = new HttpClient(messageHandler);

            MockServer.Setup(config => config.GetHttpCliente()).Returns(httpClient);

            //Action
            List <CompositeResponse> retorno = CrmWebApi.MultipleRequestAsync(mockRequests).GetAwaiter().GetResult();

            //Assert
            Assert.Equal(1, messageHandler.NumberOfCalls);
            Assert.NotNull(retorno);
            Assert.Single(retorno);

            Assert.Equal(HttpStatusCode.BadRequest, retorno.First().HttpStatusCode);
            Assert.Equal("R1", retorno.First().ReferenceId);
            Assert.NotNull(retorno.First().HttpHeaders);
            Assert.Empty(retorno.First().HttpHeaders);
            Assert.Null(retorno.First().Sucess);

            Assert.NotNull(retorno.First().Errors);
            Assert.Single(retorno.First().Errors);
            Assert.Equal("Unable to create/update fields: Name.", retorno.First().Errors.First().Message);
            Assert.Equal("INVALID_FIELD_FOR_INSERT_UPDATE", retorno.First().Errors.First().ErrorCode);
            Assert.NotNull(retorno.First().Errors.First().Fields);
            Assert.Single(retorno.First().Errors.First().Fields);
            Assert.Equal("Name", retorno.First().Errors.First().Fields.First());
        }
        public async Task CompositeSoqlInjectionTest()
        {
            var client = await LoginTask()
                         .ConfigureAwait(false);

            await DeleteTestingRecords(client)
            .ConfigureAwait(false);

            try
            {
                const string testText = "UnitTest' AND Name != '";
                var          request  = new CompositeRequest();
                request.Create("create", "Product2", Dnf.Assign(GetTestProduct2(), new JObject
                {
                    ["ProductCode"] = testText
                }));
                request.Retrieve("created", "Product2", "@{create.id}");

                request.Query("query", @"
SELECT Id, Name, ProductCode FROM Product2 WHERE Id = '@{created.Id}'
AND ProductCode = '@{created.ProductCode}'");

                request.UpsertExternal("upsert", "Product2", "Id", "@{created.Id}", new JObject
                {
                    ["Name"] = testText
                });
                request.Query("upserted", $@"
SELECT Id, Name, ProductCode FROM Product2 WHERE Id = '@{{created.Id}}'
AND Name = {Dnf.SoqlString(testText)}");

                request.Update("update", "Product2", new JObject
                {
                    ["Id"]          = "@{created.Id}",
                    ["ProductCode"] = "@{created.ProductCode}"
                });
                request.Query("updated", $@"
SELECT Id, Name, ProductCode FROM Product2 WHERE Id = '@{{created.Id}}'
AND ProductCode = {Dnf.SoqlString(testText)}");

                request.Delete("delete", "Product2", "@{create.id}");
                var result = await client.Composite.PostAsync(request)
                             .ConfigureAwait(false);

                result.Assert();
                Assert.Equal(testText, result.Results("created")["ProductCode"]);
                Assert.Equal(0, result.Queries("query").TotalSize);
                Assert.Equal(testText, result.Queries("upserted").Records?[0]["Name"]);
                Assert.Equal(testText.Replace("\n", " ").Replace("\\", ""), result.Queries("updated").Records?[0]["Name"]);
            }
            finally
            {
                await DeleteTestingRecords(client)
                .ConfigureAwait(false);
            }
            try
            {
                const string testText = "Uni\\nt\\tTe\\\\ns\\\\ts\\\\\\nt\\\\\\tt";
                var          request  = new CompositeRequest();
                request.Create("create", "Product2", Dnf.Assign(GetTestProduct2(), new JObject
                {
                    ["ProductCode"] = testText
                }));
                request.Retrieve("created", "Product2", "@{create.id}");

                request.Query("query", @"
SELECT Id, Name, ProductCode FROM Product2 WHERE Id = '@{created.Id}'
AND ProductCode = '@{created.ProductCode}'");

                // cannot upsert
                request.UpsertExternal("upsert", "Product2", "Id", "@{created.Id}", new JObject
                {
                    ["Name"] = testText
                });
                request.Query("upserted", $@"
SELECT Id, Name, ProductCode FROM Product2 WHERE Id = '@{{created.Id}}'
AND Name = {Dnf.SoqlString(testText)}");

                request.Update("update", "Product2", new JObject
                {
                    ["Id"]          = "@{created.Id}",
                    ["ProductCode"] = "@{created.ProductCode}"
                });
                request.Retrieve("updated", "Product2", "@{created.Id}");

                request.Delete("delete", "Product2", "@{create.id}");
                var result = await client.Composite.PostAsync(request)
                             .ConfigureAwait(false);

                //result.Assert();
                Assert.Equal(testText, result.Results("created")["ProductCode"]);
                Assert.Equal(0, result.Queries("query").TotalSize);
                Assert.Equal(1, result.Queries("upserted").TotalSize);
                Assert.Equal("Uni t\tTe\\ns\\ts\\ t\\\tt", (string)result.Results("updated")["ProductCode"]);
            }
            finally
            {
                await DeleteTestingRecords(client)
                .ConfigureAwait(false);
            }
        }
Example #15
0
        async Task StandartizationQueryCompositeTest()
        {
            var sb =
                "[\n" +
                "    [ \"1\",\n" +
                "      \"Федотов Алексей\",\n" +
                "      \"Москва, Сухонская улица, 11 кв 89\",\n" +
                "      \"8 916 823 3454\"\n" +
                "    ],\n" +
                "    [ [\"2\"],\n" +
                "      [\"Иванов\", \"Сергей Владимирович\"],\n" +
                "      [\"мск\", \"улица свободы\", \"65\", \"12\"],\n" +
                "      [\"495 663-12-53\"]\n" +
                "    ],\n" +
                "    [ \"3\",\n" +
                "      [\"Ольга Павловна\", \"Ященко\"],\n" +
                "      [\"\", \"Спб, ул Петрозаводская 8\", \"\", \"\"],\n" +
                "      \"457 07 25\"\n" +
                "    ]\n" +
                "]";

            var request = new CompositeRequest
            {
                Structure = new JArray
                {
                    "AS_IS",
                    "NAME",
                    "ADDRESS",
                    "PHONE"
                },
                Data = JArray.Parse(sb)
            };

            var result = await ApiClient.StandartizationQueryComposite(request);

            Assert.NotNull(result);
            Assert.NotNull(result.Value);

            var first = result.Value;

            Assert.NotNull(first);

            Assert.NotNull(first.Data);
            Assert.NotEmpty(first.Data);

            var data = first.Data;

            var requests = data.Children <JArray>();

            var firstRequest = requests.ElementAt(0).Children <JObject>();

            var child1 = firstRequest.ElementAt(0);

            Assert.Equal("1", child1.Property("source").Value.ToString());

            var child2 = firstRequest.ElementAt(1);

            Assert.Equal("Федотов Алексей", child2.Property("source").Value.ToString());
            Assert.Equal("Федотов Алексей", child2.Property("result").Value.ToString());
            Assert.Equal(0, child2.Property("qc").Value.ToObject <int>());

            var child3 = firstRequest.ElementAt(2);

            Assert.Equal("Москва, Сухонская улица, 11 кв 89", child3.Property("source").Value.ToString());
            Assert.Equal("г Москва, ул Сухонская, д 11, кв 89", child3.Property("result").Value.ToString());
            Assert.Empty(child3.Property("unparsed_parts").Value.ToString());
            Assert.Equal(0, child3.Property("qc").Value.ToObject <int>());

            var child4 = firstRequest.ElementAt(3);

            Assert.Equal("8 916 823 3454", child4.Property("source").Value.ToString());
            Assert.Equal("Мобильный", child4.Property("type").Value.ToString());
            Assert.Equal("+7 916 823-34-54", child4.Property("phone").Value.ToString());
            Assert.Equal(0, child4.Property("qc").Value.ToObject <int>());

            var secondRequest = requests.ElementAt(1).Children <JObject>();

            child1 = secondRequest.ElementAt(0);

            Assert.Equal("2", child1.Property("source").Value.ToString());

            child2 = secondRequest.ElementAt(1);

            Assert.Equal("Иванов Сергей Владимирович", child2.Property("source").Value.ToString());
            Assert.Equal("Иванов Сергей Владимирович", child2.Property("result").Value.ToString());
            Assert.Equal(0, child2.Property("qc").Value.ToObject <int>());

            child3 = secondRequest.ElementAt(2);

            Assert.Equal("мск,улица свободы,65,12", child3.Property("source").Value.ToString());
            Assert.Equal("г Москва, ул Свободы, д 65, кв 12", child3.Property("result").Value.ToString());
            Assert.Empty(child3.Property("unparsed_parts").Value.ToString());
            Assert.Equal(0, child3.Property("qc").Value.ToObject <int>());

            child4 = secondRequest.ElementAt(3);

            Assert.Equal("495 663-12-53", child4.Property("source").Value.ToString());
            Assert.Equal("Стационарный", child4.Property("type").Value.ToString());
            Assert.Equal("+7 495 663-12-53", child4.Property("phone").Value.ToString());
            Assert.Equal(0, child4.Property("qc").Value.ToObject <int>());

            var thirdRequest = requests.ElementAt(2).Children <JObject>();

            child1 = thirdRequest.ElementAt(0);

            Assert.Equal("3", child1.Property("source").Value.ToString());

            child2 = thirdRequest.ElementAt(1);

            Assert.Equal("Ольга Павловна Ященко", child2.Property("source").Value.ToString());
            Assert.Equal("Ященко Ольга Павловна", child2.Property("result").Value.ToString());
            Assert.Equal(0, child2.Property("qc").Value.ToObject <int>());

            child3 = thirdRequest.ElementAt(2);

            Assert.Equal("Спб, ул Петрозаводская 8", child3.Property("source").Value.ToString());
            Assert.Equal("г Санкт-Петербург, ул Петрозаводская, д 8", child3.Property("result").Value.ToString());
            Assert.Empty(child3.Property("unparsed_parts").Value.ToString());
            Assert.Equal(0, child3.Property("qc").Value.ToObject <int>());

            child4 = thirdRequest.ElementAt(3);

            Assert.Equal("457 07 25", child4.Property("source").Value.ToString());
            Assert.Equal("Стационарный", child4.Property("type").Value.ToString());
            Assert.Equal("+7 812 457-07-25", child4.Property("phone").Value.ToString());
            Assert.Equal(1, child4.Property("qc").Value.ToObject <int>());
        }
        public async Task CompositeTest()
        {
            var client = await LoginTask()
                         .ConfigureAwait(false);

            try
            {
                // characters to avoid
                // " json injection
                // \ json & soql injection
                // ' soql injection, because string is quoted by '
                // / url injection, cannot upsert w/ external id
                // & url param injection, & need to be escaped
                // % url param param injection, % need to be escaped
                // + url param injection, converted to space in query
                // $ url param injection
                const string testSubject = "UnitTest"; // @!~-.,=_[]()*`";

                var request = new CompositeRequest(true);
                request.Create("1create", "Product2", Dnf.Assign(GetTestProduct2(), new JObject
                {
                    ["Name"]            = $"UnitTest{Guid.NewGuid():N}",
                    ["ProductCode"]     = $"{testSubject}",
                    ["CurrencyIsoCode"] = "USD"
                }));
                request.Query("1query", @"
SELECT Id, ProductCode
FROM Product2
WHERE Id = '@{1create.id}'"); /*
                               * AND ProductCode = {Dnf.SOQLString($"{testSubject}")}");//*/
                request.Update("2update", "Product2", new JObject
                {
                    ["Id"] = "@{1query.records[0].Id}",
                    //["ProductCode"] = $"UnitTest{testSubject}2",
                    ["ProductCode"] = "@{1query.records[0].ProductCode}2"
                });
                request.Retrieve("2retrieve", "Product2", "@{1query.records[0].Id}", "Id", "ProductCode");
                request.UpsertExternal("3upsert", "Product2", "Id", new JObject
                {
                    //["Id"] = $"@{{1query.records[0].Id}}",
                    ["Id"]         = "@{2retrieve.Id}",
                    ["ExternalId"] = "U2"
                });
                request.Query("3_query", @"
SELECT Id, ProductCode
FROM Product2
WHERE Id = '@{2retrieve.Id}'
AND ProductCode = '@{2retrieve.ProductCode}'
AND ExternalId = 'U2'");
                request.Delete("4delete", "Product2", "@{3_query.records[0].Id}");
                var result = await client.Composite.PostAsync(request)
                             .ConfigureAwait(false);

                WriteLine(result.ToString());
                result.Assert();
            }
            finally
            {
                await DeleteTestingRecords(client)
                .ConfigureAwait(false);
            }
        }
        public async Task CompositeJsonInjectionTest()
        {
            var client = await LoginTask()
                         .ConfigureAwait(false);

            try
            {
                var request = new CompositeRequest(true);
                request.Create("create", "Case", new JObject
                {
                    ["Subject"] = "UnitTest\",\"SuppliedName\":\"D"
                });
                request.Query("query", @"
SELECT Id, Subject, SuppliedName FROM Case WHERE Id = '@{create.id}'");
                request.Query("query2", @"
SELECT Id, Subject, SuppliedName FROM Case
WHERE Id = '@{query.records[0].Id}'
AND Subject = '@{query.records[0].Subject}'");
                request.Update("update", "Case", new JObject
                {
                    ["Id"]      = "@{query2.records[0].Id}",
                    ["Subject"] = "@{query2.records[0].Subject}"
                });
                request.Query("updated", @"
SELECT Id, Subject, SuppliedName FROM Case
WHERE Id = '@{create.id}'
AND Subject = 'UnitTest'
AND SuppliedName = 'D'");
                request.Delete("delete", "Case", "@{updated.records[0].Id}");
                var result = await client.Composite.PostAsync(request)
                             .ConfigureAwait(false);

                result.Assert();
            }
            finally
            {
                await DeleteTestingRecords(client)
                .ConfigureAwait(false);
            }

            await Assert.ThrowsAsync <ForceException>(async() =>
            {
                var request = new CompositeRequest(true);
                request.Create("create", "Case", new JObject
                {
                    ["Subject"] = "UnitTest\\"
                });
                request.Query("query", @"
SELECT Id, Subject, SuppliedName FROM Case WHERE Id = '@{create.id}'");
                request.Query("query2", @"
SELECT Id, Subject, SuppliedName FROM Case
WHERE Id = '@{query.records[0].Id}'
AND Subject = '@{query.records[0].Subject}'");
                request.Update("update", "Case", new JObject
                {
                    ["Id"]      = "@{query2.records[0].Id}",
                    ["Subject"] = "@{query2.records[0].Subject}\""
                });
                request.Delete("delete", "Case", "@{updated.records[0].Id}");
                var result = await client.Composite.PostAsync(request)
                             .ConfigureAwait(false);
                result.Assert();
            })
            .ConfigureAwait(false);
        }
        public async Task CompositeFailTest()
        {
            var client = await LoginTask()
                         .ConfigureAwait(false);

            // characters to avoid
            // & break query string i.e. q=... MALFORMED_QUERY
            // + break query string, my guess: converted to space
            // ' upsert failed, not found
            // / upsert failed, not found
            // % transaction all rollback
            // \ transaction all rollback
            // $ transaction all rollback


            await Assert.ThrowsAsync <ForceException>(async() =>
            {
                const string testName = "UnitTest$@\\/ %!~-[].,()`=&+*_\"'{}";

                var request = new CompositeRequest(true);
                request.Create("create", "Case", new JObject
                {
                    ["Subject"] = $"{testName}"
                });
                request.Query("query1", $@"
SELECT Id, Subject
FROM Case
WHERE Id = '@{{create.id}}'
AND Subject = {Dnf.SoqlString($"{testName}")}");
                request.Update("update", "Case", new JObject
                {
                    ["Id"]      = "@{create.id}",
                    ["Subject"] = $"UnitTest{testName}"
                });
                request.Query("query2", $@"
SELECT Id, Subject
FROM Case
WHERE Id = '@{{create.id}}'
AND Subject = {Dnf.SoqlString($"UnitTest{testName}")}");
                request.UpsertExternal("upsert", "Case", "Id", new JObject
                {
                    ["Id"]      = "@{query.records[0].Id}",
                    ["Subject"] = $"UnitTest {testName}"
                });
                request.Query("query3", $@"
SELECT Id, Subject
FROM Case
WHERE Id = '@{{create.id}}'
AND Subject = {Dnf.SoqlString($"UnitTest {testName}")}");
                request.Delete("delete", "Case", "1@{query2.records[0].Id}");
                var result = await client.Composite.PostAsync(request)
                             .ConfigureAwait(false);
                WriteLine(result.ToString());
                Assert.NotNull(result.Errors("query3"));
                Assert.Equal(
                    result.Requests().Count - 1,
                    result.Errors().Values
                    .Count(errs => errs.Any(err => err.Message == "The transaction was rolled back since another operation in the same transaction failed.")));
                result.Assert();
            })
            .ConfigureAwait(false);
        }