public async Task <PageData> GeneratePageData(string itemid, PayloadType itemLoadType, List <ScopeType> itemScopeTypes, string datasourceFieldName, string itemLanguage = "en")
        {
            ScItemsResponse response = await GetItemById(itemid, itemLoadType, itemScopeTypes, itemLanguage);

            if (response == null)
            {
                return(null);
            }

            ISitecoreItem item = response.First();

            if (item == null)
            {
                return(null);
            }

            PageData pageData = new PageData {
                PageName               = item.DisplayName,
                ItemContext            = response,
                NavigationTitle        = item.GetValueFromField(Constants.Sitecore.Fields.Navigation.NavigationTitle),
                PageType               = item.GetTemplateName(),
                DataSourceFromChildren = await GetDatasourceFromChildren(item),
                DataSourceFromField    = await GetDataSourceFromFieldName(item, datasourceFieldName)
            };

            return(pageData);
        }
        private void PreFetchSingleProductOrVariantData(ISitecoreItem item)
        {
            var productItem = item as ContentNodeSitecoreItem;

            if (productItem == null)
            {
                return;
            }

            int productId  = int.Parse(productItem.Node.ItemId);
            var repository = ObjectFactory.Instance.Resolve <IRepository <Product> >();
            var product    = repository.Select(new SingleProductQuery(productId)).FirstOrDefault();

            if (product == null)
            {
                return;
            }

            if (product.IsVariant)
            {
                AddVariantDataToCache(product);
            }
            else
            {
                AddProductDataToCache(product);
            }
        }
        public async Task <IEnumerable <ListItem> > GenerateListItemsFromChildren(ScItemsResponse itemsResponse)
        {
            List <ListItem> list = new List <ListItem> ();


            for (int i = 0; i < itemsResponse.ResultCount; i++)
            {
                ISitecoreItem item = itemsResponse[i];

                if (item == null)
                {
                    continue;
                }

                ListItem listlItem = new ListItem {
                    Header         = item.GetValueFromField(Constants.Sitecore.Fields.PageContent.Title),
                    Text           = item.GetValueFromField(Constants.Sitecore.Fields.PageContent.Summary),
                    NavigationItem = item.Id,
                    NavigationText = item.GetValueFromField(Constants.Sitecore.Fields.PageContent.Title),
                    SitecoreItem   = item,
                    Media          = await _cachedMediaRepository.GetCache(item.GetImageUrlFromMediaField(Constants.Sitecore.Fields.PageContent.Image))
                };

                list.Add(listlItem);
            }

            return(list);
        }
Example #4
0
        public void SetItem(ISitecoreItem item)
        {
            string Title = item[SCHelper.TitleFieldName].RawValue;

            this.RegionName.Text  = Title;
            this.RegionIcon.Image = UIImage.FromFile("Images/" + Title + ".png");
        }
Example #5
0
        private static object ConvertItemToModel(ISitecoreItem item, SitecoreTemplateAttributeInfo sitecoreTemplateAttributeInfo)
        {
            var result = Activator.CreateInstance(sitecoreTemplateAttributeInfo.Type);

            ((ISitecoreTemplate)result).Id = item.Id;

            foreach (var fieldInfo in sitecoreTemplateAttributeInfo.SitecoreFieldAttributeInfos)
            {
                var propertyInfo = fieldInfo.PropertyInfo;
                var propertyType = propertyInfo.PropertyType;

                if (propertyType.IsGenericEnumerable())
                {
                    var genericArguments = propertyType.GetGenericArguments();

                    var children = ConvertChildren(genericArguments[0], item.GetChildren());

                    if (children != null)
                    {
                        propertyInfo.SetValue(result, children);
                    }

                    continue;
                }

                SetFieldValue(item, result, fieldInfo);
            }

            return(result);
        }
