Friday, July 25, 2014

Ignore SSL Certificate Check in PowerShell

Sometimes we might be using self signed or different domain SSL certificate for staging or QA specific websites. In Windows PowerShell, when HttpRequest is used to make requests to such websites, below error is thrown

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

This error means that the server certificate validation failed. If we want to ignore SSL validation check in PowerShell, we must write a call back for server certificate validation. To do this, just add below line of code before actual the HttpRequest call:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

Above line will always return true which means that SSL certificate validation was successful.

Monday, July 21, 2014

Partial Responses in WCF REST API

One of the nice to have feature in any REST API is partial responses. With the help of partial responses, we can request only those fields which are required as part of response.  By only requesting information that it will actually use, a client application can more efficiently use network, CPU and memory resources. By contrast, an application that retrieves a full API feed, parses it and then drops unused fields is likely to waste some resources along the way.

An example of partial response is Youtube API.

WCF framework can be used to build REST APIs which by default does not support partial responses. However, we can easily write extension in WCF services to manipulate the response message and send only partial response. One such extension is available @

This extension takes the fields parameter from the query string of requested URL and accordingly sends the required fields in the response. The fields parameter limits the data fields that are returned for the feed or for specific entries in the feed. It is case insensitive.

Following are the templates for fields parameter:

  • Immediate fields of an object – To select the immediate children nodes of an object, specify the required field names separated by comma.
    E.g.: recipeId,recipeName,photoUrl,SEOPageName
  • Fields of a nested object – To select fields of a nested object, specify the name of the nested object followed by comma separated list of fields enclosed in parentheses.
    E.g.: recipeId,recipeName,Tip(TipName)
  • Fields of a collection item – To select certain set of fields of all items in a collection, specify the name of the collection and a colon (:) followed by comma separated list of fields enclosed in parentheses. E.g.: recipeId,recipeName,Ingredients:(IngredientId,IngredientName)
Note: If the start node of service response is a collection then that particular collection name and colon should not be specified in fields parameter.

This is a WCF extension and can be easily integrated to any existing WCF service using web.config.
In web.config, add a new behavior extension and then use it the required endpoint behavior.


        <!-- Declare Extension -->
        <add name="partialResponse" type="PartialFields.PartialResponseProcessor, PartialFields" />
<behaviors> <endpointBehaviors> <behavior name="webby"> <!-- Use extension --> <partialResponse /> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel> </configuration>

Monday, July 7, 2014

MongoDB and Phalcon PHP - CollectionManager Not Found

MongoDB is supported out of box in Phalcon PHP. Phalcon PHP has very simple yet limited Object-Document Mapper (ODM) library which is used for connecting to NoSQL databases like MongoDB.

To connect to MongoDB in Phalcon, a service must be added in DI container as follows:

$di->set('mongo', function() {
    $mongo = new MongoClient();
    return $mongo->selectDB("db_name"); //database name in MongoDB
}, true);

When executing the script related to MongoDB interactions in PhalconPHP, below error is thrown:
Service 'collectionManager' was not found in the dependency injection container

As each MongoDB document is a collection in Phalcon, a collection manager service is needed for initialization of models, keeping record of relations between the different models of the application etc.
To resolve this error, collectionManager service must also be added to DI container.
$di->set('collectionManager', function(){
    return new Phalcon\Mvc\Collection\Manager();
}, true);

So, while working with MongoDB in PhalconPHP, make sure that both mongo and collectionManager services are added to DI container.

Catch ThreadAbortException in ASP.Net

In ASP.Net, whenever a redirect or response end statement is executed, ThreadAbortException is thrown and it is logged in event viewer.

System.Threading.ThreadAbortException Message: Thread was being aborted. 
Source: mscorlib at System.Threading.Thread.AbortInternal() 
at System.Threading.Thread.Abort(Object stateInfo) 
at System.Web.HttpResponse.End() 

To avoid thread ThreadAbortException related messages in logging, call to Response.Redirect and Response.End methods should be wrapped in try-catch block. Simply catching this exception will not work as the exception is thrown again even after getting caught. So, in the catch block a call should be made to Thread.ResetAbort() method.

catch(ThreadAbortException ex)
    //Exception is again thrown after catch block.
    //To suppress it call ResetAbort method of System.Threading.Thread

Friday, June 27, 2014

IIS ARR Reverse Proxy and HTTP Status Code 304

In IIS 7.5, reverse proxy using ARR v2, does not send 304 status code for subsequent requests which are cached on file system. Because of this, even if the actual website allows caching of requests in browser (client side), ARR always sends HTTP 200 code. This forces the browser to download the cached request again from server.

