private IEnumerable<SitecoreTemplateSection> GetSections(ItemUri itemUri)
 {
     var children = _service.GetChildHeaders(itemUri);
     return children
         .Where(i => i.Name != "__Standard Values")
         .Select(GetSection);
 }
		public void Edit(ClientPipelineArgs args)
		{
			if (args.IsPostBack)
			{
				if (!args.HasResult)
					return;

				Value = args.Result;
				SetModified();
				SheerResponse.Refresh(this);
			}
			else
			{
				Assert.IsNotNull(DialogUrl, "Dialog URL");

				var urlString = new UrlString(UIUtil.GetUri(DialogUrl));
				var itemUri = new ItemUri(ItemId, Sitecore.Configuration.Factory.GetDatabase("master"));
				var fieldItem = Sitecore.Context.ContentDatabase.GetItem(FieldId);


				urlString["itemUri"] = itemUri.ToString();
				urlString["fieldName"] = fieldItem.Name;

				Sitecore.Context.ClientPage.ClientResponse.ShowModalDialog(urlString.ToString(), "650px", "700px", string.Empty, true);

				args.WaitForPostBack();
			}
		}
Ejemplo n.º 3
0
 public SitecoreItem(ItemUri itemUri)
 {
     Fields = new NameValueCollection();
      RenderedFields = new List<string>();
      Uri = itemUri;
      Fields.Add(BuiltinFields.Language, Uri.Language.Name);
      Fields.Add(SearchFieldIDs.Version, Uri.Version.Number.ToString());
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SkinnyItem"/> class.
 /// </summary>
 /// <param name="itemUri">
 /// The item uri.
 /// </param>
 public SkinnyItem(ItemUri itemUri)
 {
     this.Fields = new NameValueCollection();
     this.RenderedFields = new List<string>();
     this.Uri = itemUri;
     this.Fields.Add(BuiltinFields.Language, this.Uri.Language.Name);
     this.Fields.Add(SearchFieldIDs.Version, this.Uri.Version.Number.ToString(CultureInfo.InvariantCulture));
 }
        public bool StillExists(ItemUri uri)
        {
            Database db = Database.GetDatabase(uri.DatabaseName);

            Item foundItem = db.GetItem(uri.ToDataUri());

            return foundItem != null;
        }
Ejemplo n.º 6
0
 public SitecoreItem(ItemUri itemUri)
 {
     this.Fields = new NameValueCollection();
     this.RenderedFields = new List<string>();
     this.Uri = itemUri;
     this.Name = this.Fields[BuiltinFields.Name];
     this.Fields.Add(BuiltinFields.Language, this.Uri.Language.Name);
     this.Fields.Add(SearchFieldIDs.Version, this.Uri.Version.Number.ToString());
 }
 private void DownloadMediaById(string file)
 {
     Assert.ArgumentNotNull(file, "file");
     UrlString str = new UrlString(HttpUtility.UrlDecode(file));
     ItemUri uri = new ItemUri(str["id"], Language.Parse(str["la"]), Sitecore.Data.Version.Parse(str["vs"]), StringUtil.GetString(new string[] { str["db"], Sitecore.Context.ContentDatabase.Name }));
     Item mediaItem = Database.GetItem(uri);
     if (mediaItem != null)
     {
         WriteMediaItem(mediaItem);
     }
 }
 private IEnumerable<SitecoreTemplateField> GetFields(ItemUri itemUri)
 {
     var children = _service.GetChildHeaders(itemUri).Select(i => _service.GetItem(i.ItemUri));
     return children.Select(f => new SitecoreTemplateField
     {
         Id = f.ItemUri.ItemId.ToString(),
         Name = f.Name,
         Type = GetFieldValue(f, "Type"),
         SortOrder = GetFieldValue(f, "__Sortorder"),
         Fields = f.Fields
             .Where(ff => !ff.Name.In("Type", "__Sortorder"))
             .Select(_itemBuilder.GetField)
     });
 }
Ejemplo n.º 9
0
        public static Item UriToItem(string uri)
        {
            if (uri != null && !string.IsNullOrEmpty(uri)
                && uri.StartsWith("sitecore:")
                && !new Uri(uri).Equals(BrokenLinkUri))
            {
                var itemUri = new ItemUri(uri.Replace("%7B", "{").Replace("%7D", "}"));

                var database = Sitecore.Configuration.Factory.GetDatabase(itemUri.DatabaseName);

                return database.GetItem(itemUri.ItemID, itemUri.Language, itemUri.Version);
            }
            return null;
        }
        public SitecoreTemplate Build(ItemUri itemUri)
        {
            var item = _service.GetItem(itemUri);

            var template = new SitecoreTemplate
            {
                Id = item.ItemUri.ItemId.ToString(),
                Name = item.Name,
                ParentPath = _service.GetParentPath(item.Path),
                BaseTemplates = GetFieldValue(item, "__Base template"),
                Icon = GetIconPath(item.Icon),
                Sections = GetSections(itemUri),
                StandardValues = GetStandardValues(itemUri)
            };

            return template;
        }
        public SitecoreItem GetItem(ItemUri itemUri)
        {
            var item = _service.GetItem(itemUri);
            var template = _service.GetItem(new ItemUri(item.ItemUri.DatabaseUri, item.TemplateId));

            return new SitecoreItem
            {
                Id = item.ItemUri.ItemId.ToString(),
                Name = item.Name,
                ParentPath = _service.GetParentPath(item.Path),
                Language = Language.Current.ToString(),
                TemplateId = item.TemplateId.ToString(),
                TemplateName = item.TemplateName,
                TemplatePath = template.GetPath(),
                Fields = item.Fields.Select(GetField),
                IsMediaItem = _service.IsMediaItem(item),
                Media64 = _service.GetMediaAsBase64(itemUri)
            };
        }
    /// <summary>The execute.</summary>
    /// <param name="parameter">The parameter.</param>
    public override void Execute(object parameter)
    {
      var context = parameter as ContentTreeContext;
      if (context == null)
      {
        return;
      }

      var item = context.SelectedItems.FirstOrDefault() as ItemTreeViewItem;
      if (item == null)
      {
        return;
      }

      var newName = string.Format(Resources.SetName_Process_Copy_of__0_, item.Item.Name);
      newName = AppHost.Prompt(Resources.SetName_Process_Enter_the_Name_of_the_New_Item_, Resources.SetName_Process_Duplicate, newName);
      if (newName == null)
      {
        return;
      }

      Site.RequestCompleted completed = delegate(string response)
      {
        var newItemUri = new ItemUri(item.ItemUri.DatabaseUri, new ItemId(new Guid(response)));
        var itemVersionUri = new ItemVersionUri(newItemUri, LanguageManager.CurrentLanguage, VisualStudio.Data.Version.Latest);

        Notifications.RaiseItemDuplicated(this, newItemUri, item.ItemUri);

        if (AppHost.CurrentContentTree != null)
        {
          AppHost.CurrentContentTree.Locate(newItemUri);
        }

        AppHost.OpenContentEditor(itemVersionUri);
      };

      item.ItemUri.Site.Execute("Items.DuplicateLatestVersionOnly", completed, item.ItemUri.DatabaseName.ToString(), item.ItemUri.ItemId.ToString(), Language.Current.ToString(), newName);
    }
Ejemplo n.º 13
0
      public static void GetItemsFromSearchResult(IEnumerable<SearchResult> searchResults, List<SkinnyItem> items, bool showAllVersions)
      {
         foreach (var result in searchResults)
         {
            var uriField = result.Document.GetField(BuiltinFields.Url);
            if (uriField != null && !String.IsNullOrEmpty(uriField.StringValue()))
            {
               var itemUri = new ItemUri(uriField.StringValue());

               var itemInfo = new SkinnyItem(itemUri);

               foreach (Field field in result.Document.GetFields())
               {
                  itemInfo.Fields[field.Name()] = field.StringValue();
               }

               items.Add(itemInfo);
            }

            if (showAllVersions)
               GetItemsFromSearchResult(result.Subresults, items, true);
         }
      }
Ejemplo n.º 14
0
        public void Initialize([NotNull] ItemUri templateUri)
        {
            Assert.ArgumentNotNull(templateUri, nameof(templateUri));

            templateDesigner.Initialize(templateUri);
        }
        /// <summary>
        /// On Load
        /// </summary>
        /// <param name="e">
        /// The e.
        /// </param>
        protected override void OnLoad(EventArgs e)
        {
            Assert.ArgumentNotNull(e, "e");
            base.OnLoad(e);
            if (Context.ClientPage.IsEvent)
            {
                return;
            }

            this.InternalLinkDataContext.GetFromQueryString();
            this.CustomTarget.Disabled = true;
            this.CustomLabel.Disabled  = true;
            var xml         = StringUtil.GetString(new[] { WebUtil.GetQueryString("va"), "<link/>" });
            var queryString = WebUtil.GetQueryString("ro");
            var document    = XmlUtil.LoadXml(xml);

            if (document == null)
            {
                this.CheckQueryStringLength(queryString);
            }

            var node = document.SelectSingleNode("/link");

            if (node == null)
            {
                this.CheckQueryStringLength(queryString);
            }

            var attribute = XmlUtil.GetAttribute("text", node);
            var str4      = XmlUtil.GetAttribute("anchor", node);
            var str5      = XmlUtil.GetAttribute("target", node);
            var str6      = string.Empty;
            var str7      = XmlUtil.GetAttribute("class", node);
            var str8      = XmlUtil.GetAttribute("querystring", node);
            var str9      = XmlUtil.GetAttribute("title", node);
            var url       = XmlUtil.GetAttribute("url", node);
            var str12     = str5;

            if (str12 != null)
            {
                if (str12.IsNotEmpty() && str12 != "_self")
                {
                    if (str12 == "_blank")
                    {
                        str5 = "New";
                    }
                    else
                    {
                        str6 = str5;
                        str5 = "Custom";
                        this.CustomTarget.Background = "window";
                        this.CustomTarget.Disabled   = false;
                        this.CustomLabel.Disabled    = false;
                    }
                }
                else
                {
                    str5 = "Self";
                }
            }

            this.Text.Value         = attribute;
            this.Anchor.Value       = str4;
            this.Target.Value       = str5;
            this.CustomTarget.Value = str6;
            this.Class.Value        = str7;
            this.Querystring.Value  = str8;
            this.Title.Value        = str9;
            var str11 = XmlUtil.GetAttribute("id", node);

            if (string.IsNullOrEmpty(str11) || !IdHelper.IsGuid(str11))
            {
                this.SetFolderFromUrl(node, url);
            }
            else
            {
                var itemId = new ID(str11);
                if (Client.ContentDatabase.GetItem(itemId) == null)
                {
                    this.SetFolderFromUrl(node, url);
                }
                else
                {
                    var uri = new ItemUri(itemId, Client.ContentDatabase);
                    this.InternalLinkDataContext.SetFolder(uri);
                }
            }
        }
Ejemplo n.º 16
0
 protected abstract XmlElement ExecuteRename([NotNull] ItemUri itemId, [NotNull] string newName);
Ejemplo n.º 17
0
        protected virtual void UpdateFields([NotNull] EnvDTE.ProjectItem projectItem, [NotNull] ItemUri itemUri, [NotNull] string fileName)
        {
            Debug.ArgumentNotNull(projectItem, nameof(projectItem));
            Debug.ArgumentNotNull(itemUri, nameof(itemUri));
            Debug.ArgumentNotNull(fileName, nameof(fileName));

            if (!string.IsNullOrEmpty(PathFieldName))
            {
                ItemModifier.Edit(itemUri, PathFieldName, "/" + fileName.Replace('\\', '/'));
            }
        }
Ejemplo n.º 18
0
 public static void OpenItem(ItemUri uri)
 {
     Util.OpenItem(Sitecore.Data.Database.GetItem(uri));
 }
Ejemplo n.º 19
0
 public void AdvancedPublish72([NotNull] ItemUri itemUri, [NotNull] string mode, [NotNull] string source, [NotNull] string languages, [NotNull] string targets, [NotNull] string relatedItems, [NotNull] ExecuteCompleted completed)
 {
     itemUri.Site.DataService.ExecuteAsync("Publishing.AdvancedPublish72", completed, itemUri.DatabaseUri.DatabaseName.ToString(), itemUri.ItemId.ToString(), mode, source, languages, targets, relatedItems);
 }
Ejemplo n.º 20
0
 protected override void OnLoad(EventArgs e)
 {
     base.OnLoad(e);
     if (MaxRequestLengthExceeded)
     {
         HttpContext.Current.Response.Write(
             "<html><head><script type=\"text/JavaScript\" language=\"javascript\">window.top.scForm.getTopModalDialog().frames[0].scForm.postRequest(\"\", \"\", \"\", 'ShowFileTooBig()')</script></head><body>Done</body></html>");
     }
     else
     {
         if (IsEvent)
         {
             return;
         }
         if (Request.Files.Count <= 0)
         {
             return;
         }
         try
         {
             var pathOrId = Sitecore.Context.ClientPage.ClientRequest.Form["ItemUri"];
             var langStr  = Sitecore.Context.ClientPage.ClientRequest.Form["LanguageName"];
             var language = langStr.Length > 0
                 ? LanguageManager.GetLanguage(langStr) ?? Sitecore.Context.ContentLanguage
                 : Sitecore.Context.ContentLanguage;
             var itemUri    = ItemUri.Parse(pathOrId);
             var uploadArgs = new UploadArgs();
             if (itemUri != null)
             {
                 pathOrId = itemUri.GetPathOrId();
                 uploadArgs.Destination = Settings.Media.UploadAsFiles
                     ? UploadDestination.File
                     : UploadDestination.Database;
             }
             else
             {
                 uploadArgs.Destination = UploadDestination.File;
                 uploadArgs.FileOnly    = true;
             }
             uploadArgs.Files     = Request.Files;
             uploadArgs.Folder    = pathOrId;
             uploadArgs.Overwrite = Sitecore.Context.ClientPage.ClientRequest.Form["Overwrite"].Length > 0;
             //uploadArgs.Overwrite = Settings.Upload.SimpleUploadOverwriting;
             uploadArgs.Unpack    = Sitecore.Context.ClientPage.ClientRequest.Form["Unpack"].Length > 0;
             uploadArgs.Versioned = Sitecore.Context.ClientPage.ClientRequest.Form["Versioned"].Length > 0;
             //uploadArgs.Versioned = Settings.Media.UploadAsVersionableByDefault;
             uploadArgs.Language         = language;
             uploadArgs.CloseDialogOnEnd = false;
             PipelineFactory.GetPipeline("uiUpload").Start(uploadArgs);
             string fileName;
             if (uploadArgs.UploadedItems.Count > 0)
             {
                 fileName = uploadArgs.UploadedItems[0].ID.ToString();
                 PowerShellLog.Audit("Upload: {0}", StringUtil.Join(uploadArgs.UploadedItems, ", ", "Name"));
             }
             else
             {
                 var fileHandle = uploadArgs.Properties["filename"];
                 if (fileHandle != null)
                 {
                     fileName = WebUtil.UrlEncode(FileHandle.GetFilename(fileHandle.ToString()));
                 }
                 else if (uploadArgs.Unpack)
                 {
                     fileName = WebUtil.UrlEncode(uploadArgs.Folder);
                 }
                 else
                 {
                     fileName = string.Empty;
                 }
             }
             if (!string.IsNullOrEmpty(uploadArgs.ErrorText))
             {
                 return;
             }
             HttpContext.Current.Response.Write(
                 "<html><head><script type=\"text/JavaScript\" language=\"javascript\">window.top.scForm.getTopModalDialog().frames[0].scForm.postRequest(\"\", \"\", \"\", 'EndUploading(\"" +
                 fileName + "\")')</script></head><body>Done</body></html>");
         }
         catch (OutOfMemoryException)
         {
             HttpContext.Current.Response.Write(
                 "<html><head><script type=\"text/JavaScript\" language=\"javascript\">window.top.scForm.getTopModalDialog().frames[0].scForm.postRequest(\"\", \"\", \"\", 'ShowFileTooBig(" +
                 StringUtil.EscapeJavascriptString(Request.Files[0].FileName) +
                 ")')</script></head><body>Done</body></html>");
         }
         catch (Exception ex)
         {
             if (ex.InnerException is OutOfMemoryException)
             {
                 HttpContext.Current.Response.Write(
                     "<html><head><script type=\"text/JavaScript\" language=\"javascript\">window.top.scForm.getTopModalDialog().frames[0].scForm.postRequest(\"\", \"\", \"\", 'ShowFileTooBig(" +
                     StringUtil.EscapeJavascriptString(Request.Files[0].FileName) +
                     ")')</script></head><body>Done</body></html>");
             }
             else
             {
                 HttpContext.Current.Response.Write(
                     "<html><head><script type=\"text/JavaScript\" language=\"javascript\">window.top.scForm.getTopModalDialog().frames[0].scForm.postRequest(\"\", \"\", \"\", 'ShowError')</script></head><body>Done</body></html>");
             }
         }
     }
 }
 protected void LoadItem(ItemUri uri, string root)
 {
     Assert.ArgumentNotNull(uri, "uri");
     Assert.ArgumentNotNull(root, "root");
     if (Database.GetItem(uri) == null)
     {
         SheerResponse.Alert("The selected item could not be found.\n\nIt may have been deleted by another user.\n\nSelect another item.", new string[0]);
     }
     else
     {
         NameValueCollection values2 = new NameValueCollection();
         values2.Add("uri", uri.ToString());
         values2.Add("root", root);
         values2.Add("disablehistory", this.DisableHistory ? "1" : "0");
         NameValueCollection parameters = values2;
         Context.ClientPage.Start(this, "LoadItemPipeline", parameters);
     }
 }
Ejemplo n.º 22
0
        public void FiltersOnPathAndTemplate()
        {
            // Mock the database
            var db = Mock.Of <Database>();

            // Mock the parent item
            var parentId   = ID.NewID;
            var parentDef  = new ItemDefinition(parentId, "parent", Templates.Product.Id, ID.Null);
            var parentData = new ItemData(parentDef, Language.Parse("en"), Version.Parse(1), new FieldList());
            var parent     = new Mock <Item>(parentId, parentData, db);

            // Mock the Sitecore services
            var factoryMock = new Mock <BaseFactory>();

            factoryMock.Setup(x => x.GetDatabase(It.IsAny <string>())).Returns(db);
            var factory     = factoryMock.Object;
            var itemManager = Mock.Of <BaseItemManager>();

            // Mock search context, so we are testing LINQ to Objects instead of LINQ to Sitecore
            var itemUri           = new ItemUri("sitecore://master/{11111111-1111-1111-1111-111111111111}?lang=en&ver=1");
            var mockSearchContext = new Mock <IProviderSearchContext>();

            mockSearchContext.Setup(x => x.GetQueryable <ProductSearchQuery>())
            .Returns(new[]
            {
                // Matches Path and Template
                new ProductSearchQuery
                {
                    UniqueId  = itemUri,
                    Templates = new[] { Templates.Product.Id },
                    Paths     = new[] { parentId }
                },
                // Matches Path and Template
                new ProductSearchQuery
                {
                    UniqueId  = itemUri,
                    Templates = new[] { ID.NewID, Templates.Product.Id, ID.NewID },
                    Paths     = new[] { ID.NewID, parentId, ID.NewID }
                },
                // Matches Template Only
                new ProductSearchQuery
                {
                    UniqueId  = itemUri,
                    Templates = new[] { Templates.Product.Id },
                    Paths     = new[] { ID.NewID }
                },
                // Matches Path Only
                new ProductSearchQuery
                {
                    UniqueId  = itemUri,
                    Templates = new[] { ID.NewID },
                    Paths     = new[] { parentId }
                }
            }.AsQueryable());

            // Use Moq.Protected to ensure our test object uses the mock search context
            var mockRepo = new Mock <ProductRepository>(factory, itemManager);

            mockRepo.Protected()
            .Setup <IProviderSearchContext>("GetSearchContext", ItExpr.IsAny <Item>())
            .Returns(mockSearchContext.Object);

            // Act
            var result = mockRepo.Object.GetProducts(parent.Object).ToList();

            // If the tested class is filtering appropriately, we should get predictible results
            Assert.Equal(2, result.Count);
        }
        public void CreateTab([NotNull] ItemUri itemUri, bool deep)
        {
            Assert.ArgumentNotNull(itemUri, nameof(itemUri));

            foreach (var i in Tabs.Items)
            {
                var t = i as TabItem;
                if (t == null)
                {
                    continue;
                }

                var l = t.Content as SitecoreCopTab;
                if (l == null)
                {
                    continue;
                }

                if (l.ItemUri != itemUri || l.Deep != deep)
                {
                    continue;
                }

                t.IsSelected = true;
            }

            ExecuteCompleted completed = delegate(string response, ExecuteResult result)
            {
                if (!DataService.HandleExecute(response, result))
                {
                    return;
                }

                var element = response.ToXElement();
                if (element == null)
                {
                    return;
                }

                var item = ItemHeader.Parse(itemUri.DatabaseUri, element);

                var tabItem = new TabItem();

                var tab = new SitecoreCopTab
                {
                    ItemUri = itemUri,
                    TabItem = tabItem
                };

                var tabHeader = new TabItemHeader
                {
                    Header = item.Name + (deep ? " (Deep)" : string.Empty),
                    Tag    = tab
                };

                tabHeader.Click += delegate { CloseTab(tabItem); };
                tabItem.Header   = tabHeader;

                Tabs.Items.Add(tabItem);

                tabItem.Content    = tab;
                tabItem.IsSelected = true;

                EnableTabs();

                tab.Initialize(itemUri, deep);
            };

            itemUri.Site.DataService.ExecuteAsync("Items.GetItemHeader", completed, itemUri.ItemId.ToString(), itemUri.DatabaseName.Name);
        }
Ejemplo n.º 24
0
        public void Initialize([NotNull] ItemUri templateUri)
        {
            Assert.ArgumentNotNull(templateUri, nameof(templateUri));

            _templateFieldSorter.Initialize(templateUri);
        }
Ejemplo n.º 25
0
        internal IEnumerable <Item> GetItemInternal(string path, bool errorIfNotFound)
        {
            LogInfo("Executing GetItem(string path='{0}')", path);


            GetVersionAndLanguageParams(out int version, out string[] language);

            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;

            // by Uri
            if (dic != null && dic.ContainsKey(UriParam) && dic[UriParam].IsSet)
            {
                var uri     = dic[UriParam].Value.ToString();
                var itemUri = ItemUri.Parse(uri);
                var uriItem = Factory.GetDatabase(itemUri.DatabaseName)
                              .GetItem(itemUri.ItemID, itemUri.Language, itemUri.Version);
                yield return(uriItem);

                yield break;
            }

            // by Query
            if (dic != null && dic.ContainsKey(QueryParam) && dic[QueryParam].IsSet)
            {
                var query = dic[QueryParam].Value.ToString();
                var items = Factory.GetDatabase(PSDriveInfo.Name).SelectItems(query);
                foreach (var resultItem in items.SelectMany(currentItem => GetMatchingItem(language, version, currentItem)))
                {
                    yield return(resultItem);
                }
                yield break;
            }

            // by Id
            if (dic != null && dic.ContainsKey(IdParam) && dic[IdParam].IsSet)
            {
                var      idParam = dic[IdParam].Value.ToString();
                Database database;
                if (dic.ContainsKey(DatabaseParam) && dic[DatabaseParam].IsSet)
                {
                    database = Factory.GetDatabase((string)dic[DatabaseParam].Value);
                }
                else
                {
                    database = Factory.GetDatabase(PSDriveInfo.Name);
                }
                foreach (var id in idParam.Split('|'))
                {
                    var itemById = database.GetItem(new ID(id));
                    foreach (var resultItem in GetMatchingItem(language, version, itemById))
                    {
                        yield return(resultItem);
                    }
                }
                yield break;
            }

            var item = GetItemForPath(path);

            if (item != null)
            {
                foreach (var resultItem in GetMatchingItem(language, version, item))
                {
                    yield return(resultItem);
                }
            }
            else if (errorIfNotFound)
            {
                WriteInvalidPathError(path);
            }
        }
 /// <summary>
 /// Deletes the specific version information from the index.
 /// </summary>
 /// <param name="id">The item id.</param>
 /// <param name="language">The language.</param>
 /// <param name="version">The version.</param>
 /// <param name="context">The context.</param>
 protected override void DeleteVersion(ID id, string language, string version, IndexDeleteContext context)
 {
   base.DeleteVersion(id, language, version, context);
   ItemUri versionUri = new ItemUri(id, Language.Parse(language), Version.Parse(version), Factory.GetDatabase(this.Database));
   Item versionItem = Sitecore.Data.Database.GetItem(versionUri);
   if (versionItem != null && this.IsCatalogItem(versionItem))
   {
     context.DeleteDocuments(context.Search(new PreparedQuery(this.GetVirtualProductsQuery(versionItem)), int.MaxValue).Ids);
   }
 }
 public ItemReference(ItemUri uri, bool recursive)
 {
     this.ItemUri = uri;
     this.Recursive = recursive;
 }
Ejemplo n.º 28
0
 public ItemReference(ItemUri uri, bool recursive)
 {
     this.ItemUri   = uri;
     this.Recursive = recursive;
 }
 protected void LoadItem(Message message)
 {
     Assert.ArgumentNotNull(message, "message");
     string path = StringUtil.GetString(new string[] { message["id"] });
     string name = StringUtil.GetString(new string[] { message["language"] });
     string str3 = StringUtil.GetString(new string[] { message["version"] });
     string str4 = StringUtil.GetString(new string[] { message["root"] });
     this.DisableHistory = StringUtil.GetString(new string[] { message["disablehistory"] }) == "1";
     if (name.Length == 0)
     {
         name = this.ContentEditorDataContext.Language.ToString();
     }
     ItemUri uri = new ItemUri(path, Sitecore.Globalization.Language.Parse(name), Sitecore.Data.Version.Parse(str3), Client.ContentDatabase.Name);
     Item item = Database.GetItem(uri);
     if (item == null)
     {
         SheerResponse.Alert("The selected item could not be found.\n\nIt may have been deleted by another user.\n\nSelect another item.", new string[0]);
     }
     else
     {
         //if (string.IsNullOrEmpty(str4))
         //{
         //    Item root = this.ContentEditorDataContext.GetRoot();
         //    if (((item.ID != root.ID) && !root.Axes.IsAncestorOf(item)) || IsHidden(item, root))
         //    {
         //        SheerResponse.Alert("The item that you are attempting to open is stored in a location that is not visible in the content tree.\n\nItem: {0}", new string[] { item.Paths.Path });
         //        return;
         //    }
         //}
         if (message["force"] == "1")
         {
             if (!string.IsNullOrEmpty(str4))
             {
                 this.ContentEditorDataContext.SetRootAndFolder(str4, uri);
             }
             else
             {
                 this.ContentEditorDataContext.SetFolder(uri);
             }
         }
         else
         {
             this.LoadItem(uri, str4);
         }
     }
 }
Ejemplo n.º 30
0
        protected override void UpdateFields(NewItemWizardPipeline pipeline, ProjectItem projectItem, ItemUri itemUri)
        {
            Debug.ArgumentNotNull(pipeline, nameof(pipeline));
            Debug.ArgumentNotNull(projectItem, nameof(projectItem));
            Debug.ArgumentNotNull(itemUri, nameof(itemUri));

            var modelName = GetTypeName(pipeline, projectItem);

            var fieldValues = new List <Tuple <FieldId, string> >();

            fieldValues.Add(new Tuple <FieldId, string>(new FieldId(new Guid("{1A0AE537-291C-4CC8-B53F-7CA307A0FEF5}")), modelName));
            fieldValues.Add(new Tuple <FieldId, string>(new FieldId(new Guid("{298F7E71-8AEB-488B-BC93-CE6F2B09E130}")), "Index"));

            ItemModifier.Edit(itemUri, fieldValues);
        }
        protected override void OnLoad(EventArgs e)
        {
            Item folder;
            Assert.ArgumentNotNull(e, "e");

            Assert.CanRunApplication("Content Editor");
            if (!Context.ClientPage.IsEvent)
            {
                string str2;
                AttributeCollection attributes;
                this.SetDocumentType();
                this.SetWebEditStylesheet();
                (attributes = this.Body.Attributes)["class"] = attributes["class"] + " " + UIUtil.GetBrowserClassString();
                this.ContentEditorDataContext.GetFromQueryString();
                this.ContentEditorDataContext.BeginUpdate();
                string queryString = WebUtil.GetQueryString("pa" + WebUtil.GetQueryString("pa", "0"));
                if (!string.IsNullOrEmpty(queryString))
                {
                    folder = Database.GetItem(ItemUri.Parse(HttpUtility.UrlDecode(queryString)));
                    if (folder != null)
                    {
                        this.ContentEditorDataContext.SetFolder(folder.Uri);
                    }
                }
                Database contentDatabase = Context.ContentDatabase;
                Item item2 = this.ContentEditorDataContext.GetRoot();
                if (item2 != null)
                {
                    contentDatabase = item2.Database;
                }
                this.ResolveLanguage(contentDatabase);
                this.ContentEditorDataContext.EndUpdate();
                folder = this.ContentEditorDataContext.GetFolder();
                this.CurrentRoot = this.ContentEditorDataContext.GetRoot().ID.ToString();
                this.ValidatorsKey = "VK_" + ID.NewID.ToShortID();
                int num = Settings.Validators.AutomaticUpdate ? Settings.Validators.UpdateDelay : 0;
                var control = Context.ClientPage.FindControl("ContentEditorForm");
                Assert.IsNotNull(control, "Form \"ContentEditorForm\" not found.");
                control.Controls.Add(new LiteralControl("<input type=\"hidden\" id=\"__CurrentItem\" name=\"__CurrentItem\" value=\"" + folder.Uri + "\"/>"));
                control.Controls.Add(new LiteralControl("<input type=\"hidden\" id=\"scValidatorsKey\" name=\"scValidatorsKey\" value=\"" + this.ValidatorsKey + "\"/>"));
                control.Controls.Add(new LiteralControl("<input type=\"hidden\" id=\"scValidatorsUpdateDelay\" name=\"scValidatorsUpdateDelay\" value=\"" + num + "\"/>"));
                if (WebUtil.GetQueryString("mo") == "preview")
                {
                    str2 = "Shell";
                }
                else
                {
                    str2 = "CE_" + ID.NewID.ToShortID();
                }
                control.Controls.Add(new LiteralControl(string.Format("<input id=\"__FRAMENAME\" name=\"__FRAMENAME\" type=\"hidden\" value=\"{0}\"/>", str2)));
                this.FrameName = str2;
                this.RenderPager();
                this.RenderButtons();
                if (!UserOptions.ContentEditor.ShowSearchPanel)
                {
                    this.SearchPanel.Style["display"] = "none";
                }
                this.BrowserTitle.Controls.Add(new LiteralControl("<title>" + Client.Site.BrowserTitle + " - Sitecore Content Editor</title>"));
                PlaceHolder holder = Context.ClientPage.FindControl("scLanguage") as PlaceHolder;
                Assert.IsNotNull(holder, "language");
                holder.Controls.Add(new LiteralControl("<input type=\"hidden\" id=\"scLanguage\" name=\"scLanguage\" value=\"" + folder.Language + "\" />"));
                var child = this.Body.FindControl("RadSpell");
                holder.Controls.Add(child);
            }
            Item root = this.ContentEditorDataContext.GetRoot();
            folder = this.ContentEditorDataContext.GetFolder();
            //if (!Sitecore.Context.Item.IsABucket())
            //{
            this.Sidebar.Initialize(this, folder, root);
            //}
            SiteContext site = Client.Site;
            site.Notifications.ItemDeleted += new ItemDeletedDelegate(this.ItemDeletedNotification);
            site.Notifications.ItemMoved += new ItemMovedDelegate(this.ItemMovedNotification);
            site.Notifications.ItemRenamed += new ItemRenamedDelegate(this.ItemRenamedNotification);
            site.Notifications.ItemCopied += new ItemCopiedDelegate(this.ItemCopiedNotification);
            site.Notifications.ItemCreated += new ItemCreatedDelegate(this.ItemCreatedNotification);
            site.Notifications.ItemSaved += new ItemSavedDelegate(this.ItemSavedNotification);
            this._lastFolder = folder.Uri;
            string formValue = WebUtil.GetFormValue("scSections");
            if (!string.IsNullOrEmpty(formValue))
            {
                HandleSections(new UrlString(formValue));
            }
            GalleryManager.SetGallerySizes();
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (NicamHelper.SafeRequest("search") != string.Empty)
                {
                    var searchWords = NicamHelper.UrlDecode(NicamHelper.SafeRequest("search"));

                    IEnumerable <Sitecore.Ecommerce.Search.SearchResult> resultHits = new LuceneSearcher(this.BuildQuery(searchWords), "web").Search();

                    List <Sitecore.Ecommerce.Search.SearchResult> results = new List <Sitecore.Ecommerce.Search.SearchResult>();
                    foreach (Sitecore.Ecommerce.Search.SearchResult resultHit in resultHits)
                    {
                        if (resultHit == null || resultHit.ResultItem == null || resultHit.ResultItem.ItemUri == null)
                        {
                            continue;
                        }

                        if (!results.Any(r => r.ResultItem.ItemLink == resultHit.ResultItem.ItemLink) && ItemUri.Parse(resultHit.ResultItem.ItemUri).Language == Sitecore.Context.Language && ItemUri.Parse(resultHit.ParentItem.ItemUri).Language == Sitecore.Context.Language)
                        {
                            results.Add(resultHit);
                        }
                    }

                    foreach (Sitecore.Ecommerce.Search.SearchResult resultHit in results)
                    {
                        TreeNode pnode = this.linksTree.Nodes.Cast <TreeNode>().FirstOrDefault(t => t.NavigateUrl == resultHit.ParentItem.ItemLink);

                        TreeNode node = new TreeNode(resultHit.ResultItem.ItemTitle)
                        {
                            NavigateUrl = resultHit.ResultItem.ItemLink,
                            Value       = resultHit.ResultItem.ItemUri
                        };

                        if (pnode == null)
                        {
                            pnode = new TreeNode(resultHit.ParentItem.ItemTitle)
                            {
                                NavigateUrl = resultHit.ParentItem.ItemLink,
                                Value       = resultHit.ParentItem.ItemUri
                            };
                            pnode.ChildNodes.Add(node);
                            this.linksTree.Nodes.Add(pnode);
                        }
                        else
                        {
                            pnode.ChildNodes.Add(node);
                        }
                    }

                    this.bodySearch.Value = searchWords;
                    AnalyticsUtil.Search(searchWords, resultHits.Count());
                }
            }
            else
            {
                if (SearchAgainClicked() && this.bodySearch.Value != string.Empty)
                {
                    var url = NicamHelper.RedirectUrl(Consts.SearchResultPage, "search", this.bodySearch.Value);
                    //// Search Result Page via QS only. It is necessary for Print version of page
                    Response.Redirect(url);
                }
            }
        }
