Sunday, September 28, 2014

Building Accordion Component Using AEM 6.0 Slightly Framework




Front end components :


There are two component's, one is accordion container component and another one is accordion section component, the container component will act as a container for section component's

Accordion Container Component Snippet

<script>
  $(function() {
    $( "#accordion" ).accordion();
  });
</script>

<div id="globalcont">
<div id="header">
<div data-sly-resource="${ @path='container', resourceType='foundation/components/parsys'}">
</div>
<div data-sly-use.acc="com.rz.AccordionContainer" >
<div id="accordion">
<ul data-sly-list.child="${acc.src}" data-sly-unwrap=""><h3>
${child.title}</h3>
<p>
${child.body}</p>
</ul>
</div>
</div>
</div>
</div>

Accordion Section Component Snippet

<div data-sly-test="${wcmmode.edit}">Show this only in edit mode to the author</div>


Code base for accordion container component

this is the code base for accordion container component what it does is it will iterate all the child nodes of container component and build custom collection called "AccordionCollection"

The AccordionContainer component extends from WCMUse which is comes with AEM 6.0 slightly framework, the main advantage of this you can get all component related properties ex : getResource()

package com.rz;

import io.sightly.java.api.Use;
import com.adobe.cq.sightly.WCMUse;
import javax.script.Bindings;
import com.day.cq.wcm.api.Page;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceWrapper;
import org.apache.sling.api.resource.ValueMap;
import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
public class AccordionContainer extends WCMUse  
{        

 private static final Logger log = LoggerFactory
   .getLogger(AccordionContainer.class);
    List src = null; 
    @Override 
    public void activate()
    {      
        
  Node rootNode = getResource().adaptTo(Node.class);
  try {
   log.error("Executing handler for try");
   if (rootNode != null) {
    log.error("Executing handler for node" + rootNode.getPath());
    Node par = rootNode.getParent();
    log.error("Executing handler for node" + par.getPath());
    NodeIterator child = rootNode.getNodes();
    while (child.hasNext()) {
     src = new ArrayList();
     Node childnode = child.nextNode();
     log.error("Executing handler for section node"
       + childnode.getPath());
     NodeIterator sectionnode = childnode.getNodes();
     long i = sectionnode.getSize();
     log.error("printing the size " + i);
     
     while (sectionnode.hasNext()) {
      Node node1 = sectionnode.nextNode();
      log.error("Executing handler for child section node"
        + node1.getPath());
      String title = node1.getProperty("sectionTitle")
        .getValue().getString();
      log.error("display the property" + title);
      String body = node1.getProperty("sectionBody")
        .getValue().getString();
      log.error("display the property" + body);
 
       src.add(new AccordionCollection(title,body));
              
     }

    }


   
   }
  } catch (RepositoryException e) {
   log.error("any Error");

   e.printStackTrace();
  }
    }   
    public List getSrc() 
    {       
        return src;  
    }
}


Code base for AccordionCollection component

package com.rz;


public class AccordionCollection {

 private String title;
 private String body;
 
 AccordionCollection(String title, String body){
  this.title = title;
  this.body = body;
 }

   
    public String getBody() {
  return body;
 }
 public void setBody(String body) {
  this.body = body;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }


 @Override
 public String toString() {
  return "AccordionCollection [title=" + title + ", body=" + body + "]";
 }
  
}


Find the output below


Saturday, September 27, 2014

Limit tags selection to certian number in AEM 6.0

Limit tags selection to certian number in AEM 6.0

I see some people have written javascript to limit tags selection to certian number in tags field, but actually there is a OOTB functionality to achieve this and this post will explain how to use OOTB functionality to limit tags selection to certain number

Step 1:

I am going to follow below structure to create tag field but you can use your own strcuture to limit tags selection to certain number, here the tag field node name is categorys


Step 2:

the below properties are created for tag field ( categorys )node


Step 3:

Create node called "namespaces" under your tag field in my case I created under categorys field

The primary type for "namespaces" node is "cq:widgetcollection"

Create a separate node in "namespaces" node and provide whatever name you want, here I given "categorynm"


Step 4:

the below properties are created for tag field "categorynm" node


The "maximum" property plays major role here and this property will limit the number of tags selection and displays error message while authoring




Tuesday, September 23, 2014

Post message on facebook wall from javascript


This article will help you to understand how to post a message on facebook wall

Now a days integration of facebook with application is very common requirement which we see from any client and there are multiple ways to integrate but This article will help you to understand how to post a message on facebook wall using javascript

To access facebook API's first we need to initialize facebook sdk by inserting below snippet directly under
tag

Initialize FaceBook SDK :

