Tridion and REL: Updating page filename within the page's PublishedUrl property - tridion

We have a requirement where the url of a page needs to be localizable/translated. Our existing mechanism relies on the actual published url to retrieve the page via oData. To clarify with a simplified example: we have some logic in the front end that takes the request url (which doesn't have a file extension, appends a .html extension, e.g.:
/my-awesome-path/my-awesome-page
now becomes
/my-awesome-path/my-awesome-page.html
the logic then pulls the page from oData using the query
/odata.svc/Pages?$filter=url eq '/my-awesome-path/my-awesome-page.html'
There is much more logic that we have around this to parse this SEO-friendly url and get MVC controller function parameters and other whatnots, but that's not relevant here.
Our requirement is that we cannot localize the page to give it a translated url since this would mean the entire page can't be managed in the parent web publication.
To get the localized path leading up to the page filename we simply localize the SGs. The difficulty is with the page filename. On the page's metadata we have a linked "localizable metadata" component with a field for providing a localized page filename.
What we'd like to do is update the page's URL property during the publishing/deployment process to update the page's published url with the localized page filename from this linked metadata component (assume that we have access to the localized filename field's value at any stage between start of publishing to commitment of deployment).
I've tried doing this via a custom resolver, however, at this level it appears that the page.PublishedUrl property is already established by the CM and cannot be overridden. So updating the page.FileName property doesn't do anything useful.
I've also tried directly updating the URL column in the PAGE table in Broker DB to a different name and it appears that everything continues to work, including dynamic linking and unpublishing of the page. Obviously writing a storage extension or a deployer extension to directly update the DB via jdbc is unacceptable.
Here are the options I'm thinking of:
1) try a deployer extension and use the Tridion API to update the url property
2) try writing a custom renderer that executes the url replace logic without actually updating the url in the broker. I don't favour this since request-time processing is required each time.
My question is: what is the most appropriate way to update the page url property? Will writing a custom deployer using Tridion APIs to update the URL property lead me to a dead end just like the Resolver did?

Following the points in Nuno's comment above I decided against using a custom deployer and have solved the problem using 2 event subscriptions of the Event System. On page publish I first localize the page, grab the localized filename from the localized linked metadata component and save the page. Then in a subsequent event I simply unlocalize the page. Here is my working code:
[TcmExtension("Publish or Unpublish Events")]
public class PublishOrUnpublishEvents : TcmExtension
{
public PublishOrUnpublishEvents()
{
EventSystem.Subscribe<Page, PublishEventArgs>(SetLocalizedPageFileName, EventPhases.Initiated);
EventSystem.Subscribe<Page, SetPublishStateEventArgs>(UnlocalizePageOncePublished, EventPhases.Initiated);
}
public void SetLocalizedPageFileName(Page page, PublishEventArgs args, EventPhases phase)
{
string localFilename = GetLocalilizedFileNameFromPageMetadata(page);
if (!string.IsNullOrEmpty(localFilename))
{
page.Localize();
if (page.TryCheckOut())
{
page.FileName = localFilename;
page.Save(true);
}
}
}
public void UnlocalizePageOncePublished(Page page, SetPublishStateEventArgs args, EventPhases phase)
{
string localFilename = GetLocalilizedFileNameFromPageMetadata(page);
if (!string.IsNullOrEmpty(localFilename))
page.UnLocalize();
}
private string GetLocalilizedFileNameFromPageMetadata(Page page)
{
string localFilename = string.Empty;
if (page.Metadata != null)
{
ItemFields fields = new ItemFields(page.Metadata, page.MetadataSchema);
if (fields.Contains("LocalizableMeta"))
{
ComponentLinkField localMetaField = fields["LocalizableMeta"] as ComponentLinkField;
Component component = localMetaField.Value;
ItemFields compFields = new ItemFields(component.Content, component.Schema);
if (compFields.Contains("LocalizedPageFilename"))
{
SingleLineTextField fileNameTextField = compFields["LocalizedPageFilename"] as SingleLineTextField;
localFilename = fileNameTextField.Value;
}
}
}
return localFilename;
}
}