Example #6
0
        public void TestParseValidResponse()
        {
            string          rawResponse = VALID_RESPONSE;
            ScItemsResponse response    = ScItemsParser.Parse(rawResponse, CancellationToken.None);

            Assert.AreEqual(1, response.ResultCount);

            ISitecoreItem item1 = response[0];

            Assert.AreEqual("Home", item1.DisplayName);
            Assert.AreEqual("web", item1.Source.Database);
            Assert.AreEqual(true, item1.HasChildren);
            Assert.AreEqual("en", item1.Source.Language);
            Assert.AreEqual("{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}", item1.Id);

            string expectedFullId = "/{11111111-1111-1111-1111-111111111111}/{0DE95AE4-41AB-4D01-9EB0-67441B7C2450}/{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}";

            Assert.AreEqual(expectedFullId, item1.LongId);
            Assert.AreEqual("/sitecore/content/Home", item1.Path);
            Assert.AreEqual("Sample/Sample Item", item1.Template);
            Assert.AreEqual(1, item1.Source.VersionNumber);

            Assert.AreEqual(2, item1.FieldsCount);
            IField field1 = item1.Fields.ElementAt(0);

            Assert.AreEqual("{75577384-3C97-45DA-A847-81B00500E250}", field1.FieldId);
            IField field2 = item1.Fields.ElementAt(1);

            Assert.AreEqual("{A60ACD61-A6DB-4182-8329-C957982CEC74}", field2.FieldId);
        }
        public Task <List <NavigationItem> > GetMenu()
        {
            return(Task.Run(() =>
            {
                ISitecoreItem rootItem = _sitecoreItemService.GetSitecoreItemRootMock(_blazorContext.ContextLanguage);


                List <NavigationItem> list = new List <NavigationItem>
                {
                    new NavigationItem() //Home
                    {
                        Item = rootItem,
                        Url = rootItem.Url,
                        Children = null
                    }
                };

                foreach (ISitecoreItem item in rootItem.Children)
                {
                    if (item == null)
                    {
                        continue;
                    }

                    list.Add(
                        CreateNavigationItem(item)
                        );
                }


                return list;
            }));
        }
        public async void TestDeleteItemByIdAsAnonymousFromShellSiteReturnsException()
        {
            await this.RemoveAll();

            var anonymousSession = SitecoreWebApiSessionBuilder.AnonymousSessionWithHost(testData.InstanceUrl)
                                   .DefaultDatabase("master")
                                   .Site(testData.ShellSite)
                                   .BuildSession();

            ISitecoreItem item = await this.CreateItem("Item to delete as anonymous");

            var request = ItemWebApiRequestBuilder.DeleteItemRequestWithPath(item.Path)
                          .Build();

            TestDelegate testCode = async() =>
            {
                var   task = anonymousSession.DeleteItemAsync(request);
                await task;
            };
            Exception exception = Assert.Throws <ParserException>(testCode);

            Assert.AreEqual("[Sitecore Mobile SDK] Data from the internet has unexpected format", exception.Message);
            Assert.AreEqual("Sitecore.MobileSDK.API.Exceptions.WebApiJsonErrorException", exception.InnerException.GetType().ToString());
            Assert.AreEqual("Access to site is not granted.", exception.InnerException.Message);

            await session.DeleteItemAsync(request);
        }