<script>
window.fbAsyncInit = function() {
FB.init({
appId      : '1374507272793832',
xfbml      : true,
version    : 'v2.1'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>

Feed Dialog :

You need to call below code on click event of your custom link

FB.ui(
{
method: 'feed',
name: 'T20mins technology site.',
link: 'http://www.t20mins.com',
picture: 'http://t20mins.com/external-xfbml/share-image.gif',
description: 'Technology.',
message: 'Technology.'
});


Code :

<!DOCTYPE html>
<head>
<script src="http://my7steps.com/sites/all/themes/zulka/js/jquery-1.10.2.js"></script>
</head>
<body>
<div id="fb-root">
</div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '1374507272793832',
xfbml : true,
version : 'v2.1'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<a id='share_button' href="#">Post Message</a>
<script type="text/javascript">
$(document).ready(function(){
$('#share_button').on('click', function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'T20mins technology site.',
link: 'http://www.t20mins.com',
picture: 'http://t20mins.com/external-xfbml/share-image.gif',
description: 'Technology.',
message: 'Technology.'
});
});
});
</script>
</body>
</html>






Demo :

Click here to post message on facebook wall



An easy way to integrate facebook with your application

Now a days integration of facebook with application is very common requirement which we see from any client and there are multiple ways to integrate but in this article I am going to explain you how to integrate facebook like button with your website using javascript

To access facebook API's first we need to initialize facebook sdk by inserting below snippet directly under
<body> tag

