Jonel Rienton's Blog

Sitecore, SharePoint, WF, WCF, ASP.Net, ADO.Net, LINQ, ASP.Net MVC
Watching Green Day and discovering Sitecore, priceless.

I’m feeling inspired and I’d like to share a technique we’ve implemented in Sitecore to address a URL mapping from our legacy site that we wanted to carry over to the new beautiful Littelfuse.com.

The challenge is to carry over all of our series URLs that have been published in our datasheets, we currently have a lot of series and having to create a manual mapping for those could be really tedious. It has the format of http://www.littelfuse.com/series/series-name.html, for instance, http://www.littelfuse.com/series/flnr.html. It would have been easier if we have our information architecture defined like this but that would have been too easy.

I took a solution that is 2-fold. First, I need to create a URL rewrite rule using the IIS URL Rewrite Module 2.0. Secondly, we need to implement a handler that will take care of the actual lookup of the actual series. It will be amazing after we’ve gone over the details.

Let’s start with the URL rewrite. Create a new blank rule, you can name it with anything you wish. The key part here to talk about is the Pattern and the Action groups. The Pattern is nothing but regex. Basically, I’m telling it to match the regex I have defined. In the Action group, I am telling it what to do, in this case, rewrite to the redirect.aspx webform. In this implementation, I will be using Rewrite instead of redirect so the URL sticks in the browser. If you opt to use Redirect, then the URL bar will display the new URL our webform will redirect to.

Let me explain one small thing, the (\w+) in my Pattern group’s regex, will actually translate to {R:1} in my Action’s group. This is where the magic begins.

image

Now let’s see what our Redirect.aspx contains. Remember our {R:1} above which becomes the query string variable s? This are basic .Net code. The only thing that you will probably ask is the LFSearch class. It’s our own implementation of addressing finding items by using a field search, we supply the fieldname, the value of the field, the template name of the item we are after, and the value of true or false if we want to do an exact search, or not.

If eureka, then redirect to that item’s Path (Url). If not, tell the user tough luck, here’s the 404 page as a consolation.

image

Amazing, ain’t it?

Microsoft opens up Team Foundation Service (TFS) for free (for now)
I have been evaluating Microsoft's TFS (service) for almost a couple of months now. It allows you to host your solution in the cloud with lets you add up to 5 users. Build is currently in preview and will be included in the Free Plan on a limited basis.

Go to https://tfs.visualstudio.com to check it out.
Sitecore Item Web API and Json.Net Test Drive (Part II –Strongly Typed)

In the earlier post I did related to this topic, I have talked about using Json.Net to consume the result of Sitecore Item Web API. In that post, I have used the keyword dynamic to express my intention of consuming the returned json of the API.

In this article, I will create some useful classes to write our implementation of consuming the API using strongly-typed. We will start of with the Record class which will hold the top most elements the API will present us.

Record class

Pretty straight forward class. It has 2 properties to hold the statuscode and the result elements. If you intend to use a different property name in your class from the json property, you can do so by passing a string literal of the json property name to the JsonProperty attribute and name your class property differently.

If you look at the earlier post, you will notice that the API returns an array of items that contains all of the Sitecore content item or items and stores them under the result->items array element. To be able to map that array of items, we have to write a collection property and decorate that with the JsonProperty attribute.

Result class

The JsonItem class is a simple class which will map to the corresponding item property contained in the array. If you notice, these properties are just the basic Sitecore fields.

JsonItem class

And here’s the main portion of this post that will binds them all together.

Main

And here’s the output of this code.

Output

In closing, the same result can be achieved using the dynamic keyword or defining classes to map the json propery returned by the Sitecore Item Web API. With a little bit more of coding, you can take advantage of power of strongly-typed solution.

Have a good week ahead of you.

Sitecore Item Web API and Json.Net Test Drive

Sitecore recently released it’s Item Web API product and I think it will be good for the community to see some sample application. I plan a to do a 3 series blog iteration in the coming weeks, this, being the first one.

  1. Sitecore Item Web API and Json.Net Test Drive
  2. Sitecore Item Web API and Json.Net Test Drive (Part II – Strongly Typed)
  3. Sitecore Item Web API and MonoTouch (iOS development), specifically MonoTouch.Dialog – awesome, awesome framework.

Before moving on, the assumption is you have already installed and configured Sitecore’s Item Web API in your development environment. I can probably cover that as well on a separate blog. It’s really simple, really.

So now that you have Sitecore’s Item Web API installed, you are probably asking yourself what does this new tool provide? In a nutshell, it provides you 3 things:

  1. Allows client to get Sitecore items based on ID or query. For now, based on my evaluation, it supports Sitecore query and Sitecore fast query. The limitation I saw initially was it does not allow me to include query filters like [@@templatename=’Product’].
  2. Allows item manipulation (add/update/delete). This is done via the different Http verbs.
  3. Allows media uploads.