Example #9
0
        public static ISitecoreInternalLinkField MockInternalLinkField(
            string path,
            string itemUrl,
            ISitecoreItem targetItem,
            string value          = "",
            HtmlString htmlString = null)
        {
            var customField = new Mock <ISitecoreInternalLinkField>();

            customField
            .Setup(x => x.Path)
            .Returns(path);

            customField
            .Setup(x => x.ItemUrl)
            .Returns(itemUrl);

            customField
            .Setup(x => x.TargetItem)
            .Returns(targetItem);

            customField
            .Setup(x => x.Value)
            .Returns(value);

            customField
            .Setup(x => x.RenderToHtml(It.IsAny <string>()))
            .Returns(htmlString);

            return(customField.Object);
        }
        public Task <List <NavigationItem> > GetMenu(IJSRuntime jsRuntime)
        {
            string currentLanguage = _blazorStateMachine.Language; //await _blazorContext.GetContextLanguageAsync(jsRuntime);

            Console.WriteLine("GetMenu " + currentLanguage);
            ISitecoreItem rootItem = _sitecoreItemService.GetSitecoreItemRootMock(currentLanguage);


            List <NavigationItem> list = new List <NavigationItem>
            {
                new NavigationItem()    //Home
                {
                    Item     = rootItem,
                    Url      = rootItem.Url,
                    Children = null
                }
            };

            foreach (ISitecoreItem item in rootItem.Children)
            {
                if (item == null)
                {
                    continue;
                }

                list.Add(
                    CreateNavigationItem(item)
                    );
            }


            return(Task.FromResult <List <NavigationItem> >(list));
        }
        private async Task <IMessageActivity> GetReplyForCityNamed(string name, Activity activity)
        {
            ISitecoreItem item = await network.GetCityNamed(activity.Text);

            IMessageActivity reply = null;

            if (item == null)
            {
                reply = activity.CreateReply("item not found");
            }
            else
            {
                string itemOverview = Helper.PrimitiveHTMLTagsRemove(item["Overview"].RawValue);
                string itemTitle    = item["Title"].RawValue;
                string imagePath    = ScNetworkSettings.instanceUrl + Helper.GetImagePathFromImageRawValue(item["Image"].RawValue);

                string replyText = "### " + itemTitle + "\n\n***\n\n" + itemOverview + "\n\n***\n\n";

                reply             = activity.CreateReply(replyText);
                reply.Attachments = new List <Attachment>();

                reply.Attachments.Add(new Attachment()
                {
                    ContentUrl  = imagePath,
                    ContentType = "image/png",
                    Name        = itemTitle
                });
            }

            return(reply);
        }
        public void ShowFieldsForItem(ISitecoreItem item)
        {
            BeginInvokeOnMainThread(delegate
            {
                this.Title = item.DisplayName;

                this.CleanupTableViewBindingsSync();

                this.fieldsDataSource    = new FieldsDataSource();
                this.fieldsTableDelegate = new FieldCellSelectionHandler();


                FieldsDataSource dataSource = this.fieldsDataSource;
                dataSource.SitecoreItem     = item;
                dataSource.TableView        = this.TableView;


                FieldCellSelectionHandler tableDelegate = this.fieldsTableDelegate;
                tableDelegate.TableView    = this.TableView;
                tableDelegate.SitecoreItem = item;

                FieldCellSelectionHandler.TableViewDidSelectFieldAtIndexPath onFieldSelected =
                    delegate(UITableView tableView, IField itemField, NSIndexPath indexPath)
                {
                    AlertHelper.ShowLocalizedAlertWithOkOption("Field Raw Value", itemField.RawValue);
                };
                tableDelegate.OnFieldCellSelectedDelegate = onFieldSelected;

                this.TableView.DataSource = dataSource;
                this.TableView.Delegate   = tableDelegate;
                this.TableView.ReloadData();
            });
        }
    public void ShowFieldsForItem(ISitecoreItem item)
    {
      BeginInvokeOnMainThread(delegate
      {
        this.Title = item.DisplayName;

        this.CleanupTableViewBindingsSync();

        this.fieldsDataSource = new FieldsDataSource();
        this.fieldsTableDelegate = new FieldCellSelectionHandler();


        FieldsDataSource dataSource = this.fieldsDataSource;
        dataSource.SitecoreItem = item;
        dataSource.TableView = this.TableView;


        FieldCellSelectionHandler tableDelegate = this.fieldsTableDelegate;
        tableDelegate.TableView = this.TableView;
        tableDelegate.SitecoreItem = item;

        FieldCellSelectionHandler.TableViewDidSelectFieldAtIndexPath onFieldSelected = 
          delegate (UITableView tableView, IField itemField, NSIndexPath indexPath)
        {
          AlertHelper.ShowLocalizedAlertWithOkOption("Field Raw Value", itemField.RawValue);
        };
        tableDelegate.OnFieldCellSelectedDelegate = onFieldSelected;

        this.TableView.DataSource = dataSource;
        this.TableView.Delegate = tableDelegate;
        this.TableView.ReloadData();
      });
    }