Ejemplo n.º 33
0
 public virtual void LinkItemAndFile([NotNull] ProjectBase project, [NotNull] ItemUri itemUri, [NotNull] string relativeFileName, bool saveProject = true)
 {
     Assert.ArgumentNotNull(project, nameof(project));
     Assert.ArgumentNotNull(itemUri, nameof(itemUri));
     Assert.ArgumentNotNull(relativeFileName, nameof(relativeFileName));
 }
Ejemplo n.º 34
0
        public void SetSource([NotNull] ItemUri itemUri)
        {
            Assert.ArgumentNotNull(itemUri, nameof(itemUri));

            validationIssues.SetSource(itemUri);
        }
Ejemplo n.º 35
0
 protected abstract void ExecutePasteXml([NotNull] ItemUri itemUri, [NotNull] string xml, bool changeIds);
 public bool StillExists(ItemUri uri)
 {
     return _crawledItems.ContainsKey(uri);
 }
Ejemplo n.º 37
0
        protected virtual List <ItemUri> CreateItems([NotNull] ProjectBase project, [NotNull] List <EnvDTE.ProjectItem> items, [NotNull] ItemUri parentItemUri, [NotNull] ItemUri templateUri)
        {
            Debug.ArgumentNotNull(project, nameof(project));
            Debug.ArgumentNotNull(items, nameof(items));
            Debug.ArgumentNotNull(parentItemUri, nameof(parentItemUri));
            Debug.ArgumentNotNull(templateUri, nameof(templateUri));

            var result = new List <ItemUri>();

            foreach (var projectItem in items)
            {
                var fileName = project.GetRelativeFileName(projectItem.GetFileName());

                var itemUri = AppHost.Server.AddFromTemplate(parentItemUri, templateUri, Path.GetFileNameWithoutExtension(fileName));
                if (itemUri == ItemUri.Empty)
                {
                    continue;
                }

                UpdateFields(projectItem, itemUri, fileName);

                result.Add(itemUri);

                AppHost.Projects.LinkItemAndFile(project, itemUri, fileName, false);
            }

            project.Save();

            return(result);
        }