Now that we got that out of the way, let’s look at the existing code below.

  1. Lines 3 to 10 are just basic variable declarations. It gets the values from the app.config this case.
  2. Lines 12 to 19 just sets the string variable request based on the value of the query.
  3. Line 21 downloads the actual request
  4. Line 23 parses the returned json string using Json.Net. Note the usage of the dynamic keyword. Very powerful stuff.
  5. If you look at the returned json string, you can see that it contained the items array inside the result.
Code Snippet
  1. static void Main(string[] args)
  2.         {
  3.             var client = new WebClient();
  4.  
  5.             var apiUrl = getConfiguration("apiUrl");
  6.             var query = getConfiguration("query");
  7.             var sc_itemid = getConfiguration("sc_itemid");
  8.             var apiParam = getConfiguration("apiParam");
  9.             var payLoad = getConfiguration("payload");
  10.             string request = "";
  11.  
  12.             if (apiParam.Equals("query",StringComparison.OrdinalIgnoreCase))
  13.             {
  14.                 request = string.Format("{0}?{1}&{2}", apiUrl, query, payLoad);
  15.             }
  16.             else if (apiParam.Equals("id",StringComparison.OrdinalIgnoreCase))
  17.             {
  18.                 request = string.Format("{0}?{1}&{2}", apiUrl, sc_itemid, payLoad);
  19.             }
  20.  
  21.             var apiResponse = client.DownloadString(request);
  22.  
  23.             dynamic jsonResponse = JObject.Parse(apiResponse);
  24.  
  25.             if (null!=jsonResponse && jsonResponse.statusCode=="200")
  26.             {
  27.                 Console.WriteLine("Status code:" + jsonResponse.statusCode);
  28.                 Console.WriteLine("Total Count:" + jsonResponse.result.totalCount);
  29.  
  30.                 foreach (var item in jsonResponse.result.items)
  31.                 {
  32.                     Console.WriteLine(item.DisplayName + ": " + item.Path);
  33.                 }
  34.             }
  35.  
  36.             Console.WriteLine("Done.");
  37.             Console.ReadLine();
  38.         }
  39.  
  40.         private static string getConfiguration(string p)
  41.         {
  42.             return ConfigurationManager.AppSettings[p];
  43.         }

Here’s a copy of the returned json. Viewed using Chrome and Pretty Json.

image

Here’s a copy of the app.config

App.config
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3.     <appSettings>
  4.         <add key="apiUrl" value="http://sitecore.local/-/item/v1"/>
  5.        
  6.         <add key="query" value="query=/sitecore/content/home/products/*"/>
  7.  
  8.         <!--
  9.             apiParam: values could be query or id
  10.         -->
  11.         <add key="apiParam" value="qUery"/>
  12.        
  13.         <add key="sc_itemid" value="sc_itemid={F29FBDBA-8DA7-4EE7-8114-07ECC25F42CF}"/>
  14.        
  15.         <!--
  16.             Payload: values could be min, content, or full
  17.         -->
  18.         <add key="payload" value="payload=min"/>
  19.        
  20.         <!-- <add key="fields" value=""/> -->
  21.     </appSettings>
  22. </configuration>

In closing, I’ve only touched the surface of Sitecore’s Item Web API. I’m sure the next releases will build upon this new framework and make it more awesome.

Viewing Sitecore log in real time

It's been almost a year since I've been Sitecore certified and I've learned so much by reading documentations, reviewing existing code, reading best in class blogs and gathering peers recommendations. In my initial months with Sitecore, I found out about the log viewer which basically allows us to view the current and previous logs of Sitecore. Pretty handy if you are troubleshooting some issues or using the logs to see what's happening with your application/website.  One of the drawbacks I noticed right away is I have to refresh the log every time to see the latest additions.

Coming from a unix background, I am familiar with a command line tool called Tail. Fortunately, there's a Windows version of tail and even better with a GUI interface. I highly recommend this tool as it provides you real time information in your current Sitecore log. You can download the application from the Tail for Win32 website.

Posted: Jun 30 2012, 07:26 PM by jonel | with no comments
Filed under:
Sitecore fast query not returning items when searching for item names issue and how to fix

 I've recently hit a snag while using Sitecore's fast query. To begin with, I first noticed the issue when one of my colleagues reported that the upload application we have recently developed is not working. The upload application is supposed to add children to items that already existed. It turns out that the issue was the fast query I have written was not finding the parent item those children are supposed to be loaded under.

 Here's a look of the query I was using:

fast:/sitecore/content/home/products//X7500

I know this parent item exists as I can view it in the content editor.

 After a few tries using the XPath Builder, Sitecore Rocks Query Analyzer and its own XPath builder, I have concluded that this might be something I can spend hours spinning my wheels but not be able to solve. So I turned to Sitecore support. After a day of corresponding in the Sitecore support portal, the engineer came back and told me that I need to run the Clean Database interface and so I did.