Example #14
0
        //Gets the image url from media field
        public static string GetImageUrlFromMediaField(this ISitecoreItem item, string mediafieldName,
                                                       string websiteUrl = null)
        {
            XElement xmlElement = GetXElement(item, mediafieldName);

            if (xmlElement == null)
            {
                return(string.Empty);
            }

            XAttribute attribute = xmlElement
                                   .Attributes()
                                   .FirstOrDefault(attr => attr.Name == "mediaid" || attr.Name == "id");

            if (attribute == null)
            {
                return(string.Empty);
            }

            string mediaId = attribute.Value;

            Guid id = Guid.Parse(mediaId);

            if (string.IsNullOrWhiteSpace(websiteUrl))
            {
                return(String.Format("-/media/{0}", id.ToString("N")));
            }

            return(String.Format("{0}/-/media/{1}", websiteUrl, id.ToString("N")));
        }
        public async void TestDeleteItemByPathWithoutDeleteAccessReturnsException()
        {
            await this.RemoveAll();

            var noAccessSession = SitecoreWebApiSessionBuilder.AuthenticatedSessionWithHost(testData.InstanceUrl)
                                  .Credentials(testData.Users.NoCreateAccess)
                                  .DefaultDatabase("master")
                                  .Site(testData.ShellSite)
                                  .BuildSession();

            ISitecoreItem item = await this.CreateItem("Item to delete without delete access");

            var request = ItemWebApiRequestBuilder.DeleteItemRequestWithPath(item.Path)
                          .Build();

            TestDelegate testCode = async() =>
            {
                var   task = noAccessSession.DeleteItemAsync(request);
                await task;
            };
            Exception exception = Assert.Throws <ParserException>(testCode);

            Assert.AreEqual("[Sitecore Mobile SDK] Data from the internet has unexpected format", exception.Message);
            Assert.AreEqual("Sitecore.MobileSDK.API.Exceptions.WebApiJsonErrorException", exception.InnerException.GetType().ToString());
            Assert.True(exception.InnerException.Message.Contains("DeleteItem - Delete right required"));

            await session.DeleteItemAsync(request);
        }
        private async void GetAndCheckItem(TestEnvironment.Item expectedItem, ISitecoreItem resultItem)
        {
            var readResponse = await this.GetItemById(resultItem.Id);

            this.testData.AssertItemsCount(1, readResponse);
            this.testData.AssertItemsAreEqual(expectedItem, readResponse[0]);
        }
        public async void TestCreateItemByPathFromBranch()
        {
            await this.RemoveTestItemsFromMasterAndWebAsync();

            const string ItemFromBranchName = "Multiple item branch";

            TestEnvironment.Item expectedItem = this.CreateTestItem(ItemFromBranchName);

            var request = ItemWebApiRequestBuilder.CreateItemRequestWithParentPath(this.testData.Items.CreateItemsHere.Path)
                          .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]);
        }
Example #18
0
        public string BuildRouteApiUrl(string language, bool?hasRouteError)
        {
            string baseUrl = $"{_uriHelper.GetBaseUri()}/data/routes";

            string relativeUrl = $"{_uriHelper.ToBaseRelativePath(_uriHelper.GetBaseUri(), _uriHelper.GetAbsoluteUri())}";

            //Incorrect url
            if (hasRouteError.HasValue && hasRouteError.Value)
            {
                return($"{baseUrl}/error/{language}.json");
            }

            ISitecoreItem rootItem = _sitecoreItemService.GetSitecoreItemRootMock(language);

            if (rootItem.GetItSelfAndDescendants().Any(item => item.Url == "/" + relativeUrl) || relativeUrl == "")
            {
                if (relativeUrl.Length <= language.Length)
                {
                    return($"{baseUrl}/{language}.json");
                }

                return($"{baseUrl}{relativeUrl.Substring(language.Length)}/{language}.json");
            }


            return($"{baseUrl}/error/{language}.json");
        }
