public void TestCorrectParamsWithFields()
        {
            ICreateItemByIdRequest request = ItemWebApiRequestBuilder.CreateItemRequestWithParentId("{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}")
                                             .ItemTemplatePath("/Sample/Sample Item")
                                             .ItemName("item name")
                                             .AddFieldsRawValuesByNameToSet("field1", "value1")
                                             .AddFieldsRawValuesByNameToSet("field2", "value2")
                                             .Build();

            ICreateItemByIdRequest autocompletedRequest = this.requestMerger.FillCreateItemByIdGaps(request);

            string result   = this.builder.GetUrlForRequest(autocompletedRequest);
            string expected = "http://mobiledev1ua1.dk.sitecore.net:7119/-/item/v234%2fsitecore%2fshell" +
                              "?sc_database=web" +
                              "&language=en" +
                              "&template=sample%2fsample%20item" +
                              "&name=item%20name" +
                              "&sc_itemid=%7b110d559f-dea5-42ea-9c1c-8a5df7e70ef9%7d";

            string fieldsResult         = this.builder.GetFieldValuesList(autocompletedRequest);
            string expectedFieldsResult = "field1=value1&field2=value2";

            Assert.AreEqual(expected, result);
            Assert.AreEqual(expectedFieldsResult, fieldsResult);
        }
        public void TestFieldsAppending()
        {
            Dictionary <string, string> fields = new Dictionary <string, string>();

            fields.Add("field1", "VaLuE1");
            fields.Add("field2", "VaLuE2");

            ICreateItemByIdRequest request = ItemWebApiRequestBuilder.CreateItemRequestWithParentId("{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}")
                                             .ItemTemplatePath("/Sample/Sample Item")
                                             .ItemName("ItEmNaMe")
                                             .Database("db")
                                             .Language("lg")
                                             .Payload(PayloadType.Full)
                                             .AddFieldsRawValuesByNameToSet(fields)
                                             .AddFieldsRawValuesByNameToSet("field3", "VaLuE3")
                                             .Build();

            ICreateItemByIdRequest autocompletedRequest = this.requestMerger.FillCreateItemByIdGaps(request);

            string result   = this.builder.GetUrlForRequest(autocompletedRequest);
            string expected =
                "http://mobiledev1ua1.dk.sitecore.net:7119/-/item/v234%2fsitecore%2fshell" +
                "?sc_database=db" +
                "&language=lg" +
                "&payload=full" +
                "&template=sample%2fsample%20item" +
                "&name=ItEmNaMe" +
                "&sc_itemid=%7b110d559f-dea5-42ea-9c1c-8a5df7e70ef9%7d";

            string fieldsResult         = this.builder.GetFieldValuesList(autocompletedRequest);
            string expectedFieldsResult = "field1=VaLuE1&field2=VaLuE2&field3=VaLuE3";

            Assert.AreEqual(expected, result);
            Assert.AreEqual(expectedFieldsResult, fieldsResult);
        }
        public async void TestCreateItemByIdWithInternationalNameAndFields()
        {
            await this.RemoveAll();

            var          expectedItem = this.CreateTestItem("International Слава Україні ウクライナへの栄光 عالمي");
            const string CreatedTitle = "ఉక్రెయిన్ కు గ్లోరీ Ruhm für die Ukraine";
            const string CreatedText  = "युक्रेन गौरव גלורי לאוקראינה";
            var          request      = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                                        .ItemTemplatePath(testData.Items.Home.Template)
                                        .ItemName(expectedItem.DisplayName)
                                        .Database("master")
                                        .AddFieldsRawValuesByNameToSet("Title", CreatedTitle)
                                        .AddFieldsRawValuesByNameToSet("Text", CreatedText)
                                        .Payload(PayloadType.Content)
                                        .Build();

            var createResponse = await session.CreateItemAsync(request);

            var resultItem = this.CheckCreatedItem(createResponse, expectedItem);

            Assert.AreEqual(CreatedTitle, resultItem["Title"].RawValue);
            Assert.AreEqual(CreatedText, resultItem["Text"].RawValue);

            this.GetAndCheckItem(expectedItem, resultItem);
        }
        public async void TestCreateItemByIdWithOverridenDatabaseAndLanguageInRequest()
        {
            await this.RemoveAll();

            const string Db           = "web";
            const string Language     = "da";
            var          expectedItem = this.CreateTestItem("Create danish version in web from request");

            var adminSession =
                SitecoreWebApiSessionBuilder.AuthenticatedSessionWithHost(testData.InstanceUrl)
                .Credentials(testData.Users.Admin)
                .Site(testData.ShellSite)
                .DefaultDatabase("master")
                .DefaultLanguage("en")
                .BuildSession();

            var request = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(testData.Items.CreateItemsHere.Id)
                          .ItemTemplatePath(expectedItem.Template)
                          .ItemName(expectedItem.DisplayName)
                          .Database(Db)
                          .Language(Language)
                          .Build();

            var createResponse = await adminSession.CreateItemAsync(request);

            var resultItem = this.CheckCreatedItem(createResponse, expectedItem);

            Assert.AreEqual(Db, resultItem.Source.Database);
            Assert.AreEqual(Language, resultItem.Source.Language);
        }
        public void TestCreateItemWithEmptyOrNullFieldsReturnsException()
        {
            var exception = Assert.Throws <ArgumentNullException>(() => ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                                                                  .ItemTemplatePath("/Sample/Sample Item")
                                                                  .ItemName("SomeValidName")
                                                                  .AddFieldsRawValuesByNameToSet(null, "somevalue"));

            Assert.IsTrue(exception.Message.Contains("fieldName"));

            var exception1 = Assert.Throws <ArgumentException>(() => ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                                                               .ItemTemplatePath("/Sample/Sample Item")
                                                               .ItemName("SomeValidName")
                                                               .AddFieldsRawValuesByNameToSet("", "somevalue"));

            Assert.AreEqual("CreateItemByIdRequestBuilder.fieldName : The input cannot be empty.", exception1.Message);

            var exception2 = Assert.Throws <ArgumentNullException>(() => ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                                                                   .ItemTemplatePath("/Sample/Sample Item")
                                                                   .ItemName("SomeValidName")
                                                                   .AddFieldsRawValuesByNameToSet("somekey", null));

            Assert.IsTrue(exception2.Message.Contains("fieldValue"));

            var exception3 = Assert.Throws <ArgumentException>(() => ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                                                               .ItemTemplatePath("/Sample/Sample Item")
                                                               .ItemName("SomeValidName")
                                                               .AddFieldsRawValuesByNameToSet("somekey", ""));

            Assert.AreEqual("CreateItemByIdRequestBuilder.fieldValue : The input cannot be empty.", exception3.Message);
        }
        public async void TestCreateItemByIdFromUnknownBranchCausesException()
        {
            await this.RemoveTestItemsFromMasterAndWebAsync();

            const string ItemFromBranchName = "ITEM ID   A default name of the branch should be used";
            //      const string itemFromBranchName = "Multiple item brunch";

            var request = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                          .BranchId(NonExistingGuid)
                          .ItemName(ItemFromBranchName)
                          .Database("master")
                          .Language("en")
                          .Payload(PayloadType.Content)
                          .Build();


            var ex = Assert.Throws <ParserException>(async() =>
            {
                await session.CreateItemAsync(request);
            });


            Assert.AreEqual("Sitecore.MobileSDK.API.Exceptions.WebApiJsonErrorException", ex.InnerException.GetType().FullName);
            var castedException = ex.InnerException as WebApiJsonErrorException;

            Assert.AreEqual(500, castedException.Response.StatusCode);
            Assert.AreEqual("Template item not found.", castedException.Response.Message);
        }
        public async void TestCreateItemByIdFromBranch()
        {
            await this.RemoveTestItemsFromMasterAndWebAsync();

            const string ItemFromBranchName = "ITEM ID   A default name of the branch should be used";

            //      const string itemFromBranchName = "Multiple item brunch";
            TestEnvironment.Item expectedItem = this.CreateTestItem(ItemFromBranchName);

            var request = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                          .BranchId("{14416817-CDED-45AF-99BF-2DE9883B7AC3}")
                          .ItemName(ItemFromBranchName)
                          .Database("master")
                          .Language("en")
                          .Payload(PayloadType.Content)
                          .Build();

            var createResponse = await session.CreateItemAsync(request);

            this.testData.AssertItemsCount(1, createResponse);

            ISitecoreItem resultItem = createResponse[0];

            this.testData.AssertItemsAreEqual(expectedItem, resultItem);


            var readJustCreatedItemRequest = ItemWebApiRequestBuilder.ReadItemsRequestWithId(resultItem.Id)
                                             .Database("master")
                                             .Build();
            var readJustCreatedItemResponse = await this.session.ReadItemAsync(readJustCreatedItemRequest);

            this.testData.AssertItemsCount(1, readJustCreatedItemResponse);
            this.testData.AssertItemsAreEqual(expectedItem, readJustCreatedItemResponse[0]);
        }
        public async void UploadJpgFileWithInternationalItemNameAndParentPath()
        {
            await this.RemoveAll();

            //create international parent
            var createRequest = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.UploadMediaHere.Id)
                                .ItemTemplatePath(testData.Items.Home.Template)
                                .ItemName("युक्रेन")
                                .Database("master")
                                .Build();
            var createResponse = await session.CreateItemAsync(createRequest);

            //Assert.AreEqual(1, createResponse.ResultCount);
            using (var image = GetStreamFromUrl(TestEnvironment.Images.Jpeg._30x30))
            {
                const string ItemName   = "International Слава Україні ウクライナへの栄光";
                const string Database   = "master";
                string       parentPath = createResponse[0].Path.Remove(0, 23);
                var          request    = ItemWebApiRequestBuilder.UploadResourceRequestWithParentPath(parentPath)
                                          .ItemDataStream(image)
                                          .Database(Database)
                                          .ItemName(ItemName)
                                          .FileName("ク.gif")
                                          .Build();
                var response = await this.session.UploadMediaResourceAsync(request);

                Assert.AreEqual(1, response.ResultCount);
                Assert.AreEqual(ItemName, response[0].DisplayName);
                this.AssertImageUploaded(response[0].Path, Database);
            }
        }
        public void TestTemplateCanNotBeEmpty()
        {
            var builder = ItemWebApiRequestBuilder.CreateItemRequestWithParentId("{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}");

            TestDelegate action = () => builder.ItemTemplatePath(" ");

            Assert.Throws <ArgumentException>(action);
        }
        public void TestCreateItemByInvalidIdReturnsException()
        {
            Exception exception = Assert.Throws <ArgumentException>(() => ItemWebApiRequestBuilder.CreateItemRequestWithParentId(testData.Items.Home.Path)
                                                                    .ItemTemplatePath("Some template")
                                                                    .ItemName("Item with invalid parent id")
                                                                    .Build());

            Assert.AreEqual("CreateItemByIdRequestBuilder.ItemId : Item id must have curly braces '{}'", exception.Message);
        }
        public void TestCreateItemByEmptyIdReturnsException()
        {
            Exception exception = Assert.Throws <ArgumentException>(() => ItemWebApiRequestBuilder.CreateItemRequestWithParentId("")
                                                                    .ItemTemplatePath("Some template")
                                                                    .ItemName("Item with empty parent id")
                                                                    .Build());

            Assert.AreEqual("CreateItemByIdRequestBuilder.ItemId : The input cannot be empty.", exception.Message);
        }
        public void TestCreateItemByIdhWithNullTemplateReturnsException()
        {
            Exception exception = Assert.Throws <ArgumentNullException>(() => ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                                                                        .ItemTemplatePath(null)
                                                                        .ItemName("Item with empty template")
                                                                        .Build());

            Assert.IsTrue(exception.Message.Contains("CreateItemByIdRequestBuilder.ItemTemplate"));
        }
        public void TestCreateItemByIdWithEmptyNameReturnsException()
        {
            var exception = Assert.Throws <ArgumentException>(() => ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                                                              .ItemTemplatePath(testData.Items.Home.Template)
                                                              .ItemName("")
                                                              .Build());

            Assert.AreEqual("CreateItemByIdRequestBuilder.ItemName : The input cannot be empty.", exception.Message);
        }
        public void TestCreateItemByIdWithEmptyDatabaseDoNotReturnsException()
        {
            var request = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(testData.Items.Home.Id)
                          .ItemTemplatePath("Some template")
                          .ItemName("Item with empty db")
                          .Database("")
                          .Build();

            Assert.IsNotNull(request);
        }
        public void TestCreateItemByIdWithSpacesOnlyInLanguageReturnsException()
        {
            Exception exception = Assert.Throws <ArgumentException>(() => ItemWebApiRequestBuilder.CreateItemRequestWithParentId(testData.Items.Home.Id)
                                                                    .ItemTemplatePath("Some template")
                                                                    .ItemName("Item with empty language")
                                                                    .Language("  ")
                                                                    .Build());

            Assert.AreEqual("CreateItemByIdRequestBuilder.Language : The input cannot be empty.", exception.Message);
        }
        public void TestFieldWithDuplicatedKeyWillCrash()
        {
            var requestBuilder = ItemWebApiRequestBuilder.CreateItemRequestWithParentId("{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}")
                                 .ItemTemplatePath("/Sample/Sample Item")
                                 .ItemName("ItEmNaMe")
                                 .AddFieldsRawValuesByNameToSet("field1", "VaLuE1")
                                 .AddFieldsRawValuesByNameToSet("field2", "VaLuE2");

            TestDelegate action = () => requestBuilder.AddFieldsRawValuesByNameToSet("field1", "VaLuE3");

            Assert.Throws <InvalidOperationException>(action);
        }
        public async void TestCreateItemWithNotExistentItemId()
        {
            const string Id      = "{000D009F-D000-000A-0C0C-0A0DF0E00EF0}";
            var          request = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(Id)
                                   .ItemTemplatePath(testData.Items.Home.Template)
                                   .ItemName("item with not existent id")
                                   .Database("master")
                                   .Build();

            var createResponse = await session.CreateItemAsync(request);

            Assert.AreEqual(0, createResponse.ResultCount);
        }
        public void TestCreateItemByIdAndGetDuplicateFieldsReturnsException()
        {
            const string FieldName = "Text";

            var exception = Assert.Throws <InvalidOperationException>(() =>
                                                                      ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                                                                      .ItemTemplatePath(testData.Items.Home.Template)
                                                                      .ItemName("Get duplicate fields")
                                                                      .AddFieldsToRead(FieldName, "Title", FieldName)
                                                                      .Build());

            Assert.AreEqual("CreateItemByIdRequestBuilder.Fields : duplicate fields are not allowed", exception.Message);
        }
        public async void TestCreateItemByPathAndTemplateIdWithoutFieldsSet()
        {
            await this.RemoveAll();

            var expectedItem = this.CreateTestItem("Create by parent path and template ID");

            var request = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                          .ItemTemplatePath(testData.Items.Home.TemplateId)
                          .ItemName(expectedItem.DisplayName)
                          .Database("master")
                          .Build();

            var createResponse = await session.CreateItemAsync(request);

            var resultItem = this.CheckCreatedItem(createResponse, expectedItem);

            this.GetAndCheckItem(expectedItem, resultItem);
        }
        private async void SendRequest()
        {
            try
            {
                using (ISitecoreWebApiSession session = this.instanceSettings.GetSession())
                {
                    var request = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.pathField.Text)
                                  .ItemTemplatePath("Sample/Sample Item")
                                  .ItemName(this.nameField.Text)
                                  .AddFieldsRawValuesByNameToSet("Title", titleField.Text)
                                  .AddFieldsRawValuesByNameToSet("Text", textField.Text)
                                  .Build();

                    this.ShowLoader();

                    ScItemsResponse response = await session.CreateItemAsync(request);

                    if (response.Any())
                    {
                        ISitecoreItem item = response[0];
                        this.CreatedItemId = item.Id;
                        AlertHelper.ShowLocalizedAlertWithOkOption("The item created successfully", "Item path: " + item.Path);
                    }
                    else
                    {
                        AlertHelper.ShowLocalizedAlertWithOkOption("Message", "Item is not exist");
                    }
                }
            }
            catch (Exception e)
            {
                AlertHelper.ShowLocalizedAlertWithOkOption("Error", e.Message);
            }
            finally
            {
                BeginInvokeOnMainThread(delegate
                {
                    this.HideLoader();
                });
            }
        }
        public async void TestCreateItemByIdWithNotExistentFields()
        {
            await this.RemoveAll();

            var          expectedItem  = this.CreateTestItem("Set not existent field");
            const string CreatedTitle  = "Existent title";
            const string CreatedTexttt = "Not existent texttt";
            var          request       = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(this.testData.Items.CreateItemsHere.Id)
                                         .ItemTemplatePath(testData.Items.Home.Template)
                                         .ItemName(expectedItem.DisplayName)
                                         .Database("master")
                                         .Payload(PayloadType.Content)
                                         .AddFieldsRawValuesByNameToSet("Title", CreatedTitle)
                                         .AddFieldsRawValuesByNameToSet("Texttt", CreatedTexttt)
                                         .Build();

            var createResponse = await session.CreateItemAsync(request);

            var resultItem = this.CheckCreatedItem(createResponse, expectedItem);

            Assert.AreEqual(CreatedTitle, resultItem["Title"].RawValue);

            this.GetAndCheckItem(expectedItem, resultItem);
        }
        protected override async void PerformCreateRequest()
        {
            var parentId        = this.ItemField.Text;
            var itemName        = this.ItemNameField.Text;
            var titleFieldValue = this.ItemTitleFieldValue.Text;
            var textFieldValue  = this.ItemTextFieldValue.Text;

            if (string.IsNullOrWhiteSpace(parentId))
            {
                Toast.MakeText(this, "Parent Item ID should not be empty", ToastLength.Short).Show();
                return;
            }

            if (string.IsNullOrWhiteSpace(itemName))
            {
                Toast.MakeText(this, "Item name should not be empty", ToastLength.Short).Show();
                return;
            }

            try
            {
                var builder = ItemWebApiRequestBuilder.CreateItemRequestWithParentId(parentId)
                              .ItemTemplatePath("Sample/Sample Item")
                              .ItemName(itemName);

                if (!string.IsNullOrEmpty(titleFieldValue))
                {
                    builder.AddFieldsRawValuesByNameToSet("Title", titleFieldValue);
                }

                if (!string.IsNullOrEmpty(textFieldValue))
                {
                    builder.AddFieldsRawValuesByNameToSet("Text", textFieldValue);
                }

                this.SetProgressBarIndeterminateVisibility(true);

                using (var session = this.Prefs.Session)
                {
                    var response = await session.CreateItemAsync(builder.Build());

                    this.SetProgressBarIndeterminateVisibility(false);
                    if (response.ResultCount == 0)
                    {
                        DialogHelper.ShowSimpleDialog(this, "Failed", "Failed to create item");
                    }
                    else
                    {
                        this.createItemId = response[0].Id;

                        var message = "Item path : " + response[0].Path;
                        DialogHelper.ShowSimpleDialog(this, "Item created", message);
                    }
                }
            }
            catch (System.Exception exception)
            {
                this.SetProgressBarIndeterminateVisibility(false);

                var title = this.GetString(Resource.String.text_error);
                DialogHelper.ShowSimpleDialog(this, title, exception.Message);
            }
        }