Ejemplo n.º 38
0
 protected abstract XmlElement ExecuteAddFromTemplate([NotNull] ItemUri parent, [NotNull] ItemUri templateUri, [NotNull] string newName);
 public SitecoreItem(string itemUri) : this(ItemUri.Parse(itemUri))
 {
 }
Ejemplo n.º 40
0
 protected abstract XmlElement ExecuteCopyTo([NotNull] ItemUri itemUri, [NotNull] ItemId newParentId, [NotNull] string newName);
        protected void Run(ClientPipelineArgs args)
        {
            if (Context.ClientPage.Modified)
            {
                var title = !string.IsNullOrWhiteSpace(args.Parameters["title"]) ? args.Parameters["title"] : "Redeploy";
                SheerResponse.Alert(string.Format("You must save your edits to this item before attempting to {0}.", title));
                args.AbortPipeline();
                return;
            }

            var itemUri    = new ItemUri(args.Parameters["itemUri"]);
            var filterItem = Database.GetItem(itemUri);

            if (filterItem == null)
            {
                Context.ClientPage.ClientResponse.Alert(string.Format(@"Filter {0} not found.", itemUri));
                return;
            }

            var ruleField = filterItem.Fields["Rule"];

            if (ruleField == null)
            {
                Context.ClientPage.ClientResponse.Alert(string.Format(@"Rule field not found for {0}.", itemUri));
                return;
            }
            var filter = JsonConvert.SerializeObject(RuleFactory.GetRules <RuleContext>(ruleField), new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All
            });

            var updatedSegments = new List <string>();

            // Find segments using filter.  Crawl, do not use links database as it may be out of sync.
            var dimensions = filterItem.Database.GetItem("{FBF255C0-72A2-4E76-A83D-633B852D82E7}");

            foreach (var folder in dimensions.Children.OfType <Item>())
            {
                foreach (var dimension in folder.Children.OfType <Item>())
                {
                    foreach (var segment in dimension.Children.OfType <Item>())
                    {
                        var filterField = segment.Fields["Filter"];
                        if (filterField == null)
                        {
                            continue;
                        }
                        if (string.IsNullOrEmpty(filterField.Value))
                        {
                            continue;
                        }
                        ID filterId;
                        if (!ID.TryParse(filterField.Value, out filterId))
                        {
                            continue;
                        }
                        if (filterId != filterItem.ID)
                        {
                            continue;
                        }

                        var workflow      = filterItem.Database.WorkflowProvider.GetWorkflow(segment);
                        var workflowState = workflow.GetState(segment);
                        if (!workflowState.FinalState)
                        {
                            continue;
                        }

                        var command = new SqlCommand {
                            CommandText = "UPDATE dbo.Segments SET [Filter] = @Filter WHERE [SegmentId] = @SegmentId"
                        };
                        command.Parameters.AddWithValue("@Filter", filter);
                        command.Parameters.AddWithValue("@SegmentId", segment.ID.Guid);
                        Factory.GetRetryer().ExecuteNoResult(() =>
                        {
                            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["reporting"].ConnectionString))
                            {
                                connection.Open();
                                command.Connection = connection;
                                command.ExecuteNonQuery();
                            }
                        });

                        // Run the deployment pipeline to deploy the segment.
                        // Sitecore.ExperienceAnalytics.Client.Deployment.DeploySegmentDefinitionProcessor DateTime.UtcNow
                        //var deployDefinitionArgs = new DeployDefinitionArgs(item);
                        //CorePipeline.Run("deployDefinition", deployDefinitionArgs);

                        updatedSegments.Add(segment.Name);
                    }
                }
            }

            if (updatedSegments.Any())
            {
                Context.ClientPage.ClientResponse.Alert(string.Format(@"Redeployed: {0}.", string.Join(",", updatedSegments)));
            }
            else
            {
                Context.ClientPage.ClientResponse.Alert(@"Filter NOT Redeployed. Make sure filter is attached to a segment and the segment is deployed.");
            }
        }