Example #19
0
        public async void TestUpdateDanishItemByPath()
        {
            await this.RemoveAll();

            const string Language    = "da";
            var          titleValue  = RandomText();
            var          textValue   = RandomText();
            var          itemSession = SitecoreWebApiSessionBuilder.AuthenticatedSessionWithHost(testData.InstanceUrl)
                                       .Credentials(testData.Users.Admin)
                                       .Site(testData.ShellSite)
                                       .DefaultLanguage(Language)
                                       .DefaultDatabase("master")
                                       .BuildSession();
            ISitecoreItem item = await this.CreateItem("Danish item to update", null, itemSession);

            var request = ItemWebApiRequestBuilder.UpdateItemRequestWithPath(item.Path)
                          .AddFieldsRawValuesByNameToSet("Title", titleValue)
                          .AddFieldsRawValuesByNameToSet("Text", textValue)
                          .Language(Language)
                          .Build();

            var result = await this.session.UpdateItemAsync(request);

            Assert.AreEqual(1, result.ResultCount);
            var resultItem = result[0];

            Assert.AreEqual(item.Id, resultItem.Id);
            Assert.AreEqual(titleValue, resultItem["Title"].RawValue);
            Assert.AreEqual(textValue, resultItem["Text"].RawValue);
            Assert.AreEqual(Language, resultItem.Source.Language);
        }
        public override async void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

      #warning first we have to setup connection info and create a session
            var instanceUrl = "http://my.site.com";

            using (var credentials = new SecureStringPasswordProvider("login", "password"))
                using (
                    var session = SitecoreWebApiSessionBuilder.AuthenticatedSessionWithHost(instanceUrl)
                                  .Credentials(credentials)
                                  .WebApiVersion("v1")
                                  .DefaultDatabase("web")
                                  .DefaultLanguage("en")
                                  .BuildSession())
                {
                    // In order to fetch some data we have to build a request
                    var request = ItemWebApiRequestBuilder.ReadItemsRequestWithPath("/sitecore/content/home")
                                  .AddFieldsToRead("text")
                                  .AddScope(ScopeType.Self)
                                  .Build();

                    // And execute it on a session asynchronously
                    var response = await session.ReadItemAsync(request);

                    // Now that it has succeeded we are able to access downloaded items
                    ISitecoreItem item = response[0];

                    // And content stored it its fields
                    string fieldContent = item["text"].RawValue;

                    UIAlertView alert = new UIAlertView("Sitecore SDK Demo", fieldContent, null, "Ok", null);
                    alert.Show();
                }
        }
Example #21
0
        private static object GetSitecoreItemFieldValue(ISitecoreItem item, Type propertyType, SitecoreFieldAttribute fieldAttribute)
        {
            ISitecoreField field = null;

            if (!string.IsNullOrEmpty(fieldAttribute.FieldId))
            {
                field = item.GetField(new Guid(fieldAttribute.FieldId));
            }
            else if (!string.IsNullOrEmpty(fieldAttribute.FieldName))
            {
                field = item.GetField(fieldAttribute.FieldName);
            }
            else
            {
                field = item.GetField(fieldAttribute.FieldIndex);
            }

            if (field == null)
            {
                return(null);
            }

            if (propertyType.IsSimple() || propertyType == typeof(DateTime))
            {
                return(GetFieldValueForSimpleType(propertyType, field.Value));
            }

            if (propertyType == typeof(HtmlString))
            {
                return(field.RenderToHtml());
            }

            return(field.CastToCustomField(propertyType));
        }
        public async Task <IEnumerable <ListItem> > GenerateListItemsFromTeasers(IList <ScItemsResponse> itemsResponse)
        {
            List <ListItem> list = new List <ListItem> ();


            for (int i = 0; i < itemsResponse.Count(); i++)
            {
                if (itemsResponse [i] == null || itemsResponse [i].ResultCount == 0)
                {
                    continue;
                }

                ISitecoreItem item = itemsResponse [i].First();

                ListItem listlItem = new ListItem {
                    Header         = item.GetValueFromField(Constants.Sitecore.Fields.Teasers.TeaserTitle),
                    Text           = item.GetValueFromField(Constants.Sitecore.Fields.Teasers.TeaserSummary),
                    NavigationItem = item.GetItemIdFromLinkField(Constants.Sitecore.Fields.Teasers.TeaserLink),
                    NavigationText = item.GetTextFromLinkField(Constants.Sitecore.Fields.Teasers.TeaserLink),
                    Media          = await _cachedMediaRepository.GetCache(item.GetImageUrlFromMediaField(Constants.Sitecore.Fields.Teasers.TeaserImage))
                };


                list.Add(listlItem);
            }

            return(list);
        }
