Programmatically skip publishing of item(s) in Sitecore

by aboo bolaky 23. July 2009 05:43

Scenario

Assume that you have a set of items (say..Product items) (sitting anywhere within the /sitecore/content..) based on a specific template. The requirement here is that

"A Product cannot be published if one of its fields (ProductID) isn't populated."

Background

To achieve this, we need to hook into the publish:itemProcessing event in the web.config. This event gets triggered every time an item is published. The general steps involved in this situation are:

  • Create a class with a method that adheres to the EventHandler delegate signature. Whenever you initiate a publish operation in sitecore (be it smart publish, incremental or full publish), the method will be called (depending on how many items that need to be published)
  • Modify the web.config to subscribe to ItemPublishing event

ItemPublisher Class

namespace Test.Events 
{
	public class ItemPublisher
	{
	   public void CheckProcessing(object sender, EventArgs args)
		{
		  ItemProcessingEventArgs theArgs = args as ItemProcessingEventArgs;
						
		  Item currentItem = theArgs.Context.PublishHelper.GetSourceItem(theArgs.Context.ItemId);

		  if ((currentItem != null) && (currentItem.Paths.IsContentItem))
		  {
			  //Template ID of item on which selective publishing is to be applied
			 if (currentItem.TemplateID == new ID("{9C9A2F3D-652A-4490-AB57-E9F1B4D5BF05}"))
			  {
				 Job currentJob = theArgs.Context.Job;
				 JobStatus currentJobStatus = currentJob.Status;

				 if (String.IsNullOrEmpty((currentItem.Fields["Product ID"].Value)))
				  {
					currentJobStatus.Messages.Add(String.Format("Item :{0} has not been published since it has no Product ID", currentItem.Name));
					theArgs.Cancel = true;
					return;
				   }
			  }
		   }
		}
	}
}


Line 7:
Cast the standard EventArgs class to ItemProcessingEvent. This is important since it gives you the possibility of retrieving details of the items being published.

Line 9: Retrieve the item being published.

Line 11: The check for "currentItem.Paths.IsContentItem" is important since we only want to check for content items. Since publishable items sitecore vary from templates,standard values, renderings... we do not want to check for the condition in ALL items.

Line 14: If the template of the current item matches the id of the Product template, then we're back in business.

Line 16 - 21: Find the reference to the current Job (and JobStatus)  being executed in the publish pipeline. If the item's field is empty, add a message to the JobStatus.

Line 22: Abort the publish operation of the current item. I don't think we require the return statement after that. Publishing will then resume for the next item in the publishing queue.

Web.Config Change

Locate the publish:itemProcessing event in the web.config. Hook up the new handler to the event.

<event name="publish:itemProcessing" 
help="Receives an argument of type ItemProcessingEventArgs (namespace: Sitecore.Publishing.Pipelines.PublishItem)" >
   <handler type="Test.Events.ItemPublisher,TestApplication" method="CheckProcessing" />
</event>

Let's put it to the test

That's all to it really. If you now  initiate a publish operation and one of the Products has an emtpy Product ID, you will end up with this (if you click on "Click here to see additional information" on the last screen of the publish wizard.)

Items Skipped = 1 (.i.e Camera item has been skipped during the publish process since it has no ProductID). If you switch to the web database, there will not be any "Camera" item. 

Result... :)

Tags: ,

.Net | Applications | Sitecore

The Sitecore Way

by Aboo Bolaky 9. July 2009 07:09

4 months since my last post. This should give you an idea of my hectic life as a software developer.  Build..Test.. Deploy.....Build..Test.. Deploy.. This seems to be the only thing that I have been doing lately and hasn't left me with any time to do anything else.

Things have got to change and NOW is the time :-)

Back in Febuary, I came accros a file (via some random Google Search about Sitecore) that outlined some good one-liners about building websites using Sitecore. At that time, I added the link to my favourites and didn't pay much attention to it. Now that I've accessed the link again (by mistake..), I realise that so many of those "guidelines" are correct. Unfortunately, I did not capture the author of the text file at that time. Here's the online version

The Sitecore Way

1) Think about the CMS users not just the Web site. The Sitecore Way.