Ejemplo n.º 42
0
 protected abstract void ExecuteCopyToAsync([NotNull] ItemUri itemUri, [NotNull] ItemId newParentId, [NotNull] string newName, [NotNull] EventHandler <CopyToCompletedEventArgs> callback);
    /// <summary>The execute psi transaction.</summary>
    /// <param name="solution">The solution.</param>
    /// <param name="progress">The progress.</param>
    /// <returns>The <see cref="Action"/>.</returns>
    protected override Action<ITextControl> ExecutePsiTransaction([NotNull] ISolution solution, [NotNull] IProgressIndicator progress)
    {
      var site = this.Site;

      var itemUri = new ItemUri(new DatabaseUri(site, new DatabaseName("master")), new ItemId(this.Guid));

      if (ActiveContext.ActiveContentTree != null)
      {
        ActiveContext.ActiveContentTree.Locate(itemUri);
      }

      return null;
    }
Ejemplo n.º 44
0
 protected abstract XmlElement ExecuteDelete([NotNull] ItemUri itemUri);
    /// <summary>The execute psi transaction.</summary>
    /// <param name="solution">The solution.</param>
    /// <param name="progress">The progress.</param>
    /// <returns>The <see cref="Action"/>.</returns>
    protected override Action<ITextControl> ExecutePsiTransaction([NotNull] ISolution solution, [NotNull] IProgressIndicator progress)
    {
      var site = this.Site;

      var itemUri = new ItemUri(new DatabaseUri(site, new DatabaseName("master")), new ItemId(this.Guid));
      var itemVersionUri = new ItemVersionUri(itemUri, LanguageManager.CurrentLanguage, VisualStudio.Data.Version.Latest);

      AppHost.OpenContentEditor(itemVersionUri);

      return null;
    }