Example #23
0
 public override void AddItem(ISitecoreItem item)
 {
     if (item is ContentNodeSitecoreItem)
     {
         HoldsProducts = true;
     }
     base.AddItem(item);
 }
Example #24
0
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            this.ValidateFields();

            ISitecoreItem selectedItem = this.sitecoreItems.ElementAt(indexPath.Row);

            this.OnItemCellSelectedDelegate(tableView, selectedItem, indexPath);
        }
        private void AddItemsToDictionary(ISitecoreItem sitecoreItem)
        {
            _sitecoreItems[sitecoreItem.Id] = sitecoreItem;

            foreach (var child in sitecoreItem.Children)
            {
                AddItemsToDictionary(child);
            }
        }
    protected override void OnCreate(Bundle bundle)
    {
      base.OnCreate(bundle);
      this.ActionBar.SetDisplayHomeAsUpEnabled(true);
      this.selectedItem = BaseReadItemActivity.SelectedItem;

      Title = this.selectedItem.DisplayName;
      this.InitList(this.selectedItem.Fields);
    }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            this.ActionBar.SetDisplayHomeAsUpEnabled(true);
            this.selectedItem = BaseReadItemActivity.SelectedItem;

            Title = this.selectedItem.DisplayName;
            this.InitList(this.selectedItem.Fields);
        }
 private NavigationItem CreateNavigationItem(ISitecoreItem item)
 {
     return(new NavigationItem
     {
         Item = item,
         Url = item.Url,
         Children = item.HasChildren ? GetChildNavigationItems(item) : null
     });
 }
Example #29
0
        public static bool GetCheckBoxValueFromField(this ISitecoreItem item, string fieldName)
        {
            if (item == null)
            {
                return(false);
            }

            return(item [fieldName].RawValue == "1");
        }
Example #30
0
        public static string GetValueFromField(this ISitecoreItem item, string fieldName)
        {
            if (item == null)
            {
                return(string.Empty);
            }

            return(item [fieldName].RawValue);
        }
