本文整理汇总了C#中Engine.GetSession方法的典型用法代码示例。如果您正苦于以下问题:C# Engine.GetSession方法的具体用法?C# Engine.GetSession怎么用?C# Engine.GetSession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Engine
的用法示例。
在下文中一共展示了Engine.GetSession方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Transform
public void Transform(Engine engine, Package package)
{
TemplatingLogger log = TemplatingLogger.GetLogger(GetType());
if (package.GetByName(Package.PageName) == null)
{
log.Info("Do not use this template building block in Component Templates");
return;
}
Page page = (Page)engine.GetObject(package.GetByName(Package.PageName));
string output;
if (page.Title.ToLower().Contains("index"))
output = StripNumbersFromTitle(page.OrganizationalItem.Title);
else
{
output = GetLinkToSgIndexPage((StructureGroup)page.OrganizationalItem, engine.GetSession()) + Separator + StripNumbersFromTitle(page.Title);
}
foreach (OrganizationalItem parent in page.OrganizationalItem.GetAncestors())
{
output = GetLinkToSgIndexPage((StructureGroup)parent, engine.GetSession()) + Separator + output;
}
package.PushItem("breadcrumb", package.CreateStringItem(ContentType.Html, output));
}
示例2: IsInPublishingQueue
/// <summary>
/// Check the Publishing queue and determine whether the given TcmUri is already present in the queue.
/// </summary>
/// <param name="engine">Engine object</param>
/// <param name="tcmUri">String representing the tcmuri of the item to check</param>
/// <param name="state">PublishTransactionState the publish state to filter on</param>
public static bool IsInPublishingQueue(Engine engine, String tcmUri, PublishTransactionState state)
{
Log.Debug(String.Format("Check Publishing queue for item '{0}'", tcmUri));
Session session = engine.GetSession();
PublishTransactionsFilter filter = new PublishTransactionsFilter(session);
filter.PublishTransactionState = state;
RepositoryLocalObject item = engine.GetObject(tcmUri) as RepositoryLocalObject;
if (item != null) filter.ForRepository = item.ContextRepository;
PublicationTarget publicationTarget = engine.PublishingContext.PublicationTarget;
if (publicationTarget != null)
{
filter.PublicationTarget = publicationTarget;
}
XmlElement element = PublishEngine.GetListPublishTransactions(filter);
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");
String xPath = String.Format("tcm:ListPublishTransactions/tcm:Item[@ItemID='{0}']", tcmUri);
XmlNodeList nodeList = element.SelectNodes(xPath, namespaceManager);
return nodeList.Count > 0;
}
示例3: Transform
public void Transform(Engine engine, Package package)
{
TemplatingLogger log = TemplatingLogger.GetLogger(GetType());
if (package.GetByName(Package.ComponentName) == null)
{
log.Info("This template should only be used with Component Templates. Could not find component in package, exiting");
return;
}
var c = (Component)engine.GetObject(package.GetByName(Package.ComponentName));
var container = (Folder)c.OrganizationalItem;
var filter = new OrganizationalItemItemsFilter(engine.GetSession()) { ItemTypes = new[] { ItemType.Component } };
// Always faster to use GetListItems if we only need limited elements
foreach (XmlNode node in container.GetListItems(filter))
{
string componentId = node.Attributes["ID"].Value;
string componentTitle = node.Attributes["Title"].Value;
}
// If we need more info, use GetItems instead
foreach (Component component in container.GetItems(filter))
{
// If your filter is messed up, GetItems will return objects that may
// not be a Component, in which case the code will blow up with an
// InvalidCastException. Be careful with filter.ItemTypes[]
Schema componentSchema = component.Schema;
SchemaPurpose purpose = componentSchema.Purpose;
XmlElement content = component.Content;
}
}
示例4: Transform
public void Transform(Engine engine, Package package)
{
_log = TemplatingLogger.GetLogger(GetType());
RepositoryLocalObject context =
engine.GetObject(package.GetByName(Package.PageName)) as RepositoryLocalObject;
if (context == null)
{
_log.Error("Could not retrieve page from package. Exiting.");
return;
}
string categoryUrl = context.ContextRepository.WebDavUrl + NavigationCategoryWebDavUrl;
Category navigation = (Category)engine.GetObject(categoryUrl);
using (MemoryStream ms = new MemoryStream())
{
XmlTextWriter w = new XmlTextWriter(ms, new UTF8Encoding(false))
{
Indentation = 4,
Formatting = Formatting.Indented
};
w.WriteStartDocument();
w.WriteStartElement(Navigation.RootNodeName);
KeywordsFilter filter = new KeywordsFilter(engine.GetSession()) { IsRoot = true };
foreach (XmlNode rootChildren in navigation.GetListKeywords(filter))
{
Keyword rootKeyword = (Keyword)engine.GetObject(rootChildren.Attributes["ID"].Value);
w.WriteStartElement(Navigation.NodeName);
NavigationNode n = new NavigationNode(rootKeyword);
}
}
}
示例5: GetPublishTransaction
/// <summary>
/// Get 'current' PublishTransaction. It tries to identify a PublishTransaction from the publish queue that is on the
/// given TcmUri, Publication, User, etc.
/// </summary>
/// <param name="engine">Engine object</param>
/// <param name="tcmUri">String representing the tcmuri of the item to check</param>
/// <returns>PublishTransaction if found; or null, otherwise</returns>
public static PublishTransaction GetPublishTransaction(Engine engine, String tcmUri)
{
String binaryPath = engine.PublishingContext.PublishInstruction.RenderInstruction.BinaryStoragePath;
Regex tcmRegex = new Regex(@"tcm_\d+-\d+-66560");
Match match = tcmRegex.Match(binaryPath);
if (match.Success)
{
String transactionId = match.Value.Replace('_', ':');
TcmUri transactionUri = new TcmUri(transactionId);
return new PublishTransaction(transactionUri, engine.GetSession());
}
return FindPublishTransaction(engine, tcmUri);
}
示例6: Transform
public void Transform(Engine engine, Package package)
{
//Fetch output package variable
string output = package.GetValue(Package.OutputName);
//Perform regex match on output
Regex regex = new Regex("tcm:\\d+\\-\\d+(?:\\-\\d+)?");
foreach (Match match in regex.Matches(output))
{
//Find title of item
string tcmuri = match.Value;
string title = engine.GetSession().GetObject(tcmuri).Title;
//Replace tcmuri with title in output
output = output.Replace(tcmuri, title);
}
//Update output package variable
package.GetByName(Package.OutputName).SetAsString(output);
}
示例7: Transform
public void Transform(Engine engine, Package package)
{
Page page = (Page)engine.GetObject(package.GetByName(Package.PageName));
TcmUri articleSchemaUri = new TcmUri(Constants.SchemaArticleId, ItemType.Schema, page.Id.PublicationId);
UsingItemsFilter filter = new UsingItemsFilter(engine.GetSession()) { ItemTypes = new[] { ItemType.Component } };
Schema schema = (Schema)engine.GetObject(articleSchemaUri);
TagCloud tagCloud = new TagCloud
{
Tags = new List<Tag>(),
PublicationId = page.Id.PublicationId,
TcmId = page.Id.ItemId,
PageTitle = page.Title
};
SortedList<string, int> tags = new SortedList<string, int>(StringComparer.CurrentCultureIgnoreCase);
foreach (Component c in schema.GetUsingItems(filter))
{
Article a = new Article(c, engine);
string tag = a.Author.Name;
if (tags.ContainsKey(tag))
{
tags[tag] = tags[tag] + 1;
}
else
{
tags.Add(tag, 1);
}
}
foreach (var tag in tags)
{
tagCloud.Tags.Add(new Tag { TagName = tag.Key.ToAscii(), TagValue = tag.Value });
}
string content = JsonConvert.SerializeObject(tagCloud);
//content += tagCloud.ToBsonDocument().ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict });
package.PushItem(Package.OutputName, package.CreateStringItem(ContentType.Text, content));
}
示例8: Transform
public void Transform(Engine engine, Package package)
{
// store Excel sheet on filesystem
TcmUri compUri = new TcmUri(package.GetValue("Component.ID"));
Component comp = (Component)engine.GetSession().GetObject(compUri);
Binary binary = engine.PublishingContext.RenderedItem.AddBinary(comp);
_logger.Info(binary.FilePath);
String strTmpFileName = String.Format("{0}{1}.xls", TEMP_FILE_LOCATION, comp.Title.Replace(":", "_"));
String result = String.Empty;
try
{
bool storeFile = ByteArrayToFile(strTmpFileName, comp.BinaryContent.GetByteArray());
_logger.Debug(String.Format("Storing file {0}, result = {1}", strTmpFileName, storeFile));
// TODO: make sheet name a parameter (template parameter, component metadata?)
result = ProcessSheet(strTmpFileName, "Sheet1");
}
catch (Exception ex)
{
_logger.Error(ex.Message);
}
finally
{
// delete file
File.Delete(strTmpFileName);
_logger.Info(String.Format("File {0} deleted successfully", strTmpFileName));
}
Item output = package.CreateStringItem(ContentType.Text, result);
package.PushItem(Package.OutputName, output);
}
示例9: Transform
public void Transform(Engine engine, Package package)
{
_log.Debug("GetAllComponentTemplates: start Transform");
Stopwatch watch = new Stopwatch();
watch.Start();
Session session = engine.GetSession();
ICache cache = session.Cache;
String componentTemplateName = String.Empty;
if (package.GetValue("ComponentTemplateName") != null)
{
componentTemplateName = package.GetValue("ComponentTemplateName");
}
if (!(String.IsNullOrEmpty(componentTemplateName)) && (package.GetByName(componentTemplateName) != null))
{
// Component Template found in Package
return;
}
RepositoryLocalObject context;
if (package.GetByName(Package.ComponentName) != null)
context = engine.GetObject(package.GetByName(Package.ComponentName)) as RepositoryLocalObject;
else
context = engine.GetObject(package.GetByName(Package.PageName)) as RepositoryLocalObject;
if (context != null)
{
Repository contextPublication = context.ContextRepository;
RepositoryItemsFilter filter = new RepositoryItemsFilter(session)
{
ItemTypes = new[] { ItemType.ComponentTemplate },
Recursive = true,
BaseColumns = ListBaseColumns.IdAndTitle
};
XmlNamespaceManager nm = new XmlNamespaceManager(new NameTable());
nm.AddNamespace(Constants.TcmPrefix, Constants.TcmNamespace);
XmlNodeList allComponentTemplates;
if (cache.Get("ComponentTemplate", "listcts") != null)
{
allComponentTemplates = (XmlNodeList)cache.Get("ComponentTemplate", "listcts");
_log.Debug("GetAllComponentTemplates: list already in cache");
}
else
{
allComponentTemplates = contextPublication.GetListItems(filter).SelectNodes("/tcm:ListItems/tcm:Item", nm);
cache.Add("ComponentTemplate", "listcts", allComponentTemplates);
_log.Debug("GetAllComponentTemplates: list created in cache");
}
if (allComponentTemplates != null)
foreach (XmlNode ct in allComponentTemplates)
{
if (ct.Attributes != null)
{
String ctName = ct.Attributes["Title"].Value.Replace(" ", "").Replace("-", "");
// Avoid duplicates in Package
// Possible performance impact, but could be needed if ComponentTemplateName is set to an empty String
if (package.GetByName(ctName) == null)
package.PushItem(ctName, package.CreateStringItem(ContentType.Text, ct.Attributes["ID"].Value));
}
}
}
watch.Stop();
_log.Debug("Template finished in " + watch.ElapsedMilliseconds + " milliseconds.");
}
示例10: FindPublishTransaction
/// <summary>
/// Get 'current' PublishTransaction. It tries to identify a PublishTransaction from the publish queue that is on the
/// given TcmUri, Publication, User, etc.
/// </summary>
/// <param name="engine">Engine object</param>
/// <param name="tcmUri">String representing the tcmuri of the item to check</param>
/// <returns>PublishTransaction if found; or null, otherwise</returns>
private static PublishTransaction FindPublishTransaction(Engine engine, String tcmUri)
{
Log.Debug(String.Format("Find PublishTransaction for item '{0}'", tcmUri));
PublishTransaction result = null;
Session session = engine.GetSession();
PublishTransactionsFilter filter = new PublishTransactionsFilter(session);
filter.PublishTransactionState = PublishTransactionState.Resolving;
RepositoryLocalObject item = engine.GetObject(tcmUri) as RepositoryLocalObject;
if (item != null) filter.ForRepository = item.ContextRepository;
PublicationTarget publicationTarget = engine.PublishingContext.PublicationTarget;
if (publicationTarget != null)
{
filter.PublicationTarget = publicationTarget;
}
XmlElement element = PublishEngine.GetListPublishTransactions(filter);
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");
String xPath = String.Format("tcm:ListPublishTransactions/tcm:Item[@ItemID='{0}']", tcmUri);
XmlNodeList nodeList = element.SelectNodes(xPath, namespaceManager);
String transactionId;
if (nodeList != null && nodeList.Count == 1)
{
transactionId = nodeList[0].Attributes["ID"].Value;
TcmUri transactionUri = new TcmUri(transactionId);
result = new PublishTransaction(transactionUri, session);
}
else
{
foreach (XmlNode node in element.ChildNodes)
{
transactionId = node.Attributes["ID"].Value;
TcmUri transactionUri = new TcmUri(transactionId);
result = new PublishTransaction(transactionUri, session);
if (IsPublishTransactionForTcmUri(result, tcmUri))
{
break;
}
result = null;
}
}
Log.Debug("Returning PublishTransaction " + result);
return result;
}
示例11: Transform
/// <summary>
/// ITemplate.Transform implementation
/// </summary>
/// <param name="engine">The engine can be used to retrieve additional information or execute additional actions</param>
/// <param name="package">The package provides the primary data for the template, and acts as the output</param>
public void Transform(Engine engine, Package package)
{
_engine = engine;
_package = package;
_publicationId = GetPublicationId();
// determine (optional) structure group parameter
Item targetStructureGroupItem = _package.GetByName(ParameterNameTargetStructureGroup);
if (targetStructureGroupItem != null)
{
if (!TcmUri.IsValid(targetStructureGroupItem.GetAsString()))
{
throw new InvalidDataException(string.Format("Target location {0} is not a structure group", targetStructureGroupItem));
}
TcmUri uri = new TcmUri(targetStructureGroupItem.GetAsString());
// get target structure group in context publication
_targetStructureGroup = (StructureGroup)_engine.GetSession().GetObject(new TcmUri(uri.ItemId, uri.ItemType, _publicationId));
Log.Debug(string.Format("Target Structure Group {0} found", _targetStructureGroup.Id));
}
// make sure eclSession is disposed at the end
using (IEclSession eclSession = SessionFactory.CreateEclSession(engine.GetSession()))
{
// loop over all ecl items and store them in a dictionary
_eclItemsInPackage = new Dictionary<TcmUri, EclItemInPackage>();
foreach (Item item in _package.GetAllByType(new ContentType(EclContentType)))
{
if (item.Properties.ContainsKey(Item.ItemPropertyTcmUri) && item.Properties.ContainsKey(Item.ItemPropertyFileName))
{
// has the item already been published?
if (!item.Properties.ContainsKey(Item.ItemPropertyPublishedPath))
{
// find ecl items
string uri;
if (item.Properties.TryGetValue(Item.ItemPropertyTcmUri, out uri))
{
TcmUri stubUri = new TcmUri(uri);
IEclUri eclUri = eclSession.TryGetEclUriFromTcmUri(stubUri);
if (eclUri != null)
{
// we have a valid ecl item, lets store it in the dictionary
IContentLibraryMultimediaItem eclItem = (IContentLibraryMultimediaItem)eclSession.GetContentLibrary(eclUri).GetItem(eclUri);
EclItemInPackage eclItemInPackage = new EclItemInPackage(item, eclItem);
_eclItemsInPackage.Add(stubUri, eclItemInPackage);
}
}
}
else
{
// items have been published, we are probabaly called too late...
Log.Warning("{0} has already been published, \"Resolve ECL items\" should be added before \"Publish Binaries in Package\"");
}
}
}
// end processing if there are no ecl items found in the package
if (_eclItemsInPackage.Count == 0) return;
// determine item name to operate on from a parameter or use default
string itemName = _package.GetValue(ParameterNameItemName);
if (string.IsNullOrEmpty(itemName))
{
itemName = Package.OutputName;
}
Item selectedItem = _package.GetByName(itemName);
// continue on the output by matching the found ecl items in there against the list of ecl items in the package
if ((selectedItem.Type == PackageItemType.String) || (selectedItem.Type == PackageItemType.Stream))
{
// Assume text content
string inputToConvert = selectedItem.GetAsString();
string convertedOutput = ResolveEclLinks(eclSession, inputToConvert);
if (convertedOutput != null)
{
Log.Debug("Changed Output item");
selectedItem.SetAsString(convertedOutput);
}
}
else
{
// XML
XmlDocument outputDocument = selectedItem.GetAsXmlDocument();
ResolveEclLinks(eclSession, outputDocument);
selectedItem.SetAsXmlDocument(outputDocument);
}
}
}
示例12: FindOrCreateSG
private StructureGroup FindOrCreateSG(Engine engine, string sgWebDav) {
log.Debug(string.Format("Find or Create SG '{0}'", sgWebDav));
StructureGroup sg = engine.GetObject(sgWebDav) as StructureGroup;
if (sg == null) {
int lastSlash = sgWebDav.LastIndexOf("/");
string parentSGWebDav = sgWebDav.Substring(0, lastSlash);
StructureGroup parentSG = FindOrCreateSG(engine, parentSGWebDav);
Session newSession = new Session(engine.GetSession().User.Title);
sg = new StructureGroup(newSession, parentSG.Id);
string title = sgWebDav.Substring(lastSlash + 1);
sg.Title = MakeSafeSGTitle(title);
sg.Directory = MakeSafeDirectory(title);
sg.Save();
newSession.Dispose();
log.Debug(string.Format("Created SG '{0}'", sgWebDav));
} else {
log.Debug(string.Format("Found SG '{0}'", sgWebDav));
}
return sg;
}
示例13: FieldOutputHandler
/// <summary>
/// Initializes a new instance of the <see>
/// <cref>TridionOutputHandler</cref>
/// </see>
/// class.
/// </summary>
/// <param name="tcmUri">The TCM URI.</param>
/// <param name="engine">The engine.</param>
/// <param name="package">The package.</param>
public FieldOutputHandler(TcmUri tcmUri, Engine engine, Package package)
{
if (!TcmUri.IsValid(tcmUri.ToString()))
{
Log.Error(tcmUri + " is not a valid URI. Failed to initialize Output Handler!");
}
else
{
switch (tcmUri.ItemType)
{
case ItemType.Component:
try
{
_component = new Component(tcmUri, engine.GetSession());
_currentItem = _component;
if (_component.ComponentType == ComponentType.Normal)
{
_contentFields = new ItemFields(_component.Content, _component.Schema);
}
if (_component.Metadata != null)
_metadataFields = new ItemFields(_component.Metadata, _component.Schema);
}
catch (Exception ex)
{
Log.Error("Unable to iniatilize fields for component with ID " + tcmUri + "\r\n Exception: " + ex);
}
break;
case ItemType.Page:
try
{
_page = new Page(tcmUri, engine.GetSession());
_currentItem = _page;
if (_page.Metadata != null)
{
_metadataFields = new ItemFields(_page.Metadata, _page.MetadataSchema);
}
else
{
Log.Error("Only pages with metadata are allowed.");
}
}
catch (Exception ex)
{
Log.Error("Unable to initialize fields for page with ID " + tcmUri + "\r\n Exception: " + ex);
}
break;
case ItemType.Publication:
try
{
_publication = new Publication(tcmUri, engine.GetSession());
_currentItem = null;
if (_publication.Metadata != null)
{
_metadataFields = new ItemFields(_publication.Metadata, _publication.MetadataSchema);
}
else
{
Log.Error("Only Publications with Metadata are supported!");
}
}
catch (Exception ex)
{
Log.Error("Unable to initialize fields for publication with ID " + tcmUri + "\r\n Exception: " + ex);
}
break;
case ItemType.StructureGroup:
try
{
_structureGroup = new StructureGroup(tcmUri, engine.GetSession());
_currentItem = _structureGroup;
if (_structureGroup.Metadata != null)
{
_metadataFields = new ItemFields(_structureGroup.Metadata, _structureGroup.MetadataSchema);
}
else
{
Log.Error("Only Structure Groups with Metadata are supported!");
}
}
catch (Exception ex)
{
Log.Error("Unable to initialize fields for Structure Group with ID " + tcmUri + "\r\n Exception: " + ex);
}
break;
case ItemType.Folder:
try
{
_folder = new Folder(tcmUri, engine.GetSession());
_currentItem = _folder;
if (_folder.Metadata != null)
//.........这里部分代码省略.........