Ejemplo n.º 46
0
    public override CommandResult Run()
    {
      if (string.IsNullOrEmpty(Query))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("query"));

      if (string.IsNullOrEmpty(Command) && !StatsOnly)
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("command") + " or -so flag");

      if (StatsOnly && !string.IsNullOrEmpty(Command))
        return new CommandResult(CommandStatus.Failure, "Cannot specify a command when using the -so flag");

      Index index = null;

      if (string.IsNullOrEmpty(IndexName))
        index = SearchManager.SystemIndex;
      else
        index = SearchManager.GetIndex(IndexName);

      if (index == null)
        return new CommandResult(CommandStatus.Failure, "Index not found");

      var output = new StringBuilder();
      var foundCount = 0;
      var searchCount = 0;

      using (var searchContext = index.CreateSearchContext())
      {
#if NET35
        var hits = searchContext.Search(Query);
#else
        var hits = searchContext.Search(Query, MAX_SEARCH_HITS);
#endif
        searchCount = hits.Length;

        foreach (var result in hits.FetchResults(0, MAX_SEARCH_HITS))
        {
          var itemUri = new ItemUri(result.Url);
          if (itemUri != null)
          {
            if (AllLanguages || itemUri.Language == Context.CurrentLanguage)
            {
              var contextres = Context.SetContext(itemUri.ItemID.ToString(), null, null, itemUri.Version.Number);
              if (contextres.Status != CommandStatus.Success)
                return contextres;

              if (AllVersions || Context.CurrentItem.Versions.GetLatestVersion().Version.Number == itemUri.Version.Number)
              {
                if (!StatsOnly)
                  output.Append(Context.ExecuteCommand(Command, Formatter));

                foundCount++;
              }

              Context.Revert();
            }
          }
        }
      }

      if (StatsOnly)
        output.Append(foundCount);

      if (!NoStats && !StatsOnly)
      {
        Formatter.PrintLine(string.Empty, output);
        output.Append(string.Format("Found {0} {1}", foundCount, (foundCount == 1 ? "item" : "items")));

        if (searchCount == MAX_SEARCH_HITS)
        {
          Formatter.PrintLine(string.Empty, output);
          output.Append("WARNING: Number of results equals the maximum search hit count. You may not have all the results.");
        }
      }

      return new CommandResult(CommandStatus.Success, output.ToString());
    }
 protected void LoadItem(string id)
 {
     Assert.ArgumentNotNullOrEmpty(id, "id");
     if (ShortID.IsShortID(id))
     {
         id = ShortID.Decode(id);
     }
     ItemUri uri = new ItemUri(id, this.ContentEditorDataContext.Language, Context.ContentDatabase);
     this.LoadItem(uri, string.Empty);
 }
