Example #1
0
 public SchemaFieldsData ReadSchemaFields(string schemaId, bool expandEmbeddedFields, ReadOptions readOptions)
 {
     return(_client.ReadSchemaFields(schemaId, expandEmbeddedFields, readOptions));
 }
Example #2
0
        private ViewModel CoreCreateModel(SchemaData schema, SessionAwareCoreServiceClient client)
        {
            Console.WriteLine("\nTitle:" + schema.Title + ", Schema Purpose: " + schema.Purpose);
            IList<FieldProperty> modelProperties = new List<FieldProperty>();
            ViewModel model = new ViewModel();
            switch (schema.Purpose)
            {
                case SchemaPurpose.Embedded:
                    model.BaseClass = typeof(ViewModelBase);
                    model.ModelType = ModelType.EmbeddedSchemaFields;
                    break;
                case SchemaPurpose.Component:
                    model.BaseClass = typeof(ViewModelBase);
                    model.ModelType = ModelType.ComponentPresentation;
                    break;
                case SchemaPurpose.Metadata:
                    return null;
                case SchemaPurpose.Multimedia:
                    model.BaseClass = typeof(ViewModelBase);
                    model.ModelType = ModelType.MultimediaComponent;
                    break;
                case SchemaPurpose.Protocol:
                    return null;
                case SchemaPurpose.TemplateParameters:
                    return null;
                case SchemaPurpose.UnknownByClient:
                    return null;
                case SchemaPurpose.VirtualFolderType:
                    return null;
                case SchemaPurpose.Bundle:
                    return null;
                default:
                    break;
            }

            SchemaFieldsData fields = client.ReadSchemaFields(schema.Id, false, expandedOptions);

            if (fields.Fields != null)
            {
                ProcessFields(fields.Fields, false, ref modelProperties);
            }
            if (fields.MetadataFields != null)
            {
                ProcessFields(fields.MetadataFields, true, ref modelProperties);
            }
            model.Name = schema.Title.ResolveModelName();
            model.SchemaName = schema.Title;
            model.FieldProperties = modelProperties;
            model.ContainingFolder = schema.LocationInfo.OrganizationalItem.Title.ResolveModelName();
            return model;
        }
        static void Main(string[] args)
        {
            //args[0] = "tcm:11-403-8";
            if (!args.Any())
            {
                Log("Please pass the Schema Tcm Uri as a parameter.");
                return;
            }
            string schemaUri = args[0];
            if (!TcmUri.IsValid(schemaUri))
            {
                Log("The specified URI of " + schemaUri + " is not a valid URI, please pass the schema Tcm Uri as a parameter.");
                return;
            }

            SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2013");
            if (!client.IsExistingObject(schemaUri))
            {
                Log("Could not find item with URI " + schemaUri + " in Tridion. Please pass the Schema Tcm Uri as a parameter.");
                return;
            }
            ReadOptions readOptions = new ReadOptions();
            UsingItemsFilterData whereUsedFilter = new UsingItemsFilterData { ItemTypes = new[] { ItemType.Component } };
            SchemaData schema = (SchemaData)client.Read(schemaUri, readOptions);
            SchemaFieldsData schemaFieldsData = client.ReadSchemaFields(schema.Id, true, readOptions);
            bool hasMeta = schemaFieldsData.MetadataFields.Any();
            string newNamespace = schema.NamespaceUri;

            if (schema.Purpose == SchemaPurpose.Metadata)
            {
                List<IdentifiableObjectData> items = new List<IdentifiableObjectData>();
                UsingItemsFilterData anyItem = new UsingItemsFilterData();
                foreach (XElement node in client.GetListXml(schema.Id, anyItem).Nodes())
                {
                    string uri = node.Attribute("ID").Value;
                    items.Add(client.Read(uri, readOptions));
                }
                Log("Found " + items.Count + " items using schema...");

                foreach (var item in items)
                {
                    if (item is PublicationData)
                    {
                        PublicationData pub = (PublicationData)item;
                        string meta = pub.Metadata;
                        XmlDocument xml = new XmlDocument();
                        xml.LoadXml(meta);
                        string oldnamespace = xml.DocumentElement.NamespaceURI;
                        if (oldnamespace != newNamespace)
                        {
                            Log("Replacing namespace for publication " + pub.Id + " (" + pub.Title + ") - Current Namespace: " + oldnamespace);
                            string metadata = meta.Replace(oldnamespace, newNamespace);
                            pub.Metadata = metadata;
                            client.Update(pub, readOptions);
                        }
                    }
                    else if (item is RepositoryLocalObjectData)
                    {
                        RepositoryLocalObjectData data = (RepositoryLocalObjectData)item;
                        string meta = data.Metadata;
                        XmlDocument xml = new XmlDocument();
                        xml.LoadXml(meta);
                        string oldnamespace = xml.DocumentElement.NamespaceURI;
                        if (oldnamespace != newNamespace)
                        {
                            Log("Replacing namespace for item " + data.Id + " (" + data.Title + ") - Current Namespace: " + oldnamespace);
                            string metadata = meta.Replace(oldnamespace, newNamespace);
                            data.Metadata = metadata;
                            client.Update(data, readOptions);
                        }

                    }
                }

                return;
            }

            List<ComponentData> components = new List<ComponentData>();
            foreach (XElement node in client.GetListXml(schema.Id, whereUsedFilter).Nodes())
            {
                string uri = node.Attribute("ID").Value;
                components.Add((ComponentData)client.Read(uri, readOptions));
            }
            Log("Found " + components.Count + " components.");

            Log("Current schema namespace set to " + newNamespace + ", checking for components with incorrect namespace.");
            int count = 0;
            foreach (var component in components)
            {
                if (schema.Purpose == SchemaPurpose.Multimedia)
                {
                    Log("Changing Multimedia Component");
                    string meta = component.Metadata;
                    XmlDocument metaXml = new XmlDocument();
                    metaXml.LoadXml(meta);
                    string metaOldnamespace = metaXml.DocumentElement.NamespaceURI;
                    if (metaOldnamespace != newNamespace)
                    {
                        Log("Replacing namespace for item " + component.Id + " (" + component.Title + ") - Current Namespace: " + metaOldnamespace);
                        string metadata = meta.Replace(metaOldnamespace, newNamespace);
                        component.Metadata = metadata;
                        client.Update(component, readOptions);
                    }
                    count++;
                    Log(components.Count - count + " components remaining...");

                    continue;
                }

                string content = component.Content;

                XmlDocument xml = new XmlDocument();
                xml.LoadXml(content);

                string oldnamespace = xml.DocumentElement.NamespaceURI;

                if (oldnamespace != newNamespace)
                {
                    Log("Replacing namespace for component " + component.Id + " (" + component.Title + ") - Current Namespace: " + oldnamespace);
                    content = content.Replace(oldnamespace, newNamespace);
                    try
                    {
                        ComponentData editableComponent = component;
                        editableComponent.Content = content;
                        if (hasMeta)
                        {
                            string metadata = editableComponent.Metadata.Replace(oldnamespace, newNamespace);

                            // Fix for new meta
                            if (string.IsNullOrEmpty(metadata))
                            {
                                metadata = string.Format("<Metadata xmlns=\"{0}\" />", newNamespace);
                                Log("Component had no metadata, but schema specifies it has. Adding empty metadata node");
                            }
                            editableComponent.Metadata = metadata;
                        }

                        if (!hasMeta && !(string.IsNullOrEmpty(editableComponent.Metadata)))
                        {
                            editableComponent.Metadata = string.Empty;
                        }

                        client.Update(editableComponent, readOptions);

                    }
                    catch (Exception ex)
                    {
                        Log("Error occurred trying to update component: " + component.Id + Environment.NewLine + ex);

                    }

                }
                count++;
                Log(components.Count - count + " components remaining...");
            }
        }