2) Use XSLT to minimize code compilation for maintenance. The Sitecore Way.

3) Get better performance with ASP.NET user-controls.  The Sitecore Way.

4) Use an ASP.NET master for your layouts. The Sitecore Way.

5) Return Item ID for XSLT extension results. The Sitecore Way.

6) Avoid setting language in a request after the Sitecore pipeline. The Sitecore Way.

7) Use icons for your masters and templates. The Sitecore way.

8) Protect /sitecore as much as you can. The Sitecore way.

9) Cookieless is possible, but be careful. The Sitecore way.

10) It's very important to Organize the content structure correctly. The Sitecore Way.

11) Finalize design as much as you can before implementation. The Sitecore way.

12) Ask for design behavior specs not just content info. The Sitecore way.

13) Use file system for large files instead of media library. The Sitecore way.

14) Use source-control for new/changed files inside Sitecore. The Sitecore Way.

15) Please avoid inline C# code in XSLT. The Sitecore way.

16) Test renderings using the debugger ALWAYS. The Sitecore way.

17) Multi-site, multi-language, identify what the client needs. The Sitecore Way.

18) Globalization is easy with Sitecore...use it. The Sitecore way.

19) Create custom XAML apps for better experience. The Sitecore way.

20) Use Sitecore's security mechanism for other applications. The Sitecore way.

21) Be careful of data cache synchronization between two sites. The Sitecore way.

22) Remove default favico.ico or your client might yell at you. The Sitecore way.

23) To stage or not to stage. We say to stage. The Sitecore way.

24) Use Lucene.net if you can for site search...it's FREE. THe Sitecore way.

25) Disaster recovery plan: zipped Web site and DB backups.  The Sitecore way.

26) Minimize rendering URL parameters to keep an SEO-friendly site. The Sitecore way.

27) Dont' forget the robots.txt...just good Web practice. The Sitecore way.

28) Analyze secuirty by feature and content access. The Sitecore way.

29) Download the Enhanced Email Action, why not? The Sitecore way.

30) Content analysis should be a top priority. The Sitecore way.

31) Use nested templates but be careful. The Sitecore way.

32) Make life easy by using a sticky session load-balancer. The Sitecore way.

33) More than a CMS, it's an integration platform. The Sitecore way.

34) Get more value by integrating it with internal systems. The Sitecore way.

35) Deliver templates and masters early to  avoid content freeze. The Sitecore way.

36) Physical storage of data does not look like Sitecore XML. THe Sitecore way.

37) Ever used Sitecore Query to query the Sitecore XML?  It's cool. The Sitecore way.

38) Use the search in the Sitecore bar for a quick content search. The Sitecore way.

39) No gray desktop background or you might loose your cursor : ). THe Sitecore way.

40) Drag content items on the desktop to create a shortcut. The Sitecore Way.

Credits: Unknown Author

 

How many of these have you achieved????

 

Tags: ,

.Net | Applications | Sitecore | Tips & Tricks

Listview losing viewstate on postback in Sitecore V6

by Aboo Bolaky 21. February 2009 08:23

This post will most probably apply to the GridView and LoginView controls as well.

The Problem

Lets assume that you've successfully bound a listview to your datasource and configured all the properties on the listview to display the Select/Edit/Delete links. You then have the task to write the logic in the appropriate events of the usercontrol/sublayout. While I was implementing the Edit functionality, I implemented the OnItemCommand event of the Listview to display an Edit Panel with the data populated from the selected row. I was a bit suprised to see that the end result wasn't what I was expecting:

The Edit Panel shows up but the Listview has left the party.!!

The Frustration 

It dawned on me that, at some point, I must have messed up somewhere in the code.So, I began putting "EnableViewState=true" to every control.. (this shows how desperate I was!!). I also reverted to "AutoEventFireUp=false" (Originally, I was manually hooking up the events..).I tried databinding on every possible method I could lay my hands on!!. I lost confidence on the fact that this was a really easy task and yet, it was taking me hours to get to the bottom of the problem. I completely lost my mind....I began googling on the issue ["postback..losing viewstate"], I started to watch a few videos that demonstrate the functionality of the ListView..I even got the point where I created another item in Sitecore, assigned the same sublayout to the item's presentation and accessed the item using the url.. I ended up in the same situation.... I surrendered...I left the battlefield...wounded..!!![White flag..Sealed].