Ejemplo n.º 48
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);


            if (Context.ClientPage.IsEvent)
            {
                return;
            }

            var itemUri   = WebUtil.GetQueryString("itemUri");
            var fieldName = WebUtil.GetQueryString("fieldName");

            if (!ItemUri.IsItemUri(itemUri) || string.IsNullOrWhiteSpace(fieldName))
            {
                return;
            }

            var item = Database.GetItem(ItemUri.Parse(itemUri));

            if (item == null)
            {
                return;
            }

            var model = new HoursOfOperationModel(item[fieldName]);

            OpenTwentyFourHoursRaw.Value = model.OpenTwentyFourHours ? "1" : "0";

            if (model[DayOfWeek.Monday] != null)
            {
                MondayOpeningTimeSelectRaw.Value = model[DayOfWeek.Monday].OpeningTime;
                MondayClosingTimeSelectRaw.Value = model[DayOfWeek.Monday].ClosingTime;
                MondayClosedCheckboxRaw.Value    = model[DayOfWeek.Monday].IsClosed ? "1" : "0";
            }

            if (model[DayOfWeek.Tuesday] != null)
            {
                TuesdayOpeningTimeSelectRaw.Value = model[DayOfWeek.Tuesday].OpeningTime;
                TuesdayClosingTimeSelectRaw.Value = model[DayOfWeek.Tuesday].ClosingTime;
                TuesdayClosedCheckboxRaw.Value    = model[DayOfWeek.Tuesday].IsClosed ? "1" : "0";
            }

            if (model[DayOfWeek.Wednesday] != null)
            {
                WednesdayOpeningTimeSelectRaw.Value = model[DayOfWeek.Wednesday].OpeningTime;
                WednesdayClosingTimeSelectRaw.Value = model[DayOfWeek.Wednesday].ClosingTime;
                WednesdayClosedCheckboxRaw.Value    = model[DayOfWeek.Wednesday].IsClosed ? "1" : "0";
            }

            if (model[DayOfWeek.Thursday] != null)
            {
                ThursdayOpeningTimeSelectRaw.Value = model[DayOfWeek.Thursday].OpeningTime;
                ThursdayClosingTimeSelectRaw.Value = model[DayOfWeek.Thursday].ClosingTime;
                ThursdayClosedCheckboxRaw.Value    = model[DayOfWeek.Thursday].IsClosed ? "1" : "0";
            }

            if (model[DayOfWeek.Friday] != null)
            {
                FridayOpeningTimeSelectRaw.Value = model[DayOfWeek.Friday].OpeningTime;
                FridayClosingTimeSelectRaw.Value = model[DayOfWeek.Friday].ClosingTime;
                FridayClosedCheckboxRaw.Value    = model[DayOfWeek.Friday].IsClosed ? "1" : "0";
            }

            if (model[DayOfWeek.Saturday] != null)
            {
                SaturdayOpeningTimeSelectRaw.Value = model[DayOfWeek.Saturday].OpeningTime;
                SaturdayClosingTimeSelectRaw.Value = model[DayOfWeek.Saturday].ClosingTime;
                SaturdayClosedCheckboxRaw.Value    = model[DayOfWeek.Saturday].IsClosed ? "1" : "0";
            }

            if (model[DayOfWeek.Sunday] != null)
            {
                SundayOpeningTimeSelectRaw.Value = model[DayOfWeek.Sunday].OpeningTime;
                SundayClosingTimeSelectRaw.Value = model[DayOfWeek.Sunday].ClosingTime;
                SundayClosedCheckboxRaw.Value    = model[DayOfWeek.Sunday].IsClosed ? "1" : "0";
            }
        }
 protected void LoadItem(string id, string language, string version)
 {
     Assert.ArgumentNotNullOrEmpty(id, "id");
     Assert.ArgumentNotNull(language, "language");
     Assert.ArgumentNotNull(version, "version");
     ItemUri uri = new ItemUri(id, Language.Parse(language), Sitecore.Data.Version.Parse(version), Context.ContentDatabase);
     this.LoadItem(uri, string.Empty);
 }