For some strange reason, ARR always send status code 200 if requests contains ETags.
So, basically if you want ARR to send 304 status code then ETags must be removed.

In IIS, Etags can be removed from response with the help IIS URL Rewrite module. Following outbound rule must be created to remove ETags:

  <rule name="Remove ETag">
    <match pattern=".+" servervariable="RESPONSE_ETag">
    <action type="Rewrite" value="">

For more details check below links:

Wednesday, June 25, 2014

Reading Complex Field Values in Sitecore WFFM

Sitecore Web Forms for Marketers is a Sitecore CMS module used for creating forms in a website. It has various set of fields like simple, list, complex, pre-filled etc.

Usually to access field value in code, Value property of AdaptedControlResult class is used.
For any list or complex types of fields, the Value property normally contains extra information.

For e.g., A WFFM form has a check-box list and the values for its items are 1,2,3,4,5. User selects 1,2,3 and submits the form.
Then in the server-side code the value of this field is:


To get a simple value with out item tags then GetSitecoreStyleValue method of FieldReflectionUtil class can be used.
Example code snippet:

AdaptedResultList fields;

// Get the form field by specifying the field name
AdaptedControlResult formField = fields.GetEntryByName("fieldName"); 

// complex value with item tags
string fieldValue = formField.Value;

// simple value without item tags
fieldValue = Sitecore.Form.Core.Utility.FieldReflectionUtil.GetSitecoreStyleValue(formField.FieldID, fieldValue);

BottomLine: Use FieldReflectionUtil class to get simplified version of form field values.

Tuesday, June 24, 2014

Extension Randomly Added in Sitecore Media Item URLs

In Sitecore 6.6, MediaManager randomly adds extension while generating URL for any Sitecore Media Item. This is a bug in Sitecore. A workaround is available to fix this issue.
MediaUrlOptions mediaUrlOpts = new MediaUrlOptions();
mediaUrlOpts.IncludeExtension = false;
Response.Write(MediaManager.GetMediaUrl(item, mediaUrlOpts));

In case extension is always needed in the URL then set IncludeExtension property to true.

Tuesday, April 22, 2014

Sitecore Admin User Password Reset

Some times the admin password for Sitecore instance is lost or the user admin account is locked.
One way to reset the admin password is by executing SQL scripts.

Another easy way is by placing below C# code in an aspx page and browsing it using the sitecore instance domain:

string resetPassword = String.Empty;
string userName = string.Empty;
string newPassword = "newPassword";
bool status = false;
bool isLocked = false;

using (new Sitecore.SecurityModel.SecurityDisabler())
 userName = @"sitecore\admin";
 MembershipUser user = Membership.GetUser(userName, true);
 if (user != null)
  resetPassword = user.ResetPassword();
                status = user.ChangePassword(resetPassword, newPassword);
                isLocked = user.IsLockedOut;
                if (isLocked)

Response.Write(String.Format("Password updated {0} for user - {1}", (status ? "successfully" : "failed"), userName));

This code can be placed in an aspx file kept inside \Website\sitecore\admin\ location.
Once the aspx page is created with the above snippet, browsing that aspx page will reset the admin password to the desired password given in variable newPassword.

Sample aspx page can be found in GitHub.

Sunday, April 20, 2014

Reasons for Sitecore IIS App Pool Crash

In past few months, there were two separate instance where IIS application pool of Sitecore website was crashing intermittently. In both of these cases, stack overflow resulted in IIS application pool crash. This article lists some of the reasons for stack overflow scenarios in Sitecore:

1. Infinite control load using Presentation Inversion of Control:

The websites which were built on Sitecore instance uses Presentation Inversion of Control. In simple terms, there were some custom Sitecore sublayouts built which renders the controls added to its DataSource item.

In one of the website's home page (startItem), the content author added one such control. The data source item for that control also had the same control, mistakenly, added as part of it presentation details. Whenever a request was made for the home page, the controls were loaded infinitely which led to application pool crash.

2. Sitecore Custom Security Providers:

Whenever an item is requested, sitecore checks if the user has access rights to the item or not. To get the user details for access rights, Sitecore checks with the security providers which are configured in web.config file. In one such custom security provider, to get user details, a sitecore item was being accessed. Since this custom security provider was trying to access sitecore item, Sitecore again checks for user access and invokes GetUser() for security providers. This resulted in an infinite recursive loop and led to application pool crash. So, if you are creating any custom security providers in Sitecore, ensure that those security providers in turn do not access any sitecore item.