Initialize FaceBook SDK
<script>
window.fbAsyncInit = function() {
FB.init({
appId      : '1374507272793832',
xfbml      : true,
version    : 'v2.1'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>


The important thing which we need to keeep in mind is appId : '1374507272793832'

You can get appId by going to https://developers.facebook.com/ Settings and App ID


Render Like Button

You need to call below code to render like button
<div  class="fb-like" data-send="true" data-width="450" data-show-faces="true">
</div>

Monday, September 22, 2014

YouTube events are not firing from javascript


While integrating analytics with YouTube player, we found that the custom events were not firing when we use Iframe based javascript approach

Finally we found that by adding "enablejsapi=1" at the end of youtube url then is started working as expected , refer below code

Ex: http://www.youtube.com/embed/0Bmhjf0rKe8?enablejsapi=1

<iframe id="player" src="http://www.youtube.com/embed/0Bmhjf0rKe8" frameborder="0" allowfullscreen>
</iframe>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
playerVars: {
'autoplay': 1,
'controls': 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var playerReady = false;
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
playerReady = true;

}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
alert('Fired...');
}
}
</script>

AEM 6.0 BSOD Error

When ever I open AEM 6.0 instance in my local machine the system is going down and getting BSOD error

To overcome this problem, I have installed below things in my local machine

1. Install JDK1.8
2. Install AEM6.0 Service Pack1


Install JDK 1.8 :

you can download and install JDK 1.8 by following below link

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Installing Service Pack 1

Recently Adobe has released Service pack for AEM 6.0, you can download it by going through the package share

Install Service Pack :

Unzip your quickstart folder by using below command

java -jar a*.jar -unpack

Now, create a new folder called install in quick-start folder and place Service pack 1 for AEM 6.0 in install folder and then start your AEM 6 instance




Monday, October 7, 2013

Integration with other third-party service

The below list of questions will help you to get some high level overview of how to integrate
your application with other third party services and also will help you what are all the question's
we may need to ask to third party provider
  • Do you have any kind of web interface where we can test web methods by passing sample data?
  • How many ways we can integrate your product in to our application? ( Web-methods, REST API's, JavaScript api's, ODATA etc )
  • Does all API's support all functionality’s?
  • Limitations of your product?
  • Do you have any web interface, where we can do basic/limited operations like creating test user's, checking reports etc...
  • Who will provide secret token? Can we generate secret key by following client side web interface?
  • Any limitation on web service API’s calls count? Will you charge if the request count exceeds?
  • Do we need to send username and password along with web service request or username, password and secret token is enough?
  • Will you charge any amount? if we raise a request to create new user or modify something etc... ?
  • What kind of output does your application returns?
        • JSON
        • XML
        • Encrypted IMAGE
        • IFrame contains html
  • If the output is html, does it support all browsers?
  • What kind of authentication mechanism, do we need to follow while using web-service?
  • If authentication mechanism is basic then do we need to make SSL requests?
  • Does your application supports SSL?
  • Does your web-service supports generating entity classes?
  • How can we identify whether the request is succeed or not?
  • Is there any time-out applied for web-service calls?
  • If we are not able to access your web-service url, what are all the things do we need to check, do you have any trouble-shooting document?
  • Do we need to do any kind of encryption while passing parameters to server?

Wednesday, October 2, 2013

CMS Best Practices

Don't include JQuery libs at component level

I have seen so many people who include JQuery libs at component level, the disadvantage of including at component level is for each and every component the system will make request to server to download JQuery libs and it may lead to page performance

Sometimes we get lot of undefined JavaScript errors because of loading multiple versions of JQuery libs

Solution:

Maintaining central location, I suggest create client libs and include at Basetemplate level, if new version comes just update client libs

In some scenarios the system will force you to include at component level, in such cases use JQuery.noConflict () option to avoid conflicts

Consider that the AEM also provides JQuery libs, some functionality which is depending on particular version of JQuery then download into your clientlibs; otherwise try to utilize OOTB JQuery Libs

Don’t deploy CSS or JS files in to production

Is it right approach deploying CSS, JavaScript files as part of deployment package in “Content Management System”?

Why,  because I have seen some people who came from traditional web development and no knowledge on CMS trying to deploy css and js files through package and finally mess up entire environment like overriding content of css and js files of content authors

How can we handle this situation, in any CMS you can find two types of content one is static content and another one is dynamic content

Dynamic content:

The content which you think it changes frequently by content author or admin’s need to be handled by content deployment or replication or page activation

Ex: Style sheets, images, text etc…

Normally, the content authors or site admin’s performs this action

Static content:

The content which you think it will not change in future need to be deployed as package such as style sheets, images, JavaScript files etc…
This is the developer job and the developer includes this content into package and deploys into a respective environment

Solution:

Don’t include css and js files in your deployment package, if you feel the content author is going to modify it, keep it in central location which can be accessible by content authors as well as developers

Normally in SharePoint you can do this by placing style sheets in style library and in CQ5 you can do this by putting in etc/designs folder

Don’t deploy configuration file in to the production environment

The general meaning of configuration file is to change settings of system at any time, but if you deploy your settings through deployment package that may override existing entries which has made by author and the system may go down

I strongly recommend don’t deploy your configuration settings through package which you feel it changes frequently

Always create I18n folder at site level not at component level

Don’t create I18n folder at component level, if you create your I18n folder at component level you may lose certain capabilities,

Suppose in future if you want to create new locale it is very difficult to check entire solution to identify I18n folders, which needs to convert into new locale and which may lead to maintenance issue and moreover there is a chance for duplicate entries

These duplicate entries may override existing ones and you need to spend lot of time to debug the issue

Always use locale copy while creating new website

Don’t create web site by simply creating pages in hierarchy manner, it is very difficult to implement MSM

The page nName needs to be in the format of or _, for example en, en_US, en_us, en_GB, en_gb.
•    The supported language code is lower-case, two-letter code as defined by ISO-639-1
•    The supported country code is lower-case or upper-case, two-letter code as defined by ISO 3166
 

Don’t iterate nodes, try to use Query Builder, if you are performing any search operation


Use Case:

The user shall be able to receive news based on subscribed opt-in's

The Taxonomy for news is

    Therapy area news                                         
    Oncology news       
       
While registering into site the end user select’s any of news taxonomy keyword either Therapy area or oncology, based on the selection the system will send respective news related email’s to the user

Here, don’t iterate each and every user node to find out opt-in, try to use query build to avoid performance impact

The sibling nodes should not exceed more than 2k

Keep in mind that the sibling nodes should not exceed more than 2k , under normal circumstances it is fine like simple creating and reading node’s but, if you are  performing any kind of search operation on these nodes this may impact on performance


Don't enable dispatcher level cache in lower environment only enable in production environment

Don’t enable dispatcher level cache in lower environment, if you are planning to do load testing, test it on lower environments either pre-prod or the environment which is similar to your production box

Always make sure the cache should be enabling in production box, initially this may impact on performance but while going forward the performance will increase

Before enabling cache in production box think about your application digital asset size, if the volume of size heavy, then it is better to enable cache ASAP

All environments should be in sink to avoid surprises

Always make sure that the environments should be in sink to avoid last minute surprises, I strongly recommend don’t directly work on production environment if you face some problems in production environment, first fix it in pre-prod environment , then test it in prod author and finally fix  it on publish environment

I recommend first deploy package in author and publish environment then replicate content from author to publish environment, before replication content check all configurations are fine or not

I have seen some people who directly work’s on publish environment and making entire system down, but this is not right approach


Don't do over architecture keep it simple


While developing components don’t do over architecture keep it as simple as possible, sometimes the over architecture may impact on performance, for simple components try to reduce layers


Don't store PII information in cookies


The Personal Identification Information is very important for any client, so don’t store PII information in cookies like user password, social security number etc,..

Try to leverage to use OOTB functionalities


Once you receive requirements from your client first check whether it is feasible with OOTB functionality or not, if it feasible then tries to use OOTB, if it is not feasible then only start developing custom components

Identify Data Model before start developing custom components

Choosing database is not an big difficult just compare relational database features with JavaContentRepository features

Ex :

For some of the requirements demands versioning capability, in such cases the relational database does not support versioning functionality, so we need to think about JCR

Avoid loading unnecessary dependencies in POM files


Try to avoid loading un-necessary jar files through POM entries, identify all required common jar files and create separate module and import that in to other modules

This we can achieve only through user education


Don’t refer untrusted resources


I have seen some components which is directly referring like below code


The best practice is download the .js file to your solution and refer it

Use CDN 


To achieve greater performance, if possible try to implement CDN, but this totally depends on client

Don’t hard code CDN server url while making image, video, file etc… it is very difficult to identify each and every link

Create separate Filter which parse each and every url, if it is a digital asset then redirect to CDN server to download that Digital Asset

Create custom error pages


For any website the custom error pages are mandatory like 500 server error, 404 not found etc… if we directly display as it is then this will directly effect on overall website credit

So always design custom error message pages and apply it


XSS

Cross site scripting enable attacker to inject maliculious code in to your system, so don’t forget to encode user inputs before submitting form

Use XSSFilter in CQ5 to validate User entered information

 Know the difference between Sessions

If you see Any CMS there are two sessions one is Admin session and another one is User Session

For read only operations use User sessions and if you are doing some edit and update operations then go with admin sessions

If the requirement is just reading items or nodes and display it on a page then just go with user session

Try to avoid using admin sessions , if  you are obtaining inputs from end user try to store into /content/usergenerated folder in content repository

For just reading nodes and properties use user session slingRequest.getResourceResolver().adaptTo(Session.class)

Thursday, September 12, 2013

Information Architecture Planning

Introduction

In the current digital-world the amount of data that the company’s are storing in their repositories’ and also dealing is growing day by day and it is very important for any company to efficiently use this data to make company success or failure, for any company the first priority is customer, if the customer is not able to find what he wants in company website then chances are high to loose them, the web sites which helps customers to find what they need quickly and easily will definitely win the customers

How can I describe you as Information Architecture?

I am an information architect and I am responsible for organizing huge amount of data in my company

What client is expecting?

You have received requirements from client to build a new website; you can develop this website with four pages and 10 components and deliver it, but what exactly the client is expecting out of these functionalities? What are the web site goals?

Identifying goals are very simple, assemble all the people who are responsible for making project success, it includes client or peers and ask them to provide order of importance to the content. Collect all suggestions and document everything share it with all stake holders to get approval

This article talks about how efficiently we can organize data

Why do we need to organize data?

Have you ever think why your company is investing lot of money and time on designing and developing intranet portals? What is the return on investment? Can we not design sites without wasting money and time?

The answer for all above questions is yes, we can do only, if you are ready to face below problems

The cost of losing customers:

The site looks very good but day by day, no of hits per day is going down and finally identified that the customer is not able to find what he wants in your portal

The cost of re-design:

How many dollars do us need to spend, if the site is poorly designed and not meeting your goals and need to re-design entire site
 
The cost of time:

The employee time is very important for any organization, how much time does your employee spends extra 5minutes per day struggling to find out what he wants? If you don’t have proper intranet portal

Assume that you are working for a big organization and everyday you get hundreds of mails, if you don’t organize your mails properly finally you end-up with wasting time on searching mails

The cost of maintenance:

How much money you spend to maintain technical people or third party providers (Savvies, Rack space etc…) to update single line in your page, there should be some kind of mechanism that the non-technical people also should be able to update the content

In WCM based portals every month we may expect hundreds of pages, how can we handle this situation if we don’t have proper architecture planning?

What is information architecture?

Information architecture talks about organizing your company’s information and website structure by categorizing content logically, priority basis and also ensures that the content is organized in proper structure in each section of web site

The best example for information architecture is Library, because the Library are well-structured and they follow subject oriented approaches, when you get into Library you can see all magazines are placed one side and books are placed other side, in books section you can find clear separation between each and every category, all fiction related information placed one side and all romantic related books are other side

When I was in child hood , I used to go to library to borrow some books for my grand-mother , the librarians used to keep display boards to easily identify books

by writing book information like author, book name etc…on the display board by seeing display boards, I could easily find out what I want

Here, the librarian plays information architecture role, first he will try to find out relationship between each and every books by following label of books or on author’s information and then put it in proper place

Also the librarian tries to find out what kind of information the readers are looking for by interacting with them, based on that he will have a call with library’s organizers and get approvals to purchase new books

Information architecture planning?

When it comes to website design the IA plays with content such as images, videos, files, documents, people, process etc…

Long time back, I was designed and implemented intranet portal for my company on SharePoint content management system while developing this, I used to interact with lot of people to find out what exactly they were expecting, to find out, we used to have regular meetings with respective department heads and create datasheet for every department and shared with respective POC’s as well as all stakeholders

We asked them to prioritize content and give ranking to every user story or paragraph in the datasheet but, sometimes if the client is poor client then we may need to give suggestions based on experience to the client on prioritization of content

Once, we got all the datasheets from respective managers or POC’s , we used to prioritize all and once we got some logical conclusion by analyzing content and identifying audience, we have designed draft version of sitemap and wire-frames to showcase to leads how the website looks like

Identifying the stake-holders?

As an Information Architect you need to identify and clarify all stake holder goals, the stake-holders are the people who define the depth and scope of project, identifying the audiences, determining sensitivity of information, giving approvals on each phase of development and giving functional clarification

Roles include: Senior Managers who give approval for every phase
Content owners, end users, development leads, respective department heads etc…

What are goals?

The world is changing day by day and people come up with new strategy’s to sustain in current market, for that they will ask you to create new site or migrate current site to either in content management system or some other platform

As an information architect you need to find out why they are moving to new platform? To
  • Increase sales
  • Attract more audience
  • Reduce phone calls by providing online support
  • Increase brand value
Getting information from stake-holders is not one day job. The customer’s priorities changes day by day, so you need to have regular meetings with them and try to get what exactly they are expecting and also to get approvals on functional clarifications on certain phases

Target Audience:

The audiences are people who visit your website
  • People who sells items in your site
  • People who purchase items through your site
  • People who maintains content of site
  • Venture capitalist who wants to know about your company etc…
As an IA you need to identify whom the client is targeting who are the primary audience and secondary audience

There is an ecommerce portal which sells products through online; their target audience is men’s and they get few females customers also, but the client says that they have strong male audience , so while designing our website we need to keep this in mind and we need to design our site which targets men’s as primary

Content analysis

Don’t wait for complete information, first start analyzing the content which you already have, interact with your stake holders and decide what should be included in a new site, if you are migrating content from existing site, then analyze the existing content management system, sitemap, total pages and find out what needs to be include and excluded, keep the content that will be only useful to end users, don’t put un necessary information which the end-user really does not want

Next, try to imagine end-user perceptive, once he/she enters into your web site, what you are show casing to them based on client goals is the matter

Normally, digital marketing sites displays top 10 articles or products and special offers etc...On home page

Organizing content:

Once the analysis is completed next step is organizing content, we need to identify the relation between content and also relation between one page to other , if you feel there is a similar content, you can make it as separate group and provide meaning full name, later we need to design navigation structure based on these groups

Making logical groups are very important thing, because while going forward we will apply metadata and labels on this

Sitemap:

Before designing sitemap we should try to understand what are all the functionalities, features and what kind of content are going to have in website



Monday, November 19, 2012

Report Suites Architecture


I have seen lot of people started thinking about development, when we ask them to integrate site catalyst, Google analytic or urchin in their site, people are immediately jumping into code like how to call JavaScript to record data into site catalyst and how to retrieve site catalyst data etc… but all these things are simple, we can get lot of examples when we read respective SDK’s, but there is another area where we need to put actual attention

What is Report Suite in Site Catalyst?

Every day the omniture system captures thousand of records from web application or website which are integrated with ominture, where exactly all these information stores? These information stores in report suite of site catalyst and we need to pass reportsuiteid for every request

Is one report suite sufficient for entire application?

Before creating new report suite we need to identify what kind of information the client wants to track and what kind of reports he/she wants to generate, without having all these required information in your hand and if you blindly starts then you will be definitely in big mess

Because the report suite supports only 100 events, 75 Traffic variables and 75 conversion variables, what if we want track more than 100 events and if we want to create 76 Traffic variable ?

See the below image,



if we create single report suite for entire Amazon site, then it is very difficult to maintain, if India location head wants to see last one month reports of “Amazon India site” then to generate this report is difficult, we need to apply filters, sometimes the data accuracy problem may occur, and sometimes the events, variables may cross the limit and also we are missing modularization concept here

The solution for this is create new report suite for every location, so that the location head can easily generate reports,  sometimes we may need aggregate data across all locations, we can create global report suite which contain all locations information 


Note : creating report suites is totally depends on how you organize your data , don't forget to get complete information from your client and also the information architects or CMS experts can help on this


Saturday, November 17, 2012

Is it right approach deploying CSS, JavaScript files as part of deployment package in “Content Management System”?


Is it right approach deploying CSS, JavaScript files as part of deployment package in “Content Management System”?

Why,  because I have seen some people who came from traditional web development and no knowledge on CMS trying to deploy css and js files through package and finally mess up entire environment like overriding content of css and js files of content authors

How can we handle this situation, in any cms you can find two types of content one is static content and another one is dynamic content

Dynamic content:

The content which you think it changes frequently need to be handled by content deployment or replication or page activation

Ex: Style sheets, images, text etc…

Normally, the content authors or site admin’s performs this action

Static content:

The content which you think it will not change in future need to be deployed as package such as style sheets, images, JavaScript files etc…
This is the developer job and the developer includes this content into package and deploys into a respective environment

Solution:

You can solve this using several ways one is creating two sets of css files one is for static content and another one is for dynamic content so that if you deploy new package in your CMS environment that t will not disturb dynamic content

Second one is don’t include css and js files in your deployment package keep it in central location which can be accessible by content authors as well as developers
Normally in SharePoint you can do this by placing style sheets in style libray and in CQ5 you can do this by putting in etc/designs folder

Monday, November 5, 2012

Reading data from site catalyst through CQ5

In this article I am going to explain how to read data from site catalyst and display it on CQ5 components

REST api’s :

The omniture exposes REST api to read/write data from site catalyst data source, REST is a lightweight protocol and alternative to Web Services (SOAP, WSDL, etc.), in this I am not going to explain REST based concepts

CQ5:

To connect to site catalyst data source the cq5 has provided cq-analytics.jar file, this jar file is just wrapper of omniture REST api it provide different methods to read data from omniture, using this we can successfully read data from site catalyst from CQ5 environment


POM of cq-analytics jar :

<dependency>
           <groupId>com.day.cq</groupId>
     <artifactId>cq-analytics</artifactId>
           <version>5.4.4</version>
           <scope>provided</scope>
      </dependency>

Code :

The cq5 is provided “SitecatalystWebservice” to connect to site catalyst and there is one more class “Account” we use this entity class to pass account information to site catalyst web service

Account acc = new Account (true, companyName, userName, secret, server);
 
SitecatalystWebservice active = sling.getService(SitecatalystWebservice.class);

String str = active.getReportSuites(acc);

String reports = active.getSuccessEvents(acc,”reportSuiteId”)

The above code returns all success events which are created for “reportSuiteId”

CompanyName :

The name is company name which we use to connect to CQ5 omniture site catalyst

Username :

Omniture site catalyst username

Secret:

The secret key is unique for every user we can find this by navigating   “Omniture Site Catalyst”  -> Admin -> Admin Console -> Company

Server :

This is datacenter url we can find this in omniture admin console

Monday, August 13, 2012

Bug in SharePoint 2010

I have created "Survey" activity feed using sharepoint object model but when I try to remove the same I am getting Not Implemented exception

Error Message :

"The method or operation is not implemented."

Code :

removeType = app.ActivityTypes["Survey"];
m_ActivityManager.ActivityApplications[app.ApplicationId].Remove();
//getting The method or operation is not implemented.


if (removeType != null)
{
app.ActivityTypes.Remove(removeType); //getting The method or operation is not implemented.

removeType.ActivityTypeNameLocStringResourceFile = Survey_RFile;
removeType.ActivityTypeNameLocStringName = "Srvey _Feed_Display";
removeType.IsPublished = true;
removeType.IsConsolidated = true;
removeType.Commit();
removeType.Refresh(true);
}

Problem :

Problem is the Remove() method is not implemented

app.ActivityTypes.Remove(removeType);

Resoultion :

Then how can we Remove this?

We can remove the same through sql query but that is not supported by microsoft, if you still want to go ahead and remove you can use below query's

delete [ActivityTemplate] where activitytemplateid > 18
delete [ActivityType] where ApplicationID > 5
delete [ActivityApplication] where ApplicationID > 19

WTF...Do we need to wait until the microsoft releases service pack for this?

Tuesday, June 12, 2012

CQ5 : Creating new page and adding content

In this article, I am going to explain how to create new page and content using SlingHttpRequest Object

<%@page import="com.day.cq.dam.api.Rendition"%>
<%@page import="com.day.cq.dam.api.Asset"%>
<%@page import="org.apache.sling.api.SlingHttpServletRequest"%>
<%@include file="/libs/foundation/global.jsp"%>
<%@page import="org.apache.sling.api.resource.ResourceResolver"%>

<%@page import="com.day.cq.wcm.api.Template"%>

<%
ResourceResolver resolverPage = slingRequest.getResourceResolver();
Resource resPage = resolverPage.getResource("/content/geometrixx");


We are going to read page class, so we need to adapt our Resource to Page.class

Page geoPages = resPage.adaptTo(Page.class);
if(geoPages!=null) {
Resource res2 = resolverPage.getResource(geoPages.getPath());

//The PageManager class helps us to create new pages

PageManager pm = geoPages.getPageManager();

if(pm!=null) {
pm.create("/content/","MspBoxhomeName","/apps/mspbox/templates/contentpage","MspBoxTitle");
Page newPage = pm.getPage("/content/MspHome/");
if(newPage != null)
{
Node newNode = newPage.adaptTo(Node.class);
Node cont = newNode.getNode("jcr:content");
if(newNode != null)
{
cont.addNode("par").setProperty("sling:resourceType","foundation/components/parsys");
Node parNode = cont.getNode("par");
parNode.addNode("image");
Node imageNode = parNode.getNode("image");
imageNode.setProperty("sling:resourceType","foundation/components/image");
imageNode.setProperty("fileReference","/content/dam/geometrixx/shapes/tri_equilateral.png");
parNode.addNode("text");
Node textNode = parNode.getNode("text");
textNode.setProperty("sling:resourceType","foundation/components/text");
textNode.setProperty("text","<p>With at least two equal sides, isoceles is sometimes equilateral and visa versa. Or as the ancient Greeks would say, iso skelos!</p><p></p>");
cont.save();

}
}
}
}
%>

Monday, June 11, 2012

CQ5 : Reading DAM assets

<%@page import="com.day.cq.dam.api.Rendition"%>
<%@page import="com.day.cq.dam.api.Asset"%>
<%@page import="org.apache.sling.api.SlingHttpServletRequest"%>
<%@include file="/libs/foundation/global.jsp"%>

<%@page import="org.apache.sling.api.resource.ResourceResolver"%>

<%

ResourceResolver resolver = slingRequest.getResourceResolver();
Resource res = resolver.getResource("/content/dam/geometrixx/movies");

Node rootNode = res.adaptTo(Node.class);
if(rootNode!=null) {

NodeIterator children = rootNode.getNodes();
while (children.hasNext()) {
Node node = children.nextNode();
if(node != null) {
Resource res1 = resolver.getResource(node.getPath());
Asset as = res1.adaptTo(Asset.class);
String src = "";
String name = "";
String rel = "";
if(as != null) {

Rendition ren = as.getRendition("cq5dam.thumbnail.140.100.png");
src = ren.getPath();
name = as.getName();
rel = as.getPath();
}
out.print("<ul>");
out.print("<li rel=" + rel + "title=" + name + ">");
out.print("<img src=" + src + "></img>");
out.print("</li>");
out.print("</ul>");
}
}
};

%>

CQ5 Reading Node Properties

In CQ5 everything stores in the form of content ( Nodes and Properties ), but while reading content from repository the apache sling framework assumes this is a Resource.Because the sling follows REST based architecture

In this article I am going to explore how to read properties of a Node


<%@page import="org.apache.sling.api.SlingHttpServletRequest"%>
<%@include file="/libs/foundation/global.jsp"%>
<%@page import="org.apache.sling.api.resource.ResourceResolver"%>
<%

By using CRXDE I am going to create component called "PropertyReader" and going to read properties of this component

In CQ5 everything stores in the form of content that means "PropertyReader" component also exists in content repository

the below code will send a request to server and tries to return Resource object if it does not find any resource then it returns Null

We need to use SlingHttpServletRequest object to communicate with CQ5 CRX, here the slingRequest is avariable which is already defined in global.jsp file

ResourceResolver resolver = slingRequest.getResourceResolver();
Resource res = resolver.getResource("/apps/mspbox/components/PropertyReader");

If needed you can adapt a Sling Resource to a JCR Node like below code Node.class, if you are going to read DAM Assets then you need to use Asset.class

Code :

<%@page import="org.apache.sling.api.SlingHttpServletRequest"%>
<%@include file="/libs/foundation/global.jsp"%>
<%@page import="org.apache.sling.api.resource.ResourceResolver"%>
<%

ResourceResolver resolver = slingRequest.getResourceResolver();
Resource res = resolver.getResource("/apps/mspbox/components/PropertyReader");


Accessing a Property :

Node rootNode = res.adaptTo(Node.class);
ValueMap prop = res.adaptTo(ValueMap.class);
String group = prop.get("componentGroup", (String) null);
out.print(group);

Reading all properties :

if(rootNode!=null) {
NodeIterator children = rootNode.getNodes();
while (children.hasNext()) {
Node node = children.nextNode();
if(node != null) {
PropertyIterator pi= node.getProperties();
out.print("<table>");
while (pi.hasNext()) {
Property p = pi.nextProperty();
out.print("<tr><td>");
out.print(p.getName());
out.print(p.getPath());
out.print("</td></tr>");
}
out.print("</table>");
}
}
};
%>

OUTPUT :

General
cq:layout
jcr:createdBy
jcr:created
cq:dialogMode
jcr:primaryType

Friday, March 25, 2011

Custom 404 Page not found error page - SharePoint

SharePoint is a content management system, so people creates thousands of pages and at the same time deletes hundreds or thousands of pages, if you hit one of page in deleted pages then you will get page not found error (blue and white screen page), but the problem is the error page is not user friendly, you will not find any redirection link, so how will you solve this problem?

Usually, we apply 404 page at IIS virtual directory level, but how will you apply same for SharePoint website?

In SharePoint when we create web application using SharePoint central administration internally that will create a virtual directory under IIS, so now our job is so easy, just check below code, the SPWebApplication refers to Virtual Directory

Create a feature receiver and add below code in to FeatureActivated method

See, the web application class contains a property called “FileNotFoundPage” just apply your custom 404 page to that property

SPSite curSiteColl = properties.Feature.Parent as SPSite;
System.Uri webApplicationUri = new Uri(curSiteColl.Url);
SPWebApplication webApplication = SPWebApplication.Lookup(webApplicationUri);
webApplication.FileNotFoundPage = "404ErrorPage.html";
webApplication.Update();

The property accepts only HTML page, so we need to assign HTML page and then using Java script redirect to our custom .aspx page

<html>
<head>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=utf-8" />
<meta HTTP-EQUIV="Expires" content="0" />
<script language="javascript" src="/_layouts/1033/init.js"></script>
<script language="javascript" src="/_layouts/1033/core.js"></script>
<script language="javascript">
var requestedUrl = escapeProperly(window.location.href);
STSNavigate("/_layouts/ErrorPages/404ErrorPage.aspx?oldUrl=" + requestedUrl);
</script>
</head>
<body>
</body>
</html>

Now, open the 404ErrorPage.aspx page and add whatever message you want under place holder main section

<asp:Content ID="mainContent" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<table>
<tr>
<td class="ErrorPageTitle" >
<span class="ErrorPageTitle1">Page Not Found</span>
</td>

</tr>
<tr>
<td> <span class="ErrorPageMsg1">The page you requested could not be found. Use this link<http://mspbox.blogspot.com> to redirect to home page </td>
</tr>
</table>
</asp:Content>

Thursday, February 24, 2011

Custom error message in SharePoint 2010 + Feature Receiver

In SharePoint 2007 there was no way to redirect to custom error page when you use event receivers, if you try also it redirects to default out of the box blue-white error page

But in SharePoint 2010 there are some properties by using this you can redirect to custom error page

public override void ItemAdding(SPItemEventProperties properties)

{
base.ItemAdding(properties);
string tite = properties.AfterProperties[“title”].ToString();
if(tite.Contains(“RSM”))
{
properties.Cancel = true;
properties.Status = SPEventRecieverStatus.CancelWithRedirectUrl;
Properties.RedirectUrl = “/_layouts/CustomError.aspx?errormessage=bang...don't use RSM...I hate RSM”;
}
}

Limitations.

This works only for synchorounous events like Itemadding, deleting etc...
Works only for browser based clients not with outlook.

Tuesday, February 15, 2011

Language pack probem Spanish(United States)

Today, we started developing new locale for our existing site that is Hispanic locale for United States, but the main problem which we found is Microsoft does not provide language pack for Hispanic (United States) the solution for this we have chosen (Spanish) Mexico language pack (es-MX)under regional settings of site collection settings of site because the Spanish (Mexico) and Spanish (United States) are almost same

But, before start developing new locale with above approach the resource files should be in the form of .es-MX.resx not .es-US.resx because you have chosen (Spanish)Mexico language pack (es-MX) under regional settings of site collection

Tuesday, February 1, 2011

Planning Content Type Hubs in SP2010

when you are developing enterprise application for large organization some fields are common across all brands such as brand name, brand logo, SEO title, SEO description etc..

How will you handle this common fields across farms?

Scenario (P&G only for reference)

Assume that we are designing architecture for P&G products, normally P&G has lot of products (Pantene, Olay, pampers etc...)but, all these products have some common fields such as Product logo, product name, SEO title, SEO description etc... How will you handle this?

SharePoint 2007

In SharePoint 2007 usually what we do? we go and create separate content type for this called brand content type and deploy this into site collection but, here the problem is we need to go to each and every web application and install site content type feature , there is no central location to place common fields, in future if you want to update particular column, you have to go to each and every web application and update

SharePoint 2010

In SharePoint 2010 there is a new concept called Content Type Hubs, through this you can manage all common fields centrally and publish it to the other web applications, so in 2010 the other web applications can subscribe these content types and pull down the published content types from the CTH and also can get updates when ever changes happened in published content types

Here, mainly you need to concentrate on three things

Site collection to host the content types and act as a Content Type Hubs

Managed metadata service application( to expose content type hub to each and every web application)

Web applications ( to subscribe content type hubs)

Advantages

No need of going to each and every web application and installing the content types and if you want to do updates on particular content type you can simply do it on Content Type Hubs and push it down, so managing the content types easy

In reality the content types changes frequently like adding new fields or creating new content type etc... It's easier to coordinate this from a single location and make sure that xml files are correctly set up across all web applications/farms.