Ejemplo n.º 50
0
    public void ShouldGetItemByUri()
    {
      // arrange
      using (var db = new Db
                        {
                          new DbItem("home", this.itemId)
                            {
                              new DbField("Title")
                                {
                                  { "en", 1, "Welcome!" }, 
                                  { "da", 1, "Hello!" },
                                  { "da", 2, "Velkommen!" }
                                }
                            }
                        })
      {
        // act & assert
        var uriEn1 = new ItemUri(this.itemId, Language.Parse("en"), Version.Parse(1), db.Database);
        Database.GetItem(uriEn1).Should().NotBeNull("the item '{0}' should not be null", uriEn1);
        Database.GetItem(uriEn1)["Title"].Should().Be("Welcome!");

        var uriDa1 = new ItemUri(this.itemId, Language.Parse("da"), Version.Parse(1), db.Database);
        Database.GetItem(uriDa1).Should().NotBeNull("the item '{0}' should not be null", uriDa1);
        Database.GetItem(uriDa1)["Title"].Should().Be("Hello!");

        var uriDa2 = new ItemUri(this.itemId, Language.Parse("da"), Version.Parse(2), db.Database);
        Database.GetItem(uriDa2).Should().NotBeNull("the item '{0}' should not be null", uriDa2);
        Database.GetItem(uriDa2)["Title"].Should().Be("Velkommen!");
      }
    }
        protected void Edit(ClientPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            if (Enabled)
            {
                if (args.IsPostBack)
                {
                    if (((args.Result != null) && (args.Result.Length > 0)) && (args.Result != "undefined"))
                    {
                        XmlDocument doc = XmlUtil.LoadXml(WebUtil.GetSessionString("ASR_COLUMNEDITOR"));
                        WebUtil.SetSessionValue("ASR_COLUMNEDITOR", null);

                        Value = doc.OuterXml;
                        SetModified();
                        Refresh();
                    }
                }
                else
                {
                    XmlDocument document = GetDocument();
                    WebUtil.SetSessionValue("ASR_COLUMNEDITOR", document.OuterXml);
                    UrlString urlString = new UrlString(UIUtil.GetUri("control:ColumnEditor"));
                    UrlHandle handle = new UrlHandle();
                    string value = Value;
                    if (value == "__#!$No value$!#__")
                    {
                        value = string.Empty;
                    }
                    handle["value"] = value;
                    handle["id"] =
                        new ItemUri(Sitecore.Data.ID.Parse(ItemID), Language.Parse(ItemLanguage), new Version(ItemVersion),
                                    Sitecore.Context.ContentDatabase).ToString(ItemUriFormat.Uri);
                    handle.Add(urlString);
                    SheerResponse.ShowModalDialog(urlString.ToString(), "800px", "500px", string.Empty, true);
                    args.WaitForPostBack();
                }
            }
        }
 /// <summary>
 /// Loads the template.
 /// </summary>
 /// <param name="uri">The item URI.</param>
 private void LoadTemplate(ItemUri uri)
 {
     Assert.ArgumentNotNull((object)uri, "uri");
     Item obj = Database.GetItem(uri);
     if (obj == null)
         return;
     this.Definition = TemplateBuilderForm.LoadTemplate((TemplateItem)obj).ToXml();
 }