Example #31
0
        public static string GetTemplateName(this ISitecoreItem item)
        {
            if (item == null)
            {
                return(string.Empty);
            }

            return(item.Template.Substring(item.Template.LastIndexOf("/", System.StringComparison.Ordinal) + 1));
        }
        private ISitecoreItem CheckCreatedItem(ScItemsResponse createResponse, TestEnvironment.Item expectedItem)
        {
            this.testData.AssertItemsCount(1, createResponse);
            ISitecoreItem resultItem = createResponse[0];

            this.testData.AssertItemsAreEqual(expectedItem, resultItem);

            return(resultItem);
        }
        /// <summary>
        /// NOTE: Performant heavy. Will require refactor to use solr or lucene search indexes and/or caching of data
        /// under high load
        /// </summary>
        /// <param name="count">Number of parameters</param>
        /// <param name="categories">Categories to search on</param>
        /// <param name="startItem">Relative path to search to limit our hit on the database</param>
        /// <returns></returns>
        public IList<IBlogDetail> GetBlogDetails(int count, IEnumerable<IBlogCategory> categories,
            ISitecoreItem startItem)
        {
            // 1.) If no categories just return null.
            if (categories == null)
            {
                return new List<IBlogDetail>();
            }
            if (startItem == null)
            {
                // should be impossible!
                throw new ArgumentNullException(nameof(startItem));
            }

            // 1.) We need every blog that has that tag associated with it. Tags are stored as GUIDs like this in
            // the categories field == {imaguid} | {imanotherguid} | {moreguidsss} so we do a gigantic
            // like query depending on how many tags we get in.
            var sb = new System.Text.StringBuilder();
            var performantCategories = categories.ToList();
            foreach (var category in performantCategories)
            {
                var first = performantCategories.FirstOrDefault();
                if (category == first)
                {
                    if (category != null)
                    {
                        sb.Append($"@Category='%{category.Id.ToString("B")}%'");
                    }
                }
                else
                {
                    sb.Append($" or @Category='%{category.Id.ToString("B")}%'");
                }
            }

            // 2.) Query relative to the start item
            var query = string.Format("fast:{0}//*[@@id='{1}']//*[@@templateid='{2}' and ({3})]", Context.SiteStartPath,
                startItem.Id, DataTemplateIds.BlogDetail.ToUpper(), sb.ToString());
            Logger.Debug(string.Format("Running the query {0}", query), this);


            // 3.) Query our context with our query
            var items = Context.Query<IBlogDetail>(query).Take(count).OrderBy(x => x.BlogDetailDate).ToList();
            Logger.Debug(string.Format("Found {0} items for our query {1}, returning {2}",
                items.Count(), query, count), this);

            // 4.) Return
            return items;

        }
 public void AssertItemsAreEqual(Item expected, ISitecoreItem actual)
 {
   if (null != expected.DisplayName)
   {
     Assert.AreEqual(expected.DisplayName, actual.DisplayName);
   }
   if (null != expected.Id)
   {
     Assert.AreEqual(expected.Id, actual.Id);
   }
   if (null != expected.Path)
   {
     Assert.AreEqual(expected.Path, actual.Path);
   }
   if (null != expected.Template)
   {
     Assert.AreEqual(expected.Template, actual.Template);
   }
 }
    public void OnItemClick(AdapterView parent, View view, int position, long id)
    {
      SelectedItem = this.items.ToArray()[position];

      this.StartActivity(typeof(ItemFieldsActivity));
    }
    private async void GetAndCheckItem(TestEnvironment.Item expectedItem, ISitecoreItem resultItem)
    {
      var readResponse = await this.GetItemById(resultItem.Id);

      this.testData.AssertItemsCount(1, readResponse);
      this.testData.AssertItemsAreEqual(expectedItem, readResponse[0]);
    }
 public static string SitecoreUrl(this UrlHelper urlHelper, ISitecoreItem sitecoreItem)
 {
     return urlHelper.SitecoreUrl(sitecoreItem, LinkManager.GetDefaultUrlOptions());
 }
 public static string SitecoreUrl(this UrlHelper urlHelper, ISitecoreItem sitecoreItem, UrlOptions urlOptions)
 {
     var db = IoC.Resolver.Resolve<IDatabaseProvider>().GetDatabase();
     return LinkManager.GetItemUrl(db.GetItem(sitecoreItem.Id.ToID()), urlOptions);
 }
    private async Task<ISitecoreItem> CreateItem(string itemName, ISitecoreItem parentItem = null, ISitecoreWebApiSession itemSession = null)
    {
      if (itemSession == null)
      {
        itemSession = session;
      }
      string parentPath = parentItem == null ? this.testData.Items.CreateItemsHere.Path : parentItem.Path;
      var request = ItemWebApiRequestBuilder.CreateItemRequestWithParentPath(parentPath)
        .ItemTemplatePath(testData.Items.Home.Template)
        .ItemName(itemName)
        .Build();
      var createResponse = await itemSession.CreateItemAsync(request);

      Assert.AreEqual(1, createResponse.ResultCount);
      return createResponse[0];
    }