The Solution

I finally blamed it on Sitecore!! Who knows, maybe it was a known issue in one of their releases or maybe I just needed to upgrade to the latest stable release(090120). Out of desperation, I tried searching on the Forums and found that I wasn't the only one experiencing this issue.I came across this forum post. Thanks to Mark Cassidy, I eventually finished my task (It had taken me almost a day...and that had messed up (big time) on my initial estimate!!!)

The solution, as Mark outlined, is to add the type of the control (in my case, System.Web.UI.WebControls.ListView) to the typesThatShouldNotBeExpanded element in the web.config. Presumably, for the sake of consistency, you might also append the System.Web.UI.WebControls.Gridview to the list (in case your website makes use of one!!). From what I've read so far, no one knows about the purpose of the typesThatShouldNotBeExpanded element .!! {Sigh...Sitecore!! What did you do that to me????}

In hindsight, only laughs...Good Days...Good Times...

I hope this helps someone!!!

Back to Sitecore  ......

Tags:

.Net | Applications | Sitecore | Tips & Tricks

The AddAspxExtension property in Sitecore V6

by Aboo Bolaky 11. February 2009 07:53

In Sitecore 6.0, a new Link Manager class has been added. In the web.config, a few properties affect the functionality of the Link Manager. I've already posted on the EncodeNames property (fyi, default value : false).

The AddAspxExtension Property

On the surface, I can clearly relate to the functionality of this property. If this is set to false, we are instructing Sitecore to render links (i.e via <sc:link>) without any extensions. This is (alledgedly) GREAT NEWS for SEO experts. If you leverage this functionality with some Url Rewriting (either via Helicon Isapi Rewrite Lite (free)  or UrlRewriter.Net ), you must be thinking that you will have a Sitecore front-end website without any extensions.

The Glitch...

If you spent most of your time in implementing regular expressions to rewrite (under the hood) those extensionless links to .aspx and feed them back to Sitecore, Well...I'm afraid you have wasted your precious time (no matter how cool your regex expressions are!!). The moment you try to access the Content Editor in the CMS, you  simply receive some weird error messages. Sometimes, it's the dreaded YSOD (Object Reference not set to an instance of an object) or occasionally a 404 page welcomes you. With the AddAspxExtension property set to false, you might end up with a fancy looking frontend and NO backend support at all. Not very usefull... Did a bit of research on SDN5, turns out that the symptoms are correct

This has led me to believe that, in the midst of tackling problems that vary in programming complexity and requirements , always take a step back and test both the front end and back end when dealing with "unchanted territories".

And then...

The search to build an SEO friendly website in Sitecore continues.. Surely, I'll get the better of this (it's just a matter of time...why not build up the suspense?)  and will let you know how I did it !!!! 

Back to Sitecore now....

Tags:

.Net | Applications | Sitecore | Tips & Tricks

SEO Friendly Urls in Sitecore -Remove spaces in Url (2)

by Aboo Bolaky 2. December 2008 11:03

This post is merely a follow up on my previous post : SEO Friendly Urls in Sitecore -Remove spaces in Url .

Even if you use the encodeNameReplacements settings in your web.config, this may well not be enough to get you going with clean urls. Although it will allow you to access an item by replacing the spaces with a dash (.i.e. if you chose to replace a space with a dash in the encodeNameReplacements element) in the url, the links that are rendered on the page (either by doing sc:link in xslt or the usual .net code) will still contain "%20" characters.

Now, this is the bit where I "kind of" messed up. In Sitecore V6 , we have the concept of LinkManager in the web.config. By default, the EncodeNames property is set to true. This is correct and you SHOUD NOT CHANGE IT. If the EncodeNames property is set to false, you will end up having "%20" characters in your hyperlinks.

The big question for me is when and why did I change the EncodeNames to false? I don't know.. Maybe I thought, at some point in time, that toggling the key to a value of false would solve some other problem that I was experiencing?

