Example #1
0
        /// <summary>
        /// Impersonate the TridionClient configured identity
        /// </summary>
        /// <param name="identity">Tridion user identity.</param>
        public void Impersonate(String identity)
        {
            if (String.IsNullOrEmpty(identity))
            {
                throw new ArgumentException("identity");
            }

            mClient.Impersonate(identity);
        }
Example #2
0
        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);
            }
        }
Example #3
0
        public static SessionAwareCoreServiceClient GetCoreService()
        {
            var result = new SessionAwareCoreServiceClient();

            result.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName());
            return(result);
        }
Example #4
0
        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());
            }
        }
Example #5
0
        public static SessionAwareCoreServiceClient GetCoreService()
        {
            var client = new SessionAwareCoreServiceClient("netTcp_2013");

            client.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName());
            return(client);
        }
        /// <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;
        }
Example #7
0
        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);
        }
Example #8
0
        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);
        }
Example #9
0
        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);
        }
Example #10
0
        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 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;
		}
Example #12
0
        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...";
        }
Example #13
0
        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...";
        }
Example #14
0
        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 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);
            }
        }
Example #16
0
        private static SessionAwareCoreServiceClient CreateCoreService(string endpointName)
        {
            using (Tracer.GetTracer().StartTrace(endpointName))
            {
                SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient(endpointName);
                var clientCredentials = client.ClientCredentials as ClaimsClientCredentials;

                if (clientCredentials != null)
                {
                    SetClaimsCredential(clientCredentials, client.Endpoint.Address.Uri);
                }
                else
                {
                    // Default ClientCredentials. Use the current Windows Identity as client credentials and specify the user name in a Core Service Impersonate call.
                    client.Impersonate(UserName);
                }

                return(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;
        }
Example #18
0
        private void SetAppDataAddress(string id, string address)
        {
            // Create a new, null Core Service Client
            SessionAwareCoreServiceClient client = null;

            // TODO: Update to pass internal part of below snippet as a function (to reuse try-catch pattern)

            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);

                Byte[]          byteData = Encoding.Unicode.GetBytes(address);
                ApplicationData appData  = new ApplicationData
                {
                    ApplicationId = id,
                    Data          = byteData
                };

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

                // Explicitly abort to ensure there are no memory leaks.
                client.Abort();
            }
            catch (Exception ex)
            {
                // Proper way of ensuring that the client gets closed... we close it in our try block above,
                // then in a catch block if an exception is thrown we abort it.
                if (client != null)
                {
                    client.Abort();
                }

                // We are rethrowing the original exception and just letting webapi handle it.
                throw ex;
            }
        }
Example #19
0
        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;
        }
Example #20
0
        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;
        }
Example #21
0
        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);
        }
Example #22
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);
        }
        /// <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;
        }
        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;
        }
Example #25
0
 protected void OpenSession(string userName)
 {
     session.Open();
     session.Impersonate(userName);
 }
Example #26
0
 public static SessionAwareCoreServiceClient GetCoreService()
 {
     var client = new SessionAwareCoreServiceClient("netTcp_2013");
     client.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName());
     return client;
 }
        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...";
        }