Ejemplo n.º 53
0
 protected abstract bool ExecuteGetChildrenAsync([NotNull] ItemUri itemUri, [NotNull] EventHandler <GetChildrenCompletedEventArgs> callback);
Ejemplo n.º 54
0
        public virtual ProjectBase GetProjectContainingLinkedItem([NotNull] ItemUri itemUri)
        {
            Assert.ArgumentNotNull(itemUri, nameof(itemUri));

            return(null);
        }
    /// <summary>
    /// Locates the in sitecore explorer.
    /// </summary>
    /// <param name="site">The site.</param>
    /// <param name="renderingName">The name.</param>
    private void LocateInSitecoreExplorer(Site site, string renderingName)
    {
      Site.RequestCompleted completed = delegate(string response)
      {
        var parts = response.Split('|');
        if (parts.Length != 2)
        {
          AppHost.MessageBox(response, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
          return;
        }

        var itemUri = new ItemUri(new DatabaseUri(site, new DatabaseName(parts[0])), new ItemId(new Guid(parts[1])));

        AppHost.CurrentContentTree.Activate();
        AppHost.CurrentContentTree.Locate(itemUri);
      };

      site.Execute("XmlLayouts.GetRenderingItemUri", completed, renderingName);
    }
Ejemplo n.º 56
0
 protected abstract void ExecuteGetXmlAsync([NotNull] ItemUri itemUri, bool deep, [NotNull] EventHandler <GetXMLCompletedEventArgs> callback);
        private bool compareUris(ItemUri a, ItemUri b)
        {
            if (a == null || b == null)
                return false;

            return a.DatabaseName == b.DatabaseName
                && a.ItemID == b.ItemID
                && a.Language == b.Language
                && a.Version == b.Version;
        }
Ejemplo n.º 58
0
 protected abstract XmlElement ExecuteMove([NotNull] ItemUri itemUri, [NotNull] ItemId newParentId);
Ejemplo n.º 59
0
 protected abstract XmlElement ExecuteDuplicate([NotNull] ItemUri itemUri, [NotNull] string newName);
Ejemplo n.º 60
0
 protected abstract XmlElement ExecuteGetChildren([NotNull] ItemUri itemUri);