Anyway, had I not changed EncodeNames to false , I would have never the known the actual meaning and implications of EncodeNames. We learn from our mistakes... Cool

While we're here, you can remove the language code in the urls (http://hostname/en/node1/child.aspx) by changing the key languageEmbedding to "never". In that case, you will end with a url that looks like http://hostname/node1/child.aspx.

Back to Sitecore now..

Tags:

.Net | Applications | Sitecore | Tips & Tricks

The WebUtil Class in Sitecore

by aboo bolaky 30. November 2008 06:36

For those Sitecore lovers..

When you code against Sitecore, whether against renderings or sublayouts, I'd suggest you have a look at the very useful methods defined in Sitecore.Web.WebUtil Class. Those methods will help save you some time and prevent you from re-inventing the wheel. Some methods worth mentioning are :-

string AddQueryString(string url, params string[] parameters)
string AddQueryString(string url, bool xhtml, params string[] parameters)
string ExecuteWebPage(string url)
string ExtractFilePath(string url)
string ExtractUrlParm(string name, string url)
Placeholder FindPlaceholder(string key, Control root)
HtmlAnchor GetAnchor(Item itm, string linkField)
Control GetErrorControl(string error, string details)
Control GetFormControl(Page page)
string GetFormValue(string fieldName)
string GetFullUrl(string url, string serverUrl)
string GetHostIPAddress()
string GetHostName()
string GetQueryString()
string GetQueryStringOrCookie(string key, string defaultValue)
void RedirectToErrorPage(string text)
string RemoveQueryString(string url)
void ReloadPage()
string ReplaceUrlParameter(string url, string replace, string withtext, bool append)

Alternatively, you can have a peek at all the methods in the screen grab below [Click on the image for a better view..]

Tags:

.Net | Applications | Sitecore | Tips & Tricks

SEO Friendly Urls in Sitecore -Remove spaces in Url

by aboo bolaky 29. November 2008 09:50

Aliases in Sitecore

Sitecore has the concept of "Aliases", whereby each item can accessed using a specific name (rather than the default path). Aliases are turned on by default. To turn them off, you can flip the web.config settings name AliasesActive to false (But who would want to do that???? Sealed)

Space Characters in Sitecore

When you create an item in Sitecore, you free to choose the naming of your item (provided it succesfully validates against some key rules .e.g Item name cannot contain :,?.. otherwise, you will end up with a "Item xxx is not a valid name"). Most of the time, you will want to put spaces in the item name. Let's take an example:

If an item (at the root level) has an item name of "John Doe", the url of the actual page should theoretically be http://hostname/John%20Doe .

Of course, you can get rid of this spacing issue by specifying an Alias of John-Doe on the item itself. But imaging you having hundreds of items with spaces !!!..

The encodeNameReplacements element in the Web.config

This encodeNameReplacements settings allow you to globally replace any unwanted character in your url to a character of your choice. So, rather than creating an alias for each item (without spaces), we can add the following new setting.

<encodeNameReplacements>
	<replace mode="on" find="&" replaceWith=",-a-,"/> 
	<replace mode="on" find="?" replaceWith=",-q-,"/>
	.....
	<replace mode="on" find=" " replaceWith="-" />
</encodeNameReplacements> 

Job Done ! Cool

 

Tags:

.Net | Applications | Sitecore | Tips & Tricks

Sitecore-Compelling Web Experiences

by Aboo Bolaky 4. November 2008 08:44

Over the past few weeks, I've had the opportunity to use Sitecore to build a website. Whilst i still consider myself to be a novice in Sitecore, I'm afraid I won't be able (at least for the time being!!!) to shed more light on this powerful Content Management System.

However, he're is a video that will help you "understand" what Sitecore is REALLY about. Great marketing stuff!!!

PS: Sitecore isn't just a CMS...

 

Anyways, I'll keep you all posted about my learning journey with Sitecore. So far, it's been GREAT!!

Tags:

.Net | Applications | Sitecore

Tag cloud

Flash Player 9 required.

About Me

I wish I could write something here..
//TODO: ElaborateMe