Perhaps another option:
Store the localised URL has an additional metadata field for the page, keeping the same physical URL for the published pages.
I see your requirement is to avoid localisation of child pages, I like the way it's possible in wordpress to enter globally how URLs work, for example:
/mysite/%postname%/
It would be cool to build something similar to this within SDL Tridion, where the content title could be extracted and used at the content URL.
Either way, if you'd have to write a system that takes the 'Friendly URL' and does a look up for the actual URL, which I think would be pretty simple.

Related

How to create dynamic assets in Meteor

I thought this would be easy.
I want to create simple files the user can download by clicking a link.
Write what you want into the servers assets/app folder and then generate a simple link
Download> me!
Writing files into Meteor's server side asset folder is easy. And the download link above will always download a file with the name you specified.
You will get a yourNewFile.txt in the client's download folder. But, unfortunately its content will not be what you wrote on the server (new.txt).
Meteor has the strange behavior of downloading its startup html page as the content if the name of your content wasn't originally in the public folder. I think this is bug .... put the above anchor into a default Meteor project and click the link .. don't even create a public folder. You get a downloaded file with the name you asked for...
So, if you put stubs in the public folder (you know the names of the assets you are going to create) then you can create them dynamically.
I don't know the names before hand. Is there any way to get Meteor to 'update' its assets list with the new names I want to use?
I know there are packages that can do this. I'd like to just do it myself as above, really shouldn't be this hard.
The public/ folder intended use is specifically for static assets. Its content is served by the node http server.
If you want to dynamically generate assets on the server, you can rely on iron:router server side routes.
Here is a simple example :
lib/router.js
Router.route("/dynamic-asset/:filename",function(){
var filename = this.params.filename;
this.response.setHeader("Content-Disposition",
"attachment; filename=" + filename);
this.response.end("Hello World !");
},{
name: "dynamic-asset",
where: "server"
});
In server-side route controllers, you get access to this.response which is a standard node HTTP response instance to respond to the client with the correct server generated content. You can query your Mongo collections using the eventual parameters in the URL for example.
client/views/download/download.html
<template name="download">
{{#linkTo route="dynamic-asset" target="_blank" download=""}}
Download {{filename}}
{{/linkTo}}
</template>
client/views/parent/parent.html
<template name="parent">
{{> download filename="new.txt"}}
</template>
The linkTo block helper must be called in a context where the route parameters are accessible as template helpers. It will generate an anchor tag having an href set to Router.path(route, dataContext). It means that if our server-side route URL is /dynamic-asset/:filename, having a data context where filename is accessible and set to "new.txt" will generate this URL : /dynamic-asset/new.txt.
In this example we set the current data context of the download template to {filename: "new.txt"} thanks to the template invocation syntax.
Note that target="_blank" is necessary to avoid being redirected to the dynamic asset URL inside the current tab, and the download HTML attribute must be set to avoid considering the link as something the browser should open inside a new tab. The download attribute value is irrelevant as it's value will be overriden server-side.
Here is the raw Picker (meteorhacks:picker) route and method I used to get this running. I've kept it lean and its just what I got working and probably not the best way to do this ... the synchronous methods (like readFileSync) throw exceptions if things are not right, so they should be wrapped in try-catch blocks and the mkdirp is a npm package loaded through meteorhacks:npm package hence the Meteor.npmRequire. Thanks again to saimeunt for the directions.
Picker.route('/dynamic-asset/:filename', function(params, req, res, next) {
console.log('/dynamic-asset route!');
var fs = Npm.require('fs');
var path = Npm.require('path');
var theDir = path.resolve('./dynamic-asset');
var filename = params.filename;
var fileContent = fs.readFileSync(theDir + '/' + filename, {encoding:'utf8'});
res.end(fileContent);
});
The Meteor method that creates the file is
writeFile: function(fname, content) {
console.log('writeFile', fname);
var fs = Npm.require('fs');
var path = Npm.require('path');
var mkdirp = Meteor.npmRequire('mkdirp');
// verify/make directory
var theDir = path.resolve('./dynamic-asset');
mkdirp(theDir);
fs.writeFileSync(theDir + '/' + fname, content);
return 'aok';
}
and the hyper link I generate on the client if the file gets created looks like this:
Download lane file now
I incorrectly stated in my original question at the top that you could use stubs and write files into the assets folder. Its not so .. you will only get back the stub ... sorry.

How to get the itemxml of a selected item in Tridion

I would like to get and display the itemxml of the selected item from the Tridion CME.
I was able to get the Itemxml from my VM server when i give the tcm id in the browser.
However, i would like to get the same information from Tridion GUI Extension.
I am able to get the selected item tcm id. Is there any way to get the itemxml using coreservice?
or is there any other way to get this?
At the moment there's no way you can get Item XML through core service. Item XML you have seen was provided to you by TCM Protocol handler that might not be there in future versions. If you want to show item XML in CME - take a look at this extention by Yoaw:
http://sdltridionworld.com/articles/sdltridion2011/tutorials/GUIextensionIn8steps.aspx
Also, keep in mind that not all properties of an item might be exposed in Xml, sometimes you have more info in Data object
Take a look at the PowerTools, it has an ItemXML viewer (written by Robert Curlette) for all items in SDL Tridion
http://code.google.com/p/tridion-2011-power-tools/wiki/ItemXML
The XML is loaded on a tab using JavaScript as follows:
ItemXmlTab.ItemXmlTab.prototype.updateView = function ItemXmlTab$updateView()
{
if (this.isSelected())
{
var xslPath = $ptUtils.expandPath("/PowerTools/Client/ItemXml/ItemXmlTab.xslt", true);
$xml.loadXsltProcessor(xslPath, function (value)
{
var xmlSource = $display.getItem().getXml();
// Filter out all spacing characters
xmlSource = xmlSource.replace(/\t|\n|\r/g, "");
var html = $xml.xsltTransform(value, $xml.getNewXmlDocument(xmlSource), null);
$dom.setOuterHTML($("#itemXml"), html);
});
}
};
You can view the source code of the extension at http://code.google.com/p/tridion-2011-power-tools/source/browse/#svn%2Ftrunk%2FPowerTools.Editor%2FPowerTools%2FClient%2FItemXml%253Fstate%253Dclosed
You can get the item XML via CoreService, but this will get you the Tridion R6 (2011) Xml format, which is not the same you would see before.
Sample code available here.
I tend to have a page "GetItemXml.aspx" on my Tcm servers that I then call with a Uri as a parameter, and then this page would return the Item Xml.
Article written by Yoav Niran (Url in the post of user978511) is perfect for your requirement.
if you are still facing any issue and in hurry to get it working just perform below steps -
1- Download the extension.
2- Apply the steps 7 and 8 of this article to configure this extension.

Tridion Core Service Update Error

On a refactoring exercise we are working on, we have to change Page Templates for select websites. Most page get localized and have their page templates updated by the code below but for a few we get the following error:
XML validation error. Reason: The element 'Metadata' in namespace 'uuid:940d95aa-fcce-481c-8de5-c61d06c74f46' has invalid child element 'description' in namespace 'uuid:940d95aa-fcce-481c-8de5-c61d06c74f46'.
List of possible elements expected: 'TitleSEO, KeywordsSEO, DescriptionSEO, omniture' in namespace 'uuid:940d95aa-fcce-481c-8de5-c61d06c74f46'.
There is no description field in our metadata schema and TitleSEO, KeywordsSEO, DescriptionSEO, omniture are all optional fields which are not being changed by the code .
try
{
pData = client.Read(page.Attribute("ID").Value, null) as PageData;
//Localize Page
if (!(bool)pData.BluePrintInfo.IsLocalized)
{
client.Localize(pData.Id, new ReadOptions());
if (dTemplateIDs.ContainsKey(pData.PageTemplate.IdRef.ToString()))
{
pData.IsPageTemplateInherited = false;
pData.PageTemplate.IdRef = dTemplateIDs[pData.PageTemplate.IdRef];
client.Update(pData, new ReadOptions());
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error Inner " + ex.Message);
}
It sounds like at some point in the past there was a field in your page metadata schema called "description" (which I suspect was later changed to what is now "DescriptionSEO"). These few pages that cause the error have probably not been updated since the change, and so have the old metadata field in their XML, hence the validation problem when you come to change the Page Template.
If it's only a few pages, just open the pages, add some description or otherwise change something, save them and then try your code again.
If it's more than a few, you'll probably need to detect and remove the existing data programmatically.
I am not sure which version of SDL Tridion you are using, but in some early versions of SDL Tridion 2011, if Metadata had previously been added to any object, it was not cleared by changing the Metadata Schema to be empty on the object. As such, I have found that you had to set the Metadata value to NULL with code before saving the item. This may solve your problem.

Tridion 2009 - Publish another Component from a Component Template

First, the overall description:
There are two Component Templates, NewsArticle and NewsList. NewsArticle is a Dreamweaver Template, and is used to display the content of a news article. NewsList is an xml file that contains aggregated information about all of the news articles.
Currently, a content author must publish the news article, and then re-publish the newslist to regenerate the xml.
Problem:
I have been tasked with having the publish of a news article also regenerate and publish the newslist. Through C#, I am able to retrieve the content of the newslist component, generate the updated xml from the news article, and merge it into the xml from the newslist. I am running into trouble getting the newslist to publish.
I have limited access to documentation, but from what I do have, I believe using the static PublishEngine.Publish method will allow me to do what I need. I believe the first parameter (items) is just a list that contains my updated newslist, and the second parameter is a new PublishInstruction with the RenderInstruction.RenderMode set to Publish. I am a little lost on what the publicationTargets should be.
Am I on the right track? If so, any help with the Publish method call is appreciated, and if not, any suggestions?
Like Quirijn suggested, a broker query is the cleanest approach.
In a situation if a broker isn't available (i.e. static publishing model only) I usually generate the newslist XML from a TBB that adds the XML as a binary, rather than kicking off publishing of another component or page. You can do this by calling this method in your C# TBB:
engine.PublishingContext.RenderedItem.AddBinary(
Stream yourXmlContentConvertedToMemoryStream,
string filename,
StructureGroup location,
string variantId,
string mimeType)
Make the variantId unique per the newslist XML file that you create, so that different components can overwrite/update the same file.
Better yet, do this in a Page Template rather than Component Template so that the news list is generated once per page, rather than per component (if you have multiple articles per page).
You are on the right tracks here with the engine.Publish() method:
PublishEngine.Publish(
new IdentifiableObject[] { linkedComponent },
engine.PublishingContext.PublishInstruction,
new List() { engine.PublishingContext.PublicationTarget });
You can just reuse the PublishInstruction and Target from the current context of your template. This sample shows a Component, but it should work in a page too.
One thing to keep in mind is that this is not possible in SDL Tridion 2011 SP1, as the publish action is not allowed out of the box due to security restrictions. I have an article about this here http://www.tridiondeveloper.com/the-story-of-sdl-tridion-2011-custom-resolver-and-the-allowwriteoperationsintemplates-attribute

ASP.Net How to access images from different applications

I have 2 different project. One is supposed to upload images (admin) and the other is supposed to show them.
I was writing something like "/Contents/images/image path"... But wait! I will I upload the images from the application into that address?
Any help and suggestions please.
If you have two applications that will interact with the same files, it's probably better to have an ImageController with an action that allows you to upload/download the image rather than storing them directly as content. That way both applications can reference the same file location or images stored in a database and manipulate them. Your download action would simply use a FileContentResult to deliver the bytes from the file. You can derive the content type from the file extension.
Example using a database. Note that I assume that the database table contains the content type as determined at upload time. You could also use a hybrid approach that stores the image metadata in a database and loads the actual file from a file store.
public class ImageController : Controller
{
public ActionResult Get( int id )
{
var context = new MyDataContext();
var image = context.Images.SingleOrDefault( i => i.ID == id );
if (image != null)
{
return File( image.Content, image.ContentType );
}
// or you could return a placeholder image here if appropriate.
throw new HttpException( 404, "The image does not exist" );
}
}
An alternative would be to incorporate your administrative interface in an area of the same application rather than in a separate project. This way you could reuse the content/images directory if you wanted. I find that when you have dynamic images the database or a hybrid approach works better from a programming perspective since it's more consistent with the rest of your data model.
you could try like this..
Let's assume that all of your images are in Project A and you want to use the same images in Project B.
Open Project B with Visual Studio. In the Solution Explorer, right click your Project Name and select "Add Existing Item...".
Browse to the physical location on disc where your images in Project A are stored and select the files that you want to import.
You'll then be able to access those images from project A in Project B.

Resources