Exemple #1
0
        private void Close()
        {
            if (_client != null)
            {
                if (_client.State == CommunicationState.Faulted)
                {
                    _client.Abort();
                }
                else
                {
                    if (_client.State != CommunicationState.Opened)
                    {
                        return;
                    }

                    try
                    {
                        _client.Close();
                    }
                    catch (CommunicationException ex)
                    {
                        _client.Abort();
                    }
                    catch (TimeoutException ex)
                    {
                        _client.Abort();
                    }
                    catch (Exception ex)
                    {
                        _client.Abort();
                    }
                }
            }
        }
Exemple #2
0
 protected void CloseSession()
 {
     if (session.State != CommunicationState.Closed)
     {
         session.Close();
     }
 }
        /// <summary>
        /// Create Keywirds in a given category
        /// </summary>
        /// <param name="model">CategoryModel</param>
        /// <param name="CategoryId">tcm:xx-yy-zz</param>
        /// <returns></returns>
        public static string CreateKeywordsInCategory(CategoryModel model, string CategoryId)
        {
            var result = "true";

            cs_client = CoreServiceProvider.CreateCoreService();

            try
            {
                // open the category that is already created in Tridion
                CategoryData category = (CategoryData)cs_client.Read(CategoryId, null);

                var xmlCategoryKeywords = cs_client.GetListXml(CategoryId, new KeywordsFilterData());
                var keywordAny          = xmlCategoryKeywords.Elements()
                                          .Where(element => element.Attribute("Key").Value == model.Key)
                                          .Select(element => element.Attribute("ID").Value)
                                          .Select(id => (KeywordData)cs_client.Read(id, null)).FirstOrDefault();

                if (keywordAny == null)
                {
                    // create a new keyword
                    KeywordData keyword = (KeywordData)cs_client.GetDefaultData(Tridion.ContentManager.CoreService.Client.ItemType.Keyword, category.Id, new ReadOptions());
                    // set the id to 0 to notify Tridion that it is new
                    keyword.Id          = "tcm:0-0-0";
                    keyword.Title       = model.Title;
                    keyword.Key         = model.Key;
                    keyword.Description = model.Description;
                    keyword.IsAbstract  = false;

                    // create the keyword
                    cs_client.Create(keyword, null);
                    cs_client.Close();
                }
            }
            catch (Exception ex)
            {
                result = "Error: " + ex.Message;
            }
            finally
            {
                cs_client.Close();
            }

            return(result);
        }
 public void Dispose()
 {
     if (_client.State == CommunicationState.Faulted)
     {
         _client.Abort();
     }
     else
     {
         _client.Close();
     }
 }
        /// <summary>
        /// Gets list of CT's along with the associated schema & view
        /// </summary>
        /// <param>none</param>
        /// <returns></returns>
        public static string GetTemplatesInPublication(string pubID)
        {
            //note: this runs for about 1 minute
            StringBuilder sb = new StringBuilder();
            string        meta = string.Empty, ct = string.Empty, schema = string.Empty;

            byte[]       data = null;
            MemoryStream stm  = null;;
            XDocument    doc  = null;

            try
            {
                cs_client = CoreServiceProvider.CreateCoreService();

                // get the Id of the publication to import into
                RepositoryItemsFilterData templateFilter = SetTemplateFilterCriterias();
                XElement templates = cs_client.GetListXml(pubID, templateFilter);;

                foreach (XElement template in templates.Descendants())
                {
                    ComponentTemplateData t = (ComponentTemplateData)cs_client.Read(CheckAttributeValueOrEmpty(template, "ID"), null);

                    if (t.Metadata != "")
                    {
                        ct   = t.Title;
                        data = Encoding.ASCII.GetBytes(t.Metadata);
                        stm  = new MemoryStream(data, 0, data.Length);
                        doc  = XDocument.Load(stm);
                        meta = doc.Root.Value;

                        if (t.RelatedSchemas.Count() > 0)
                        {
                            schema = t.RelatedSchemas[0].Title;
                        }
                        else
                        {
                            schema = "No Schema Found";
                        }

                        sb.AppendLine(ct + "|" + schema + "|" + meta);
                    }
                }
            }
            catch (Exception ex)
            {
                // throw ex;
            }
            finally
            {
                cs_client.Close();
            }

            return(sb.ToString());
        }
        public void Dispose()
        {
            if (_client != null)
            {
                switch (_client.State)
                {
                case CommunicationState.Faulted:
                    _client.Abort();
                    break;

                case CommunicationState.Opened:
                    _client.Close();
                    break;
                }
                var disposable = _client as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
Exemple #7
0
        [Route("LocalizeComment")] // needs to be changed
        public bool LocalizeComment(LocalizeCommentsModel model)
        {
            SessionAwareCoreServiceClient client = null;

            try
            {
                client = GetClient();
                foreach (var itemId in model.itemIds)
                {
                    try
                    {
                        Localize(client, itemId);

                        var dict = new Dictionary <string, string>();
                        dict.Add(model.appDataKey + "Comments", model.comments);
                        dict.Add(model.appDataKey + "User", Tridion.Web.UI.Core.Utils.GetUserName());
                        dict.Add(model.appDataKey + "Date", DateTime.Now.ToString());
                        SetAppData(client, itemId, dict);
                    }
                    catch (Exception ex)
                    {
                        throw new ApplicationException("Unable to save localization comments for the item[" + itemId + "]", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error in localize comment process", ex);
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }

            return(true);
        }
        /// <summary>
        /// This allows efficient use of the CoreServices and automatic disposal and cleanup when
        /// properly used within using {} statements.
        /// </summary>
        public void Dispose()
        {
            if (_client != null)
            {
                switch (_client.State)
                {
                case CommunicationState.Faulted:
                    _client.Abort();
                    break;

                case CommunicationState.Opened:
                    _client.Close();
                    break;
                }

                //Since clientSession is by default an Interface we must polymorphically re-cast back
                //to IDisposable and then ensure it is still valid to safely dispose of the item.
                var disposable = _client as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
Exemple #9
0
 public void Close()
 {
     _client.Close();
 }
        public bool UploadToTridion(string fileName)
        {
            client = PowerTools.Common.CoreService.Client.GetCoreService();
            try
            {
                string mmType = GetMultiMediaType(Path.GetExtension(fileName));
                if (mmType != null)
                {
                    BinaryContentData bcd = new BinaryContentData
                    {
                        UploadFromFile = fileName,
                        MultimediaType = new LinkToMultimediaTypeData {
                            IdRef = mmType
                        },
                        Filename   = Path.GetFileName(fileName),
                        IsExternal = false
                    };

                    ComponentData compData = new ComponentData
                    {
                        LocationInfo = new LocationInfo
                        {
                            OrganizationalItem = new LinkToOrganizationalItemData
                            {
                                IdRef = orgItemUri //Organizational item
                            },
                        },
                        ComponentType = ComponentType.Multimedia,
                        Title         = MakeValidFileName(Path.GetFileNameWithoutExtension(fileName)),

                        Schema = new LinkToSchemaData
                        {
                            IdRef = schemaUri
                        },

                        IsBasedOnMandatorySchema  = false,
                        IsBasedOnTridionWebSchema = true,
                        ApprovalStatus            = new LinkToApprovalStatusData
                        {
                            IdRef = "tcm:0-0-0"
                        },
                        Id            = "tcm:0-0-0",
                        BinaryContent = bcd
                    };

                    ComponentData comp = (ComponentData)client.Create(compData, new ReadOptions());
                    return(true);
                }
            }
            catch (Exception ex)
            {
                string d = ex.Message;
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }

            return(false);
        }
        public override void Process(ServiceProcess process, object arguments)
        {
            ImageUploadParameters parameters = (ImageUploadParameters)arguments;

            try
            {
                string directory = parameters.Directory;
                if (!Directory.Exists(directory))
                {
                    process.Failed = true;
                    process.Complete(string.Format(CultureInfo.InvariantCulture, "Directory '{0}' does not exist. No images were uploaded!", directory));
                    return;
                }
                string[] files = Directory.GetFiles(directory);
                int      i     = 0;
                _client = PowerTools.Common.CoreService.Client.GetCoreService();

                //Get all component titles in the target folder
                _componentTitles = getAllComponentTitles(parameters.FolderUri);

                foreach (string file in files)
                {
                    process.SetStatus("Importing image: " + Path.GetFileName(file));
                    process.SetCompletePercentage(++i * 100 / files.Length);

                    FileInfo fileInfo = new FileInfo(file);
                    if (fileInfo.Exists)
                    {
                        string mmType = GetMultiMediaType(fileInfo.Extension);
                        if (mmType != null)
                        {
                            BinaryContentData bcd = new BinaryContentData
                            {
                                UploadFromFile = file,
                                MultimediaType = new LinkToMultimediaTypeData {
                                    IdRef = mmType
                                },
                                Filename   = file,
                                IsExternal = false
                            };

                            ComponentData compData = new ComponentData
                            {
                                LocationInfo = new LocationInfo
                                {
                                    OrganizationalItem = new LinkToOrganizationalItemData
                                    {
                                        IdRef = parameters.FolderUri                                         //Organizational item
                                    },
                                },
                                ComponentType = ComponentType.Multimedia,
                                Title         = MakeValidFileName(fileInfo.Name),

                                Schema = new LinkToSchemaData
                                {
                                    IdRef = parameters.SchemaUri                                     //schemaData.IdRef
                                },

                                IsBasedOnMandatorySchema  = false,
                                IsBasedOnTridionWebSchema = true,
                                ApprovalStatus            = new LinkToApprovalStatusData
                                {
                                    IdRef = "tcm:0-0-0"
                                },
                                Id            = "tcm:0-0-0",
                                BinaryContent = bcd
                            };

                            ComponentData comp = (ComponentData)_client.Create(compData, new ReadOptions());
                        }
                    }
                }

                process.Complete();
            }
            finally
            {
                if (_client != null)
                {
                    _client.Close();
                }
            }
        }
        public bool UploadToTridion(string fileName)
        {
            client = PowerTools.Common.CoreService.Client.GetCoreService();
            try
            {
                string mmType = GetMultiMediaType(Path.GetExtension(fileName));
                if (mmType != null)
                {

                    BinaryContentData bcd = new BinaryContentData
                    {
                        UploadFromFile = fileName,
                        MultimediaType = new LinkToMultimediaTypeData { IdRef = mmType },
                        Filename = Path.GetFileName(fileName),
                        IsExternal = false
                    };

                    ComponentData compData = new ComponentData
                    {
                        LocationInfo = new LocationInfo
                        {
                            OrganizationalItem = new LinkToOrganizationalItemData
                            {
                                IdRef = orgItemUri //Organizational item
                            },
                        },
                        ComponentType = ComponentType.Multimedia,
                        Title = MakeValidFileName(Path.GetFileNameWithoutExtension(fileName)),

                        Schema = new LinkToSchemaData
                        {
                            IdRef = schemaUri 
                        },

                        IsBasedOnMandatorySchema = false,
                        IsBasedOnTridionWebSchema = true,
                        ApprovalStatus = new LinkToApprovalStatusData
                        {
                            IdRef = "tcm:0-0-0"
                        },
                        Id = "tcm:0-0-0",
                        BinaryContent = bcd
                    };

                    ComponentData comp = (ComponentData)client.Create(compData, new ReadOptions());
                    return true;
                }
            }
            catch (Exception ex)
            {
                string d = ex.Message;
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }

            return false;
        }
Exemple #13
0
        public SocialPageData Execute(string pageUri)
        {
            SessionAwareCoreServiceClient client = null;
            SocialPageData socialPageData        = new SocialPageData();

            try
            {
                client = Client.GetCoreService();

                string liveTargetUri = Configuration.GetConfigString("livetargeturi");
                string liveUrl       = Configuration.GetConfigString("liveurl");

                PageData            pageData = (PageData)client.Read(pageUri, new ReadOptions());
                PublishLocationInfo pubInfo  = (PublishLocationInfo)pageData.LocationInfo;

                socialPageData.Title       = pageData.Title;
                socialPageData.Uri         = pageUri;
                socialPageData.Url         = liveUrl + pubInfo.PublishLocationUrl;
                socialPageData.IsPublished = client.IsPublished(pageUri, liveTargetUri, true);
                socialPageData.UseShortUrl = bool.Parse(Configuration.GetConfigString("shorturl"));

                string shortUrl = string.Empty;

                if (socialPageData.UseShortUrl)
                {
                    ApplicationData appData = client.ReadApplicationData(pageUri, SHORT_URL_APP_ID);

                    if (appData != null)
                    {
                        Byte[] data = appData.Data;
                        shortUrl = Encoding.Unicode.GetString(data);
                    }

                    if (shortUrl.Equals(string.Empty))
                    {
                        Bitly  service = new Bitly(socialPageData.Url);
                        string shorter = service.ShortenUrl(service.UrlToShorten, service.BitlyLogin, service.BitlyAPIKey);
                        shortUrl = Bitly.ParseXmlResponse(shorter, false);

                        Byte[] byteData = Encoding.Unicode.GetBytes(shortUrl);
                        appData = new ApplicationData
                        {
                            ApplicationId = SHORT_URL_APP_ID,
                            Data          = byteData,
                            TypeId        = shortUrl.GetType().ToString()
                        };

                        client.SaveApplicationData(pageUri, new[] { appData });
                    }
                }

                socialPageData.ShortUrl = shortUrl;
            }
            catch (Exception ex)
            {
                socialPageData.HasError  = true;
                socialPageData.ErrorInfo = ex;
            }
            finally
            {
                if (client != null)
                {
                    if (client.State == CommunicationState.Faulted)
                    {
                        client.Abort();
                    }
                    else
                    {
                        client.Close();
                    }
                }
            }

            return(socialPageData);
        }
        /// <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());
        }
		public override void Process(ServiceProcess process, object arguments)
		{
			ImageUploadParameters parameters = (ImageUploadParameters)arguments;

			try
			{
                string directory = parameters.Directory;
                if (!Directory.Exists(directory))
                {
                    process.Failed = true;
                    process.Complete(string.Format(CultureInfo.InvariantCulture, "Directory '{0}' does not exist. No images were uploaded!", directory));
                    return;
                }
                string[] files = Directory.GetFiles(directory);
				int i = 0;
                _client = PowerTools.Common.CoreService.Client.GetCoreService();

                //Get all component titles in the target folder           
                _componentTitles = getAllComponentTitles(parameters.FolderUri);

				foreach (string file in files)
				{
					process.SetStatus("Importing image: " + Path.GetFileName(file));
					process.SetCompletePercentage(++i * 100 / files.Length);
					
					FileInfo fileInfo = new FileInfo(file);
					if (fileInfo.Exists)
					{
						string mmType = GetMultiMediaType(fileInfo.Extension);
						if (mmType != null)
						{
							BinaryContentData bcd = new BinaryContentData
							{
								UploadFromFile = file,
								MultimediaType = new LinkToMultimediaTypeData { IdRef = mmType },
								Filename = file,
								IsExternal = false
							};

							ComponentData compData = new ComponentData
							{
								LocationInfo = new LocationInfo
								{
									OrganizationalItem = new LinkToOrganizationalItemData
									{
										IdRef = parameters.FolderUri //Organizational item
									},
								},
								ComponentType = ComponentType.Multimedia,
								Title = MakeValidFileName(fileInfo.Name),

								Schema = new LinkToSchemaData
								{
									IdRef = parameters.SchemaUri //schemaData.IdRef
								},

								IsBasedOnMandatorySchema = false,
								IsBasedOnTridionWebSchema = true,
								ApprovalStatus = new LinkToApprovalStatusData
								{
									IdRef = "tcm:0-0-0"
								},
								Id = "tcm:0-0-0",
								BinaryContent = bcd
							};

							ComponentData comp = (ComponentData)_client.Create(compData, new ReadOptions());
						}
					}
				}

				process.Complete();
			}
			finally
			{
				if (_client != null)
				{
					_client.Close();
				}
			}
		}