Now, this Clean Database interface is one of those that are not well documented (or I might not have done my home work or research well enough). It turns out that when you run this database clean up, the time it will take depends on the size of your master database. In my case, it was a little under an hour. Here's another interesting thought, it kept on timing out on my first couple of tries. Now since this is a background process, I decided to close the modal window after I have  started the process and tail my logs to see what's happening. Sitecore logs stated that the Database Clean up has started and after a few minutes it stated that the job completed (no error message though) so I thought everything went well.

 When I tried the same fast query above, it still didn't work. So I did some research and find out that the DefaultSqlTimeout setting in the web.config is initially set to 5 minutes by default. After adjusting that value I re-run the Clean Database interface and let the modal window stay and this time it completed with no issues and my fast query is now returning the parent items which were not being found earlier.

One thing I recall about those parent items that were not being found, we actually move that item from a staging website to the production website in the same Sitecore installation. I'm not certain if that was the root cause but it might have contributed to it.

Posted: Jun 29 2012, 10:03 PM by jonel | with no comments
Filed under:
FirstOrDefault to the rescue

I have been tinkering with LINQ for quite a bit now and I came across a trivial question about how does LINQ return an entity. I'm going to start off by sharing you a very simple example just to illustrate.  To begin, I'll create a Contact table:

image

Very simple stuff, I start by creating a schema, create the table and start inserting 3 records to it. The next thing I'm going to do is create a solution using Visual Studio 2008.

image

I have renamed the default Class1.cs to ContactDirector.cs. I will then add a LINQ to SQL Class and call it Contact.dbml. VS in turn will create a class for me called ContactDataContext behind the scenes. This class inherits from System.Data.Linq.DataContext.

image

After VS has done its code generation, I'm presented with the LINQ designer. I will go ahead and drag my newly created Contact table to the designer.

image

Ok, we're halfway there. I will now start writing a few code to go back to our initial topic.  At first, I'll start using the very basic way of getting a contact back.

image

I know, I know it's not so elegant at all. But let me generate some unit test from this and I'll show you that indeed this works. But before I do that, I have to override a couple of members of the Contact class. The Equals and the GetHashCode methods. I have to implement a custom logic to compare one contact to another for my testing.

image

Here's my unit test auto-generated by VS, I just added the value for the contactId and the expected variables. You guys should really test this, VS is smart enough to generate the test stubs for you.

image

I just run the test and I get the result back as Passed:

image

Ok, moving back to the next way of getting our contact back, I have come up with this approach:

image

This actually will work but there's one tiny problem with it, if there's actually no element returned, this will throw a InvalidOperationException as the sequence doesn't contain any elements. I can easy surround this call with a try-catch block but that wouldn't feel right.

Now comes FirstOrDefault to the rescue:

image

FirstOrDefault will return the contact I'm looking for or it will return null if it doesn't find any contact that matches. If I actually passed in a contactId that doesn't exist and I change my unit test to do something like:

image

This actually returned a Passed result. I'm sure there are other ways to implement this but I thought this might be worth sharing.

Remeber, always check for null!

Microsoft Event

Today I have been to a Microsoft event. The presenter talked about ASP.Net security, Visual Studio.Net 2008 and a few tips on how to secure your web applications. One thing I like about this kind of events is there's always hidden gold that you can walk with. One that stands out is when the presenter talked about ViewStateUserKey.  To avoid malicious user from using your ViewState value for XSS kind of attacks, setting the ViewStateUserKey in the Page_Init event of the Page will alleviate this.

 ViewStateUserKey 

The presenter also talked about Microsoft Anti-Cross Site Scripting Library V1.5. This library will help you HtmlEncode text that your web application process.

Posted: Jan 24 2008, 10:21 PM by jonel | with 1 comment(s)
Filed under: ,
Hello and welcome!

It's finally nice to have a blog that actually belongs to a community of my own peers. I have been blogging using Google's Blogger for some time and I haven't really updated that site that much. I have been really busy between work and my family. Microsoft has been really generous to allow community members have their own blog space and even provide the Live Writer tool to conveniently post blog entries.  This is really sweet. You can get more information about setting up the Live Writer here.

I'm currently evaluating the free edition of the Community Server to see if we can leverage it for a project at work. Making it work in a Vista Business Edition is a bit challenging; none of my CSS and my images load. I have read quite a few post on what to do to make them load but so far to no avail. I have tried enabling the Static Content and that didn't seem to work.

Windows Features

I have also tried setting up the folder permissions and added Network Service to the list and that didn't go anywhere either. I have created a copy of the Web folder and placed it under my wwwroot folder and it still didn't work. I will just probably move on and install this on my Windows 2003 VM to continue evaluating this product.

I would like to personally thank Joe Stagner for setting up my account in weblogs.asp.net.  Till next time, remember, always check for null!

Posted: Jan 23 2008, 10:57 PM by jonel | with no comments
Filed under:
More Posts