Example #28
0
        public string GetLatestItems(LatestItemsRequest request)
        {
            // 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);

                // Start building up a string of html to return, including headings for the table that the html will represent.
                string html = "<div class=\"usingItems results\" id=\"latestItemsList\">";
                html += CreateItemsHeading();

                var filter = new SearchQueryData();

                // TODO: Add check for valid start and end times:

                if (String.IsNullOrEmpty(request.startTime))
                {
                    filter.ModifiedAfter = DateTime.Now.AddDays(-1);
                }
                else
                {
                    filter.ModifiedAfter = Convert.ToDateTime(request.startTime);
                }

                if (String.IsNullOrEmpty(request.endTime))
                {
                    filter.ModifiedBefore = DateTime.Now;
                }
                else
                {
                    filter.ModifiedBefore = Convert.ToDateTime(request.endTime);
                }

                filter.IncludeLocationInfoColumns = true;

                if (!string.IsNullOrEmpty(request.pathOfContainer) && !request.pathOfContainer.Equals("(All)"))
                {
                    // Assume publication field is valid publication name
                    // TODO: Validate here
                    string containerId = client.GetTcmUri(ConvertPathToWebdav(request.pathOfContainer), null, null);
                    //string pubTcm = client.GetTcmUri("/webdav/" + request.publication, null, null);
                    filter.SearchIn = new LinkToIdentifiableObjectData {
                        IdRef = containerId
                    };
                }

                if (!string.IsNullOrEmpty(request.user) && !request.user.Equals("(All)"))
                {
                    // TODO: Find a more efficient way of doing this than simply looking at all users.

                    var users = client.GetSystemWideList(new UsersFilterData {
                        BaseColumns = ListBaseColumns.IdAndTitle, IsPredefined = false
                    });

                    string userId = string.Empty;

                    foreach (var ud in users)
                    {
                        if (ud.Title == request.user)
                        {
                            userId = ud.Id;
                        }
                    }

                    // If userId is not found, allow an empty string to be passed, which will trigger and error message.
                    filter.Author = new LinkToUserData()
                    {
                        IdRef = userId
                    };
                }

                filter.ItemTypes = new[] { ItemType.Schema,
                                           ItemType.Component,
                                           ItemType.TemplateBuildingBlock,
                                           ItemType.ComponentTemplate,
                                           ItemType.PageTemplate,
                                           ItemType.Category,
                                           ItemType.Folder,
                                           ItemType.Keyword,
                                           ItemType.Page,
                                           ItemType.StructureGroup,
                                           ItemType.VirtualFolder,
                                           ItemType.Publication };

                filter.BlueprintStatus = SearchBlueprintStatus.Local;

                var searchResults = client.GetSearchResults(filter);

                filter.BlueprintStatus = SearchBlueprintStatus.Localized;

                var searchResults2 = client.GetSearchResults(filter);

                // Merge the two searchResults arrays (local and localized; union goes into searchResults):
                int array1OriginalLength = searchResults.Length;
                Array.Resize <IdentifiableObjectData>(ref searchResults, array1OriginalLength + searchResults2.Length);
                Array.Copy(searchResults2, 0, searchResults, array1OriginalLength, searchResults2.Length);

                int row = 0;

                foreach (IdentifiableObjectData item in searchResults)
                {
                    row++;

                    string path = "";
                    if (item is RepositoryLocalObjectData)
                    {
                        path = ((RepositoryLocalObjectData)item).LocationInfo.Path;
                    }

                    bool outputItem = true;

                    // If user is not empty or set to (All), then run some logic to see if items match selected user within specified time range.
                    // This is necessary to account for scenarios where one user creates an item, but another edits it at a later time, for instance.
                    // If no specific user is specified, DO NOT run these checks as they are expensive and not necessary in that case!
                    // Only perform this check for Versioned Items (i.e. not folders, etc.).
                    ////if (!string.IsNullOrEmpty(request.user) && !request.user.Equals("(All)") && (item is VersionedItemData))
                    ////{
                    ////    // Set flag to false by default and set back to true if we find a match.
                    ////    outputItem = false;

                    ////    VersionsFilterData versionsFilter = new VersionsFilterData();
                    ////    versionsFilter.IncludeRevisorDescriptionColumn = true;
                    ////    IdentifiableObjectData[] versionList = client.GetList(item.Id, versionsFilter);

                    ////    foreach (IdentifiableObjectData objectData in versionList)
                    ////    {
                    ////        var versionInfo = (FullVersionInfo)objectData.VersionInfo;

                    ////        // Check 2 things:
                    ////        // 1) that versionInfo.Revisor.Title == request.user
                    ////        // 2) that versionInfo.RevisionDate.Value is between filter.ModifiedAfter and filter2.ModifiedBefore
                    ////        // If we find a match, set outputItem to true and break the foreach loop.

                    ////        if (versionInfo.Revisor.Title == request.user)
                    ////        {
                    ////            if ((objectData.VersionInfo.RevisionDate >= filter.ModifiedAfter) && (objectData.VersionInfo.RevisionDate <= filter.ModifiedBefore))
                    ////            {
                    ////                outputItem = true;
                    ////                break;
                    ////            }
                    ////        }
                    ////    }
                    ////}

                    if (outputItem)
                    {
                        string currItemHtml = "<div class=\"item\">";

                        // Some JS magic is needed here to retrieve the icon and add it to the url by string replacement.
                        // We need to do this in JS because the core service provides no access to an item's icon.
                        currItemHtml += "<script>var icon = $models.getItem(\"" + item.Id + "\").getInfo().Icon;</script>";
                        currItemHtml += "<div id=\"tempIconId" + row + "\" class=\"icon\" style=\"background-image: url(/WebUI/Editors/CME/Themes/Carbon2/icon_v7.1.0.66.627_.png?name=" + "****" + "&size=16)\">" + "" + "</div>";
                        currItemHtml += "<script>document.getElementById('tempIconId" + row + "').outerHTML = document.getElementById('tempIconId" + row + "').outerHTML.replace(\"****\", icon);</script>";

                        currItemHtml += "<div class=\"name\">" + item.Title + "</div>";
                        currItemHtml += "<div class=\"path\">" + path + "</div>";
                        currItemHtml += "<div class=\"id\">" + item.Id + "</div>";
                        currItemHtml += "</div>";

                        html += currItemHtml;
                    }
                }

                // Close the div we opened above
                html += "</div>";

                // Explicitly abort to ensure there are no memory leaks.
                client.Abort();

                // Return the html we've built.
                return(html);
            }
            catch (Exception ex)
            {
                // Proper way of ensuring that the client gets closed... we close it in our try block above,
                // then in a catch block if an exception is thrown we abort it.
                if (client != null)
                {
                    client.Abort();
                }

                // We are rethrowing the original exception and just letting webapi handle it.
                throw ex;
            }
        }
Example #29
0
 public CoreServiceClent()
 {
     _client = new SessionAwareCoreServiceClient("wsHttp");
     _client.Impersonate(WindowsIdentity.GetCurrent().Name);
 }
Example #30
0
 public static SessionAwareCoreServiceClient GetCoreService()
 {
     var result = new SessionAwareCoreServiceClient();
     result.Impersonate(Tridion.Web.UI.Core.Utils.GetUserName());
     return result;
 }
        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...";
        }