public static SessionAwareCoreServiceClient GetCoreService() { var client = new SessionAwareCoreServiceClient("netTcp_2013"); client.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName()); return(client); }
public static SessionAwareCoreServiceClient GetCoreServiceWsHttpInstance(string hostName, string username, string password, string domain, CoreServiceInstance version) { var httpBinding = new WSHttpBinding { MaxReceivedMessageSize = 2147483647, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxStringContentLength = 2147483647, MaxArrayLength = 2147483647 } }; var remoteAddress = new EndpointAddress( string.Format("http://{0}/webservices/CoreService{1}.svc/wsHttp", hostName, (int)version)); var coreServiceClient = new SessionAwareCoreServiceClient(httpBinding, remoteAddress); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { coreServiceClient.ClientCredentials.Windows.ClientCredential.UserName = username; coreServiceClient.ClientCredentials.Windows.ClientCredential.Password = password; } if (!string.IsNullOrEmpty(domain)) { coreServiceClient.ClientCredentials.Windows.ClientCredential.Domain = domain; } //coreServiceClient.Impersonate("Siavash Shibani"); Instance = coreServiceClient; return(Instance); }
/// <summary> /// Initialize the CoreService Context /// </summary> /// <param name="endpointUri"></param> /// <param name="windowsNetworkCredentials"></param> public CoreServiceFrameworkContext(Uri endpointUri, NetworkCredential windowsNetworkCredentials) { _endpointUri = endpointUri; //Dynamically instantiate the correct binding from the Abstract method that each implementing class will provide. var endpointBinding = this.GetBinding(); //Create the Endpoint Address for WCF var endpointAddress = new EndpointAddress(endpointUri); //Initialize the Client Proxy and the NetworkCredentials for Connection, if NetworkCreditials are null then skip //and allow .Net to process with defaults. _client = new SessionAwareCoreServiceClient(endpointBinding, endpointAddress); //Implement Optimizations for the Service connection shared by all Implementations //NOTE: If specified then implement NetworkSecurity Credentials if (windowsNetworkCredentials != null) { _client.ChannelFactory.Credentials.Windows.ClientCredential = windowsNetworkCredentials; } //NOTE: Implement optimizations for WCF Client Connection // See this Blog for more info. on WCF Optimization: http://blog.shutupandcode.net/?p=1085 if (_client.State == CommunicationState.Created) { _client.Open(); } }
public Article(SessionAwareCoreServiceClient client, TcmUri location) : base(client) { ComponentData component = (ComponentData)Client.GetDefaultData(ItemType.Component, location, ReadOptions); component.Schema = new LinkToSchemaData { IdRef = ContentManager.ResolveUrl(Constants.ArticleSchemaUrl) }; Content = component; }
static void Main(string[] args) { var skipped = new List <string>(); var updated = new List <string>(); var failed = new List <FailureNotice>(); int current = 0; _whatIf = (args.Length > 0 && args[0].ToLowerInvariant() == "-whatif"); Console.CursorVisible = false; using (var client = new SessionAwareCoreServiceClient()) { var publications = client.GetSystemWideList(new PublicationsFilterData()); int total = publications.Length; if (_whatIf) { Console.WriteLine(Resources.NoChangesWillBeMade); } Console.WriteLine(GetResource(@"StartSummary"), total); Console.WriteLine(); ShowProgress(0, total); foreach (var publication in publications) { var amPublication = new Publication(new UserContext(), new TcmUri(publication.Id)); if (amPublication.Exists) { try { if (!_whatIf) { TopologyHelper.UpdateTopology(amPublication); } updated.Add(GetDescription(publication)); } catch (Exception ex) { failed.Add(new FailureNotice { Title = GetDescription(publication), Error = ex.Message }); } } else { skipped.Add(GetDescription(publication)); } ShowProgress(++current, total); } } OutputSummary(updated, failed, skipped); Quit(); }
protected ContentItem(TcmUri itemId, SessionAwareCoreServiceClient client) { ReadOptions = new ReadOptions(); Client = client; Content = (ComponentData) client.Read(itemId, ReadOptions); ContentManager = new ContentManager(Client); }
static void Main(string[] args) { // Parse the input arguments. Parser.Default.ParseArguments <CommandLineOptions>(args) .WithParsed <CommandLineOptions>(opts => { using (var client = new SessionAwareCoreServiceClient(opts.EndpointName)) { var creator = new ItemCreator(client, opts.publicationName, opts.XlsxPath); switch (opts.Type) { case CreationType.Folders: { creator.CreateFolders(opts.FolderName); break; } case CreationType.Keywords: { creator.CreateKeywords(opts.CategoryName); break; } case CreationType.StructureGroups: { creator.CreateStructureGroups(opts.StructureGroupName); break; } } } }); }
protected ContentItem(ComponentData content, SessionAwareCoreServiceClient client) { Content = content; Client = client; ReadOptions = new ReadOptions(); ContentManager = new ContentManager(Client); }
public static SessionAwareCoreServiceClient GetCoreService() { var result = new SessionAwareCoreServiceClient(); result.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName()); return(result); }
/// <summary> /// Get publishing targets for any given publication /// </summary> /// <param name="publicationID"></param> /// <returns></returns> public static Dictionary <string, List <string> > GetPublishingTargets(List <string> publicationIDs) { cs_client = CoreServiceProvider.CreateCoreService(); Dictionary <string, List <string> > resultTargets = new Dictionary <string, List <string> >(); var pubTargets = cs_client.GetSystemWideList(new PublicationTargetsFilterData()); foreach (var publicationID in publicationIDs) { foreach (PublicationTargetData pubTargetdata in pubTargets) { List <string> targetIds = new List <string>(); PublicationTargetData target = (PublicationTargetData)cs_client.Read(pubTargetdata.Id, new ReadOptions()); LinkToPublicationData[] pubDataItems = target.Publications; foreach (LinkToPublicationData publicationData in pubDataItems) { if (publicationData.IdRef == publicationID) { if (resultTargets.ContainsKey(publicationData.Title)) { resultTargets[publicationData.Title].Add(pubTargetdata.Id); } else { targetIds.Add(pubTargetdata.Id); resultTargets.Add(publicationData.Title, targetIds); } } } } } return(resultTargets); }
/// <summary> /// Initialize TreeView by setting image url attributes based on Tridion url /// </summary> private void Initialize() { // use net.tcp core service client as we are on the machine itself var endpoint = new EndpointAddress(ConfigurationManager.AppSettings["endpointAddress"]); var binding = new NetTcpBinding { MaxReceivedMessageSize = 2147483647, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxStringContentLength = 2147483647, MaxArrayLength = 2147483647 } }; _client = new SessionAwareCoreServiceClient(binding, endpoint); // impersonate core service call with currently logged on user if (!String.IsNullOrEmpty(LogonUser)) { _client.Impersonate(LogonUser); } _tcmUrl = ConfigurationManager.AppSettings["sdlTridionCmsUrl"]; EmbeddedTreeView.ExpandImageUrl = _tcmUrl + ExpandImage; EmbeddedTreeView.CollapseImageUrl = _tcmUrl + CollapseImage; }
public void AddReversedFieldToPackageTest() { var templateId = "/webdav/04%20Web/Building%20Blocks/System/Templates/Test/TestCT-ReversedString.tctcmp"; var itemId = "/webdav/04%20Web/Building%20Blocks/Test/PerSchema/Dummy/GeneratedTestData_1.xml"; var client = new SessionAwareCoreServiceClient("wsHttp_2013"); client.ClientCredentials.Windows.ClientCredential.Domain = ConfigurationManager.AppSettings.Get("domain"); client.ClientCredentials.Windows.ClientCredential.Password = ConfigurationManager.AppSettings.Get("password"); client.ClientCredentials.Windows.ClientCredential.UserName = ConfigurationManager.AppSettings.Get("username"); var publishInstruction = new PublishInstructionData { RenderInstruction = new RenderInstructionData { RenderMode = RenderMode.PreviewDynamic }, ResolveInstruction = new ResolveInstructionData { StructureResolveOption = StructureResolveOption.OnlyItems } }; try { client.RenderItem(itemId, templateId, publishInstruction, ConfigurationManager.AppSettings.Get("publicationTargetId")); } catch (Exception ex) { Assert.Fail("Rendering {0} with {1} failed: {2}", templateId, itemId, ex.Message); } }
internal static string LoadConfigurationImpl() { using (Tracer.GetTracer().StartTrace()) { using (SessionAwareCoreServiceClient client = CoreServiceManager.GetCoreServiceClient()) { try { ApplicationData appData = client.ReadApplicationData(null, Constants.DXA_RESOLVER_CONFIGURATION_NAME); if (appData != null) { ApplicationDataAdapter ada = new ApplicationDataAdapter(appData); XmlElement appDataXml = ada.GetAs <XmlElement>(); return(appDataXml.OuterXml); } return(String.Format( "<Configuration xmlns:{0}=\"{1}\"></Configuration>", Constants.DXA_RESOLVER_CONFIGURATION_PREFIX, Constants.DXA_RESOLVER_CONFIGURATION_NAMESPACE )); } catch (Exception ex) { throw new Exception( Resources.DXA_CM_Extensions_DXAResolver_Models_Strings.CR_LoadConfigurationFailed, ex); } } } }
static void Main(string[] args) { SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2013"); ContentManager cm = new ContentManager(client); List<Source> sources = cm.GetSources(); XDocument opml = XDocument.Load("feeds.xml"); foreach (XElement node in opml.Root.Elements("body").Elements("outline")) { // check if it already exists string url = node.Attribute("xmlUrl").Value; bool found = sources.Any(source => source.RssFeedUrl == url); if (!found) { Source source = new Source(client) { RssFeedUrl = url, Title = node.Attribute("text").Value }; source.Save(); Console.WriteLine("Created new source: " + source.Title); } } }
private void InitializeSessionAwareClient(string endPoint, NetworkCredential credentials) { //TODO: Resolve Error try { var binding = new WSHttpBinding { MaxReceivedMessageSize = 2147483647, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxStringContentLength = 2147483647, MaxArrayLength = 2147483647 } }; var _sessionAwareClient = new SessionAwareCoreServiceClient(binding, new EndpointAddress(endPoint + "/wsHttp")); if (_sessionAwareClient.ClientCredentials != null) { _sessionAwareClient.ClientCredentials.Windows.ClientCredential = credentials; } if (_sessionAwareClient != null) { _coreServiceVersion = _sessionAwareClient.GetApiVersion(); } } catch (EndpointNotFoundException e) { } catch (Exception e) { } }
public CoreServiceClent(string bindingName, string domainName, string userName, string passWord) { //priority, if binding name existins in config file if (!string.IsNullOrEmpty(bindingName)) { _client = new SessionAwareCoreServiceClient(bindingName); } else { //default binding set to wsHttp _client = new SessionAwareCoreServiceClient("wsHttp"); } //priority, if custom domain, username, password exists in cofig file if (!string.IsNullOrEmpty(domainName) && !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(passWord)) { string usernameFull = domainName + "\\" + userName; var credentials = new NetworkCredential(usernameFull, passWord); _client.ChannelFactory.Credentials.Windows.ClientCredential = credentials; } else { //default set to current windows login _client.Impersonate(WindowsIdentity.GetCurrent().Name); } }
internal static string SaveConfigurationImpl(string configurationXml) { using (Tracer.GetTracer().StartTrace(configurationXml)) { using (SessionAwareCoreServiceClient client = CoreServiceManager.GetCoreServiceClient()) { try { XmlDocument appDataXml = new XmlDocument(); appDataXml.LoadXml(configurationXml); ApplicationDataAdapter ada = new ApplicationDataAdapter(Constants.DXA_RESOLVER_CONFIGURATION_NAME, appDataXml.DocumentElement); client.SaveApplicationData(null, new[] { ada.ApplicationData }); return(configurationXml); } catch (Exception ex) { throw new Exception( Resources.DXA_CM_Extensions_DXAResolver_Models_Strings.CR_SaveConfigurationFailed, ex); } } } }
protected override void Notify(UserData userData, WorkItemData[] workItemData, XElement applicationData) { var emailaddress = applicationData.Element("EmailAddress").Value; var xml = GetWorkflowDataXml(userData, workItemData, applicationData); if (xslt == null) { using (var client = new SessionAwareCoreServiceClient("wsHttp_2011")) //TODO: Refactor { client.Impersonate(userData.Title); var xsltBody = client.Read(ConfigurationManager.AppSettings.Get("EmailNotifier.TcmIdXslt"), new ReadOptions()) as TemplateBuildingBlockData; xslt = xsltBody.Content; } } var myXslTrans = new XslCompiledTransform(); myXslTrans.Load(new XmlTextReader(new StringReader(xslt))); using (var sr = new StringWriter()) { myXslTrans.Transform(xml.CreateNavigator(), null, sr); //Read mailFrom from mail-settings in App.Config var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; SendMail(emailaddress, mailSettings.Smtp.Network.UserName, "Tridion Community Email notifier", sr.ToString()); } }
public NewUserReturnData CreateUser(String userName) { SessionAwareCoreServiceClient coreService = Client.GetCoreService(); try { #if TRIDION2013 UserData userData = (UserData)coreService.GetDefaultData(ItemType.User, null, new ReadOptions()); #else UserData userData = (UserData)coreService.GetDefaultData(ItemType.User, null); #endif userData.Title = userName; userData.Description = userName; userData = (UserData)coreService.Create(userData, new ReadOptions()); _newUserReturnData = new NewUserReturnData(); _newUserReturnData.UserDescription = userData.Description; _newUserReturnData.UserName = userData.Title; _newUserReturnData.UserID = userData.Id; _newUserReturnData.ErrorMessage = null; } catch (Exception e) { _newUserReturnData = new NewUserReturnData(); _newUserReturnData.UserDescription = "Creation Failed"; _newUserReturnData.UserName = userName; _newUserReturnData.UserID = null; _newUserReturnData.ErrorMessage = e.Message; } return(_newUserReturnData); }
public Person(SessionAwareCoreServiceClient client) : base(client) { Content = (ComponentData)Client.GetDefaultData(ItemType.Component, Constants.PersonLocationUrl); Content.Schema = new LinkToSchemaData { IdRef = ContentManager.ResolveUrl(Constants.PersonSchemaUrl) }; }
/// <summary> /// Create bundle from given schema /// </summary> /// <param name="schemaID"></param> /// <param name="folderId"></param> /// <returns></returns> public static VirtualFolderData CreateBundle(string schemaID, string folderId) { cs_client = CoreServiceProvider.CreateCoreService(); SchemaData bundleSchema = (SchemaData)cs_client.Read(schemaID, new ReadOptions()); SchemaData virtualFolderTypeSchema = cs_client.GetVirtualFolderTypeSchema(@"http://www.sdltridion.com/ContentManager/Bundle"); VirtualFolderData bundle = new VirtualFolderData() { Id = "tcm:0-0-0", Title = "Test Bundle Title", Description = "Test Bundle Description", MetadataSchema = new LinkToSchemaData() { IdRef = bundleSchema.Id }, TypeSchema = new LinkToSchemaData() { IdRef = virtualFolderTypeSchema.Id }, LocationInfo = new LocationInfo() { OrganizationalItem = new LinkToOrganizationalItemData() { IdRef = folderId } } }; bundle = (VirtualFolderData)cs_client.Create(bundle, new ReadOptions()); return(bundle); }
/// <summary> /// Initializes a new instance of the <see cref="Session"/> class. /// </summary> /// <param name="clientMode"><see cref="T:TcmCoreService.Configuration.ClientMode" /></param> /// <param name="targetUri">Target <see cref="T:System.Uri" /></param> /// <param name="domain">Optional domain</param> /// <param name="userName">Optional username</param> /// <param name="password">Optional password</param> public Session(ClientMode clientMode, Uri targetUri, String domain, String userName, String password) : base(targetUri, userName, password) { mClientMode = clientMode; mTargetUri = targetUri; switch (clientMode) { case ClientMode.HttpClient: mClient = new SessionAwareCoreServiceClient(ClientConfiguration.ClientWSHttpBinding, new EndpointAddress(ClientConfiguration.ClientWSHttpUri(targetUri))); break; case ClientMode.TcpClient: default: if (ClientConfiguration.IsRunningOnMono) throw new NotImplementedException ("NetTcpBinding on Mono cannot be used with Tridion CoreService"); mClient = new SessionAwareCoreServiceClient(ClientConfiguration.ClientTcpBinding, new EndpointAddress(ClientConfiguration.ClientTcpUri(targetUri))); break; } if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password)) { if (!String.IsNullOrEmpty(domain)) mCredentials = new NetworkCredential(userName, password, domain); else mCredentials = new NetworkCredential(userName, password); } else mCredentials = CredentialCache.DefaultNetworkCredentials; mClient.ClientCredentials.Windows.ClientCredential = mCredentials; }
protected ContentItem(TcmUri itemId, SessionAwareCoreServiceClient client) { ReadOptions = new ReadOptions(); Client = client; Content = (ComponentData)client.Read(itemId, ReadOptions); ContentManager = new ContentManager(Client); }
public List <string> GenerateInfoForAllSchema() { List <string> allSchema = new List <string>(); TcmUri uri = new TcmUri(bbFolderURI); SessionAwareCoreServiceClient client = GetCoreServiceClient(); RepositoryItemsFilterData filter = new RepositoryItemsFilterData(); filter.ItemTypes = new[] { Tridion.ContentManager.CoreService.Client.ItemType.Schema }; filter.Recursive = true; filter.BaseColumns = Tridion.ContentManager.CoreService.Client.ListBaseColumns.Id; IdentifiableObjectData[] schemas = client.GetList(bbFolderURI, filter); foreach (SchemaData schema in schemas) { SchemaData sch = (SchemaData)client.Read(schema.Id, null); ParseSchema(sch); allSchema.Add(formattedSchemaInfo); } return(allSchema); }
public void Open(string endPoint, NetworkCredential credentials) { _client = new SessionAwareCoreServiceClient(endPoint); if (credentials != null) { _client.ChannelFactory.Credentials.Windows.ClientCredential = credentials; } }
private void SetAppData(SessionAwareCoreServiceClient client, string itemUri, string applicationId, string value) { var appData = new ApplicationData(); appData.ApplicationId = applicationId; appData.Data = new ASCIIEncoding().GetBytes(value); client.SaveApplicationData(itemUri, new ApplicationData[] { appData }); }
public string[] GetExportEndpointAndStreamDownloadAddresses() { // Export endpoint and stream download endpoint are returned as a two element string array, // where the export endpoint is the first entry and the stream download endpoint is the second. string[] exportEndpointAndStreamDownloadAddresses = { string.Empty, string.Empty }; // Create a new, null Core Service Client SessionAwareCoreServiceClient client = null; // TODO: Use Client, not client (then you don't have to worry about handling abort/dispose/etc.). <- Alchemy version 7.0 or higher // With Client, no need to call client.Abort(); can we also remove catch block below if using Client? Fix in other parts of code as well... try { // Creates a new core service client client = new SessionAwareCoreServiceClient("netTcp_2013"); // Gets the current user so we can impersonate them for our client string username = GetUserName(); client.Impersonate(username); // App data is set up with the following parameters. string exportEndpointId = "exportEndpointAddr"; string streamDownloadId = "streamDownloadAddr"; // Pass null for the item ID, since this app data does not correspond to any items in Tridion. ApplicationData appData = client.ReadApplicationData(null, exportEndpointId); if (appData != null) { Byte[] data = appData.Data; // exportEndpointId corresponds to the first element of the array return value. exportEndpointAndStreamDownloadAddresses[0] = Encoding.Unicode.GetString(data); } appData = client.ReadApplicationData(null, streamDownloadId); if (appData != null) { Byte[] data = appData.Data; // streamDownloadId corresponds to the second element of the array return value. exportEndpointAndStreamDownloadAddresses[1] = Encoding.Unicode.GetString(data); } // Explicitly abort to ensure there are no memory leaks. client.Abort(); } catch (Exception ex) { // Proper way of ensuring that the client gets closed. if (client != null) { client.Abort(); } // We are rethrowing the original exception and just letting webapi handle it. throw ex; } return(exportEndpointAndStreamDownloadAddresses); }
public string GetPathOfSelectedItem(string tcm) { string path = string.Empty; // Create a new, null Core Service Client SessionAwareCoreServiceClient client = null; try { // Creates a new core service client client = new SessionAwareCoreServiceClient("netTcp_2013"); // Gets the current user so we can impersonate them for our client string username = GetUserName(); client.Impersonate(username); if (String.Equals(tcm, "tcm:0") || String.Equals(tcm, "0")) { // If it's tcm:0, we're dealing with the root element in the CMS's tree. In that case, simply // do nothing to return an empty path, indicating to search through the entire tree. } else { var item = client.Read("tcm:" + tcm, new ReadOptions()); if (item is RepositoryLocalObjectData) { path = ((RepositoryLocalObjectData)item).LocationInfo.Path + "\\" + item.Title; } else if (item is PublicationData) { // If the selection is not the root element and not a RepositoryLocalObjectData, // then it's a publication. path = "\\" + ((PublicationData)item).Title; } else { // Do nothing - allow empty path to be return; handle any additional cases here, if they arise. } } // Explicitly abort to ensure there are no memory leaks. client.Abort(); } catch (Exception ex) { // Proper way of ensuring that the client gets closed. if (client != null) { client.Abort(); } // We are rethrowing the original exception and just letting webapi handle it. throw ex; } return(path); }
private SessionAwareCoreServiceClient GetClient() { SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2013"); client.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName()); //var userCredential = new NetworkCredential("SDL", "SDLPE"); // client.ClientCredentials.Windows.ClientCredential = userCredential; return(client); }
public static SessionAwareCoreServiceClient GetCoreService() { #if TRIDION2013 var result = new SessionAwareCoreServiceClient("netTcp_2013"); #else var result = new SessionAwareCoreServiceClient(); #endif result.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName()); return result; }
public Article(SessionAwareCoreServiceClient client, TcmUri location) : base(client) { ComponentData component = (ComponentData)Client.GetDefaultData(ItemType.Component, location); component.Schema = new LinkToSchemaData { IdRef = ContentManager.ResolveUrl(Constants.ArticleSchemaUrl) }; Content = component; }
public static SessionAwareCoreServiceClient GetCoreService() { #if TRIDION2013 var result = new SessionAwareCoreServiceClient("netTcp_2013"); #else var result = new SessionAwareCoreServiceClient(); #endif result.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName()); return(result); }
protected void OpenSession() { if (session == null || !(session.State == CommunicationState.Opened)) { NetTcpBinding binding = GetTcpBinding(); EndpointAddress address = new EndpointAddress(string.Format("net.tcp://localhost:2660/CoreService/2011/netTcp", Environment.MachineName)); session = new SessionAwareCoreServiceClient(binding, address); } session.Open(); }
/// <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()); }
private static WorkItemData[] GetUserWorkflowItems(SessionAwareCoreServiceClient client) { var userWorkItemsFilter = new UserWorkItemsFilterData() { ActivityState = ActivityState.Started | ActivityState.Assigned, }; var workItemDataList = new List <WorkItemData>(); client.GetSystemWideList(userWorkItemsFilter).ToList().ForEach(idObject => workItemDataList.Add(idObject as WorkItemData)); return(workItemDataList.ToArray()); }
// Upload entire file private void UploadWholeFile(HttpContext context, List<FilesStatus> statuses) { client = PowerTools.Common.CoreService.Client.GetCoreService(); _componentTitles = getAllComponentTitles(orgItemUri); for (int i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; file.SaveAs(StorageRoot + Path.GetFileName(file.FileName)); string fullName = Path.GetFileName(file.FileName); bool uploaded = UploadToTridion(StorageRoot + fullName); statuses.Add(new FilesStatus(fullName, file.ContentLength, uploaded)); } }
static void Main() { SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2013"); ContentManager cm = new ContentManager(client); List<Source> sources = cm.GetSources(); foreach (var source in sources) { List<Article> articles = cm.GetArticlesForSource(source); foreach (Article article in articles) { string id = article.Id.ToString().Replace("tcm:4", "tcm:5"); if(!client.IsPublished(id, "tcm:0-2-65537", true)) cm.Publish(new []{id}, "tcm:0-2-65537"); } } }
protected void Page_Load(object sender, EventArgs e) { _coreServiceEndpoint = new EndpointAddress(WebConfigurationManager.AppSettings["EndpointAddress"]); _vocabulariesAppId = WebConfigurationManager.AppSettings["VocabulariesAppId"]; _typeOfAppId = WebConfigurationManager.AppSettings["TypeOfAppId"]; _schemaPublicationUri = WebConfigurationManager.AppSettings["SchemaPublicationUri"]; if (!IsPostBack) { var client = new SessionAwareCoreServiceClient(_binding, _coreServiceEndpoint); client.Impersonate(HttpContext.Current.User.Identity.Name); // load vocabularies appdata ApplicationData appData = client.ReadApplicationData(null, _vocabulariesAppId); if (appData != null) { AppData.Text = Encoding.Unicode.GetString(appData.Data); } else { // load default xml AppData.Text = "<vocabularies>\n <vocabulary prefix=\"s\" name=\"http://schema.org\"/>\n</vocabularies>"; } // load schemas var filter = new RepositoryItemsFilterData { ItemTypes = new[] { ItemType.Schema }, Recursive = true }; var schemas = client.GetList(_schemaPublicationUri, filter); foreach (var schema in schemas) { SchemaList.Items.Add(new ListItem(schema.Title, schema.Id)); } // load appdata for first schema in the list appData = client.ReadApplicationData(schemas[0].Id, _typeOfAppId); if (appData != null) { TypeOf.Text = Encoding.Unicode.GetString(appData.Data); } Close(client); } }
protected void SchemaListChanged(object sender, EventArgs e) { var client = new SessionAwareCoreServiceClient(_binding, _coreServiceEndpoint); client.Impersonate(HttpContext.Current.User.Identity.Name); ApplicationData appData = client.ReadApplicationData(SchemaList.SelectedItem.Value, _typeOfAppId); if (appData != null) { TypeOf.Text = Encoding.Unicode.GetString(appData.Data); } else { // reset textbox TypeOf.Text = String.Empty; } Close(client); SchemaLabel.Text = SchemaList.SelectedItem.Value; }
public static SessionAwareCoreServiceClient GetConfiglessCoreService() { string userName = Tridion.Web.UI.Core.Utils.GetUserName(); var quotas = new System.Xml.XmlDictionaryReaderQuotas { MaxStringContentLength = 10485760, MaxArrayLength = 10485760, MaxBytesPerRead = 10485760 }; var httpBinding = new WSHttpBinding { MaxReceivedMessageSize = 10485760, ReaderQuotas = quotas, Security = { Mode = SecurityMode.Message, Transport = { ClientCredentialType = HttpClientCredentialType.Windows } } }; var result = new SessionAwareCoreServiceClient(); result.Impersonate(userName); return result; }
static void Main(string[] args) { SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2013"); ContentManager cm = new ContentManager(client); List<Source> sources = cm.GetSources(); foreach (Source source in sources) { List<Article> articles = cm.GetArticlesForSource(source); Console.WriteLine("Checking {0} articles for source {1}", articles.Count, source.Title); foreach (Article article in articles) { if(cm.IsArticleInPage(article)) continue; Console.WriteLine("Article {0} was not in any page... adding.", article.Title); string sg = cm.GetStructureGroup(source.Title, cm.ResolveUrl(Constants.RootStructureGroup)); string yearSg = cm.GetStructureGroup(article.Date.Year.ToString(CultureInfo.InvariantCulture), sg); cm.AddToPage(yearSg, article); } } }
public Source(ComponentData content, SessionAwareCoreServiceClient client) : base(content, client) { }
public static SessionAwareCoreServiceClient GetCoreService() { var result = new SessionAwareCoreServiceClient(); result.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName()); return result; }
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(); } } }
protected void UpdateVocabsClick(object sender, EventArgs e) { var client = new SessionAwareCoreServiceClient(_binding, _coreServiceEndpoint); client.Impersonate(HttpContext.Current.User.Identity.Name); var appData = new ApplicationData { ApplicationId = _vocabulariesAppId, Data = Encoding.Unicode.GetBytes(AppData.Text) }; client.SaveApplicationData(null, new[] { appData }); Close(client); VocabsLabel.Text = "saved..."; }
protected ContentItem(SessionAwareCoreServiceClient client) { Client = client; ReadOptions = new ReadOptions(); ContentManager = new ContentManager(Client); }
private SessionAwareCoreServiceClient GetClient() { //string coreServiceAddress = coreServiceAddress + "/webservices/CoreService2011.svc/wsHttp"; //only will work with 2011 Core Service WSHttpBinding binding = new WSHttpBinding(); binding.TransactionFlow = true; binding.ReaderQuotas.MaxStringContentLength = 65536; //8x default EndpointAddress address = new EndpointAddress(coreServiceAddress); //using (SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient(binding, address)) //"using" statement results in CommunicationObjectFaultedException when any Exception occurs within it SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient(binding, address); client.ClientCredentials.Windows.ClientCredential.UserName = username; client.ClientCredentials.Windows.ClientCredential.Password = password; return client; }
static void Main(string[] args) { const string titleOfSourceToRemove = "Meet John Song"; SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2013"); ContentManager cm = new ContentManager(client); List<Source> sources = cm.GetSources(); Source sourceToRemove = sources.FirstOrDefault(source => source.Title == titleOfSourceToRemove); if (sourceToRemove == null) { Console.WriteLine("Could not find source with name " + titleOfSourceToRemove); return; } // find all usages of the source // Delete all pages for the source // Unpublish all pages & Components // Delete List<Article> articles = cm.GetArticlesForSource(sourceToRemove); List<string> ids = new List<string>(); List<string> pageIds = new List<string>(); foreach (Article article in articles) { ids.Add(article.Id); string pageId = cm.GetPageIdForArticle(article); if (pageId != null) { pageIds.Add(pageId); } } // need pages cm.Unpublish(ids.ToArray(), "tcm:0-2-65537"); cm.Unpublish(pageIds.ToArray(), "tcm:0-2-65537"); Console.WriteLine("Wait for unpublish to finish..."); Console.Read(); // Must delete pages first foreach (string pageId in pageIds) { try { if(client.IsExistingObject(pageId)) client.Delete(pageId); } catch (Exception ex) { Console.WriteLine("Could not delete item with ID: " + pageId + ex.ToString()); } } foreach (string id in ids) { try { if(client.IsExistingObject(id)) client.Delete(id); } catch(Exception ex) { Console.WriteLine("Could not delete item with ID: " + id + ex.ToString());} } }
static void Main(string[] args) { SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2013"); const string primaryAccountName = "Chris Summers"; List<string> alternateNames = new List<string> { "[email protected] (chris)" }; ContentManager cm = new ContentManager(client); List<Person> persons = cm.GetPersons(); Person primary = null; foreach (Person p in persons) { if (p.Name == primaryAccountName) { primary = p; break; } } if (primary == null) { Console.WriteLine("Could not find primary account with name " + primaryAccountName); return; } List<Person> duplicates = new List<Person>(); foreach (string name in alternateNames) { foreach (Person p in persons) { if(p.Name == name) duplicates.Add(p); } } // 1. Add alternate names to primary account // 2. Move author of alternate content to primary account // 3. Republish content // 4. Delete alternate person accounts List<string> currentNames = primary.AlternateNames; bool changedAuthorName = false; foreach (string name in alternateNames) { if (!currentNames.Contains(name)) { currentNames.Add(name); changedAuthorName = true; } } if (changedAuthorName) { primary.AlternateNames = currentNames; primary.Save(true); } List<string> articles = new List<string>(); foreach (Person p in duplicates) { foreach (Article a in cm.GetArticlesForPerson(p)) { // BUG in a.Authors!! // It is not replacing the values, just adding. a.Authors = new List<Person>{primary}; a.Save(true); articles.Add(a.Id.GetVersionlessUri().ToString().Replace("tcm:4-", "tcm:5-")); } } cm.Publish(articles.ToArray(), Constants.TargetUri); foreach (Person p in duplicates) { try { client.Delete(p.Id); } catch (Exception ex) { Console.WriteLine("Could not delete component with id " + p.Id + ". Exception: " + ex); } } }
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; }
public Article(ComponentData component, SessionAwareCoreServiceClient client) : base(component, client) { }
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; }
protected void UpdateSchemaClick(object sender, EventArgs e) { var client = new SessionAwareCoreServiceClient(_binding, _coreServiceEndpoint); client.Impersonate(HttpContext.Current.User.Identity.Name); var appData = new ApplicationData { ApplicationId = _typeOfAppId, Data = Encoding.Unicode.GetBytes(TypeOf.Text) }; client.SaveApplicationData(SchemaList.SelectedItem.Value, new[] { appData }); Close(client); SchemaLabel.Text = SchemaList.SelectedItem.Value + " saved..."; }
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..."); } }
public Article(TcmUri contentItemUri, SessionAwareCoreServiceClient client) : base(contentItemUri, client) { }
public Source(SessionAwareCoreServiceClient client) : base(client) { Content = (ComponentData)Client.GetDefaultData(ItemType.Component, Constants.SourceLocationUrl, ReadOptions); Content.Schema = new LinkToSchemaData { IdRef = ContentManager.ResolveUrl(Constants.SourceSchemaUrl) }; }
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 Organization(ComponentData content, SessionAwareCoreServiceClient client) : base(content, client) { }
public ContentManager(SessionAwareCoreServiceClient client) { _client = client; _readOptions = new ReadOptions(); }