Example #4
0
        private string ImportSingleItem(IEclUri eclUri)
        {
            string id = "tcm:0-0-0";
            IContentLibraryMultimediaItem eclItem = (IContentLibraryMultimediaItem)_eclContentLibraryContext.GetItem(eclUri);
            string       extension = eclItem.Filename.Substring(eclItem.Filename.LastIndexOf('.') + 1);
            MemoryStream ms        = null;
            string       tempPath;

            try
            {
                // create some template attributes
                IList <ITemplateAttribute> attributes = CreateTemplateAttributes(eclItem);

                // determine if item has content or is available online
                string publishedPath = eclItem.GetDirectLinkToPublished(attributes);
                if (string.IsNullOrEmpty(publishedPath))
                {
                    // we can directly get the content
                    IContentResult content = eclItem.GetContent(attributes);
                    ms = new MemoryStream();
                    content.Stream.CopyTo(ms);
                    ms.Position = 0;
                }
                else
                {
                    // read the content from the publish path
                    using (WebClient webClient = new WebClient())
                    {
                        byte[] thumbnailData = webClient.DownloadData(publishedPath);
                        ms = new MemoryStream(thumbnailData, false);
                    }
                }

                // upload binary (using netTcp binding as configured in SDL Tridion, because this Model extension is running inside the UI)
                using (StreamUploadClient suClient = new StreamUploadClient("streamUpload_netTcp_2012"))
                {
                    tempPath = suClient.UploadBinaryContent(eclItem.Filename, ms);
                }
            }
            finally
            {
                if (ms != null)
                {
                    ms.Dispose();
                }
            }

            // create tcm item
            var mmComponent = new ComponentData
            {
                Id     = id,
                Title  = eclItem.Title,
                Schema = new LinkToSchemaData {
                    IdRef = _schemaUri
                },
                LocationInfo = new LocationInfo {
                    OrganizationalItem = new LinkToOrganizationalItemData {
                        IdRef = _folderUri
                    }
                }
            };

            // put binary data in tcm item (using netTcp binding as configured in SDL Tridion, because this Model extension is running inside the UI)
            using (SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2012"))
            {
                // impersonate with current user
                client.Impersonate(_username);

                // set metadata
                var schemaFields = client.ReadSchemaFields(_schemaUri, true, new ReadOptions());
                if (schemaFields.MetadataFields.Any())
                {
                    var fields = Fields.ForMetadataOf(schemaFields, mmComponent);
                    if (!string.IsNullOrEmpty(eclItem.MetadataXml))
                    {
                        XNamespace ns       = GetNamespace(eclItem.MetadataXml);
                        XDocument  metadata = XDocument.Parse(eclItem.MetadataXml);
                        var        children = metadata.Element(ns + "Metadata").Descendants();
                        for (int i = 0; i < children.Count(); i++)
                        {
                            fields.AddFieldElement(new ItemFieldDefinitionData {
                                Name = "data"
                            });
                            var embeddedFields = fields["data"].GetSubFields(i);
                            embeddedFields.AddFieldElement(new ItemFieldDefinitionData {
                                Name = "key"
                            });
                            embeddedFields.AddFieldElement(new ItemFieldDefinitionData {
                                Name = "value"
                            });
                            embeddedFields["key"].Value   = children.ElementAt(i).Name.LocalName;
                            embeddedFields["value"].Value = children.ElementAt(i).Value;
                        }
                    }
                    mmComponent.Metadata = fields.ToString();
                }

                // find multimedia type
                var list           = client.GetSystemWideList(new MultimediaTypesFilterData());
                var multimediaType = list.OfType <MultimediaTypeData>().Single(mt => mt.FileExtensions.Contains(extension));

                // set BinaryContent of a component
                mmComponent.BinaryContent = new BinaryContentData
                {
                    UploadFromFile = tempPath,
                    Filename       = eclItem.Filename,
                    MultimediaType = new LinkToMultimediaTypeData {
                        IdRef = multimediaType.Id
                    }
                };

                // create (and save) component
                ComponentData data = (ComponentData)client.Create(mmComponent, new ReadOptions());
                id = data.Id;
            }

            //string result = string.Format("created {0}, from {1}, in {2}, using {3}, for {4}", id, eclUri, _folderUri, _schemaUri, _username);
            return(id);
        }
        private string ImportSingleItem(IEclUri eclUri)
        {
            string id = "tcm:0-0-0";
            IContentLibraryMultimediaItem eclItem = (IContentLibraryMultimediaItem)_eclContentLibraryContext.GetItem(eclUri);
            string extension = eclItem.Filename.Substring(eclItem.Filename.LastIndexOf('.') + 1);
            MemoryStream ms = null;
            string tempPath;
            try
            {
                // create some template attributes
                IList<ITemplateAttribute> attributes = CreateTemplateAttributes(eclItem);

                // determine if item has content or is available online
                string publishedPath = eclItem.GetDirectLinkToPublished(attributes);
                if (string.IsNullOrEmpty(publishedPath))
                {
                    // we can directly get the content 
                    IContentResult content = eclItem.GetContent(attributes);
                    ms = new MemoryStream();
                    content.Stream.CopyTo(ms);
                    ms.Position = 0;
                }
                else
                {
                    // read the content from the publish path
                    using (WebClient webClient = new WebClient())
                    {
                        byte[] thumbnailData = webClient.DownloadData(publishedPath);
                        ms = new MemoryStream(thumbnailData, false);
                    }
                }

                // upload binary (using netTcp binding as configured in SDL Tridion, because this Model extension is running inside the UI) 
                using (StreamUploadClient suClient = new StreamUploadClient("streamUpload_netTcp_2012"))
                {
                    tempPath = suClient.UploadBinaryContent(eclItem.Filename, ms);
                }
            }
            finally
            {
                if (ms != null)
                {
                    ms.Dispose();
                }
            }

            // create tcm item
            var mmComponent = new ComponentData
            {
                Id = id,
                Title = eclItem.Title,
                Schema = new LinkToSchemaData { IdRef = _schemaUri },
                LocationInfo = new LocationInfo { OrganizationalItem = new LinkToOrganizationalItemData { IdRef = _folderUri } }
            };

            // put binary data in tcm item (using netTcp binding as configured in SDL Tridion, because this Model extension is running inside the UI) 
            using (SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2012"))
            {
                // impersonate with current user
                client.Impersonate(_username);

                // set metadata
                var schemaFields = client.ReadSchemaFields(_schemaUri, true, new ReadOptions());
                if (schemaFields.MetadataFields.Any())
                {
                    var fields = Fields.ForMetadataOf(schemaFields, mmComponent);
                    if (!string.IsNullOrEmpty(eclItem.MetadataXml))
                    {
                        XNamespace ns = GetNamespace(eclItem.MetadataXml);
                        XDocument metadata = XDocument.Parse(eclItem.MetadataXml);
                        var children = metadata.Element(ns + "Metadata").Descendants();
                        for (int i = 0; i < children.Count(); i++)
                        {
                            fields.AddFieldElement(new ItemFieldDefinitionData { Name = "data" });
                            var embeddedFields = fields["data"].GetSubFields(i);
                            embeddedFields.AddFieldElement(new ItemFieldDefinitionData { Name = "key" });
                            embeddedFields.AddFieldElement(new ItemFieldDefinitionData { Name = "value" });
                            embeddedFields["key"].Value = children.ElementAt(i).Name.LocalName;
                            embeddedFields["value"].Value = children.ElementAt(i).Value;
                        }
                    }
                    mmComponent.Metadata = fields.ToString();
                }

                // find multimedia type
                var list = client.GetSystemWideList(new MultimediaTypesFilterData());
                var multimediaType = list.OfType<MultimediaTypeData>().Single(mt => mt.FileExtensions.Contains(extension));

                // set BinaryContent of a component
                mmComponent.BinaryContent = new BinaryContentData
                {
                    UploadFromFile = tempPath,
                    Filename = eclItem.Filename,
                    MultimediaType = new LinkToMultimediaTypeData { IdRef = multimediaType.Id }
                };

                // create (and save) component
                ComponentData data = (ComponentData)client.Create(mmComponent, new ReadOptions());
                id = data.Id;
            }

            //string result = string.Format("created {0}, from {1}, in {2}, using {3}, for {4}", id, eclUri, _folderUri, _schemaUri, _username);
            return id;
        }
        /// <summary>
        /// Gets list of CT's along with the associated schema & view
        /// </summary>
        /// <param>none</param>
        /// <returns></returns>
        public static string GetAllItemsInPublication(string pubID)
        {
            RepositoryItemsFilterData filter = SetPageFilterCriterias();
            StringBuilder             sb     = new StringBuilder();

            cs_client = CoreServiceProvider.CreateCoreService();
            try
            {
                IdentifiableObjectData[] pages = cs_client.GetList(pubID, filter);

                foreach (IdentifiableObjectData iod in pages)
                {
                    PageData pageData = cs_client.Read(iod.Id, new ReadOptions()) as PageData;

                    sb.AppendLine("Page: " + pageData.LocationInfo.Path);
                    sb.AppendLine("PT: " + pageData.PageTemplate.Title);
                    sb.AppendLine("PM: " + pageData.MetadataSchema.Title);

                    foreach (ComponentPresentationData cpd in pageData.ComponentPresentations)
                    {
                        sb.AppendLine("");
                        sb.AppendLine("CP: " + cpd.Component.Title);

                        ComponentData cp = (ComponentData)cs_client.Read(cpd.Component.IdRef, new ReadOptions());
                        sb.AppendLine("CS: " + cp.Schema.Title);

                        sb.AppendLine("CT: " + cpd.ComponentTemplate.Title);
                        ComponentTemplateData ct = (ComponentTemplateData)cs_client.Read(cpd.ComponentTemplate.IdRef, new ReadOptions());
                        sb.AppendLine("CM: " + ct.MetadataSchema.Title);

                        // load the schema
                        var schemaFields = cs_client.ReadSchemaFields(cp.Schema.IdRef, true, new ReadOptions());

                        // build a  Fields object from it
                        var fields = Fields.ForContentOf(schemaFields, cp);

                        // let's first quickly list all values of all fields
                        foreach (var field in fields)
                        {
                            if (field.GetType() == typeof(EmbeddedSchemaFieldDefinitionData))
                            {
                            }
                            if (field.GetType() == typeof(ComponentLinkFieldDefinitionData))
                            {
                            }
                            if (field.GetType() == typeof(EmbeddedSchemaFieldDefinitionData))
                            {
                            }
                        }
                    }

                    //blank line for readability
                    sb.AppendLine("");
                    sb.AppendLine("");
                }
            }
            catch (Exception ex)
            {
                // throw ex;
            }
            finally
            {
                cs_client.Close();
            }

            return(sb.ToString());
        }