Monday, November 18, 2013

Bing Integration with Jquery

Bing provides an interesting to alternative to Google maps for integration and if you want to integrate using Jquery. Please copy paste the example in a .html file and test it with a zip-code or city.

The key that I have in the example below will expire in 90 days so please use the below link to create a new key:
http://www.microsoft.com/maps/

Copy the below section after this line in a .html  file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Use Bing Maps REST Services with jQuery to build an autocomplete box and find a location dynamically</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js" type="text/javascript"></script>
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .ui-autocomplete-loading
        {
            background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
        }
        #searchBox
        {
            width: 25em;
        }
    </style>

    <script type="text/javascript">
        $(document).ready(function () {
            $("#searchBox").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "http://dev.virtualearth.net/REST/v1/Locations",
                        dataType: "jsonp",
                        data: {
                            key: "AlJKmxkiJg2u0CIDEyaTM6CWC9jQ_q1pf4_xzxPdEJoaT_KsgKRy73ksHyl24oe5",
                            q: request.term
                        },
                        jsonp: "jsonp",
                        success: function (data) {
                            var result = data.resourceSets[0];
                            if (result) {
                                if (result.estimatedTotal > 0) {
                                    response($.map(result.resources, function (item) {
                                        return {
                                            data: item,
                                            label: item.name + ' (' + item.address.countryRegion + ')',
                                            value: item.name
                                        }
                                    }));
                                }
                            }
                        }
                    });
                },
                minLength: 1,
                change: function (event, ui) {
                    if (!ui.item)
                        $("#searchBox").val('');
                },
                select: function (event, ui) {
                    displaySelectedItem(ui.item.data);
                }
            });
        });

        function displaySelectedItem(item) {
            $("#searchResult").empty().append('Result: ' + item.name).append(' (Latitude: ' + item.point.coordinates[0] + ' Longitude: ' + item.point.coordinates[1] + ')');
        }
    </script>
</head>
<body>
    <div>
        <div class="ui-widget">
            <label for="searchBox">
                Search:
            </label>
            <input id="searchBox" />
        </div>
        <div id="searchResult" class="ui-widget" style="margin-top: 1em;">
        </div>
    </div>
</body>
</html>

SQL | Joins Explained | Using Commerce tables.

This example below outlines lot of SQL Join functionality that we use in a lot of queries in our codes. The below example use commerce tables to demonstrate the joins functionality.

--EXAMPLE 2 OUTER JOIN Table XORDERITEMS:
CREATE TABLE XCATENTRY (catentry_id NUMBER,partnumber varchar2(255), lastupdate timestamp);

--2. Data insertion into table
insert into  XCATENTRY values (11,'DSC_1',sysdate-800);
insert into  XCATENTRY values (33,'DSC_3',sysdate-700);
insert into  XCATENTRY values (1010,'DSC_10',sysdate-500);
insert into  XCATENTRY values (1111,'DSC_11',sysdate-300);

output::
Tables Orders:
ORDERS_ID    PARTNUMBER    STATUS
-----------------------------------------
1        DSC_1    P
2        DSC_2    Y
3        DSC_3    c
4        DSC_4    c
5        DSC_5    c
6        DSC_4    P
7        DSC_3    y
8        DSC_7    c
9        DSC_8    P
10        DSC_9    P

Tables Catentry:
CATENTRY_ID   PARTNUMBER  LASTUPDATE
--------------------------------------------
11        DSC_1    29-08-2011 13:53:21.000000
33        DSC_3    07-12-2011 13:53:21.000000
1010        DSC_10    24-06-2012 13:53:21.000000
1111        DSC_11    10-01-2013 13:53:21.000000

Query: For fetching all partnumber from left table along with matching partnumber */

--Query 1
select o.partnumber from XORDERITEMS o left outer join xcatentry c on o.partnumber = c.partnumber;

--Query 2
select o.partnumber from XORDERITEMS o , xcatentry c where o.partnumber = c.partnumber(+);

output:
PARTNUMBER
DSC_1
DSC_3
DSC_3
DSC_4
DSC_4
DSC_8
DSC_9
DSC_7
DSC_5
DSC_2

--Query: For fetching all partnumber from right table along with matching partnumber

--QUERY
select distinct c.* from XORDERITEMS o right outer join xcatentry c on o.partnumber = c.partnumber;

--ALTERNATE QUERY:
select distinct c.* from XORDERITEMS o , xcatentry c where o.partnumber(+) = c.partnumber;

Result:
CATENTRY_ID    PARTNUMBER    LASTUPDATE
11    DSC_1    29-08-2011 13:53:21.000000
33    DSC_3    07-12-2011 13:53:21.000000
1010    DSC_10    24-06-2012 13:53:21.000000
1111    DSC_11    10-01-2013 13:53:21.000000

-- Query: For fetching all partnumber from left and right table along with matching partnumber

select o.*,c.* from XORDERITEMS o full outer  join xcatentry c on o.partnumber = c.partnumber;


ORDERS_ID    PARTNUMBER    STATUS    CATENTRY_ID    PARTNUMBER_1    LASTUPDATE
1    DSC_1    P    11    DSC_1    29-08-2011 13:53:21.000000
7    DSC_3    y    33    DSC_3    07-12-2011 13:53:21.000000
3    DSC_3    c    33    DSC_3    07-12-2011 13:53:21.000000
6    DSC_4    P
4    DSC_4    c
9    DSC_8    P
10    DSC_9    P
8    DSC_7    c
5    DSC_5    c
2    DSC_2    Y
            1111    DSC_11    10-01-2013 13:53:21.000000
            1010    DSC_10    24-06-2012 13:53:21.000000


--EXAMPLE 3 Query with date range
--Query 1: select partnumber of year 2011
select partnumber from xcatentry where to_date(to_char ( lastupdate,'DD/MM/YYYY'),'DD/MM/YYYY') BETWEEN TO_DATE('01/01/2011','DD/MM/YYYY') AND TO_DATE('31/12/2011','DD/MM/YYYY')

output:
PARTNUMBER
DSC_1
DSC_3

--Query 2: select partnumber of year 2011 and 2012 but not in orders tables
select partnumber from xcatentry c where to_date(to_char ( c.lastupdate,'DD/MM/YYYY'),'DD/MM/YYYY') BETWEEN TO_DATE('01/01/2011','DD/MM/YYYY') AND TO_DATE('31/12/2012','DD/MM/YYYY')
and not exists  (select 1 from XORDERITEMS o where o.partnumber = c.partnumber)

RESULTS:
PARTNUMBER
DSC_10

--EXAMPLE 4  Query : Count the status
select status,count(*) from orders group by status order by status;

output:
STATUS    COUNT(*)
P          4
Y          1
c          4
y          1

Tables XORDERITEMS:
ORDERS_ID         PARTNUMBER   STATUS
-----------------------------------------
1                              DSC_1   P
2                              DSC_2   Y
3                              DSC_3   c
4                              DSC_4   c
5                              DSC_5   c
6                              DSC_4   P
7                              DSC_3   y
8                              DSC_7   c
9                              DSC_8   P
10                           DSC_9   P

Tables XCatentry:
CATENTRY_ID   PARTNUMBER  LASTUPDATE
--------------------------------------------
11                           DSC_1   29-08-2011 13:53:21.000000
33                           DSC_3   07-12-2011 13:53:21.000000
1010                       DSC_10 24-06-2012 13:53:21.000000
1111                       DSC_11 10-01-2013 13:53:21.000000

Tables Xcatentdesc:
CATENTRY_ID    LANGUAGE_ID SHORTDESCRIPTION
11           -1            DSC_1_DESCRIPTION
33           -1            DSC_3_DESCRIPTION
1010       -1            DSC_10_DESCRIPTION
1111       -1            DSC_11_DESCRIPTION

Query 1: Example: inner join - two table
select o.orders_id, o.partnumber,c.lastupdate from Xorders o inner join Xcatentry c on o.partnumber= c.partnumber;
o/p:
ORDERS_ID         PARTNUMBER   LASTUPDATE
1              DSC_1   8/29/2011 1:53:21.000000 PM
3              DSC_3   12/7/2011 1:53:21.000000 PM
7              DSC_3   12/7/2011 1:53:21.000000 PM

Query 2: Example: inner join - three table
select o.orders_id, o.partnumber,cd.shortdescription from Xorders o inner join Xcatentry c on o.partnumber= c.partnumber inner join Xcatentdesc cd on c.catentry_id
= cd.catentry_id;

output:
ORDERS_ID         PARTNUMBER   SHORTDESCRIPTION
1              DSC_1   DSC_1_DESCRIPTION
3              DSC_3   DSC_3_DESCRIPTION
7              DSC_3   DSC_3_DESCRIPTION


Friday, November 8, 2013

SQL | Analysis and Query to find items that are not part of input list

I will have a few SQL series blogs and as a WCS developer, I feel it is very important to have good SQL skills.

--Exampple . Find all part numbers that are not found in orders table from the list (DSC_1,DSC_3, DSC_10, DSC_11)  in the XORDERITEMS table below.
Result: DSC_10, DSC_11

--1. Table creation:

CREATE TABLE XORDERITEMS (orders_id NUMBER,partnumber varchar2(255), status varchar2(1)) NOLOGGING;

--2. Data insertion into table
insert into /*+ APPEND */  XORDERITEMS values (1,'DSC_1','P');
insert into /*+ APPEND */  XORDERITEMS values (2,'DSC_2','Y');
insert into /*+ APPEND */  XORDERITEMS values (3,'DSC_3','c');
insert into /*+ APPEND */  XORDERITEMS values (4,'DSC_4','c');
insert into /*+ APPEND */  XORDERITEMS values (5,'DSC_5','c');
insert into /*+ APPEND */  XORDERITEMS values (6,'DSC_4','P');
insert into /*+ APPEND */  XORDERITEMS values (7,'DSC_3','y');
insert into /*+ APPEND */  XORDERITEMS values (8,'DSC_7','c');
insert into /*+ APPEND */  XORDERITEMS values (9,'DSC_8','P');
insert into /*+ APPEND */  XORDERITEMS values (10,'DSC_9','P');

--two alternates to fetch the above result.
--Query-1
select pno partnumber from
(SELECT TRIM(SUBSTR ( partnumber , INSTR (partnumber, ',', 1, level ) + 1 , INSTR (partnumber, ',', 1, level+1 ) - INSTR (partnumber, ',', 1, level) -1)) pno
FROM ( SELECT ','||'DSC_1,DSC_3,DSC_10,DSC_11'||',' AS partnumber FROM dual )
CONNECT BY level <= LENGTH(partnumber)-LENGTH(REPLACE(partnumber,',',''))-1 )
where pno not in (select partnumber from XORDERITEMS);

--Alternate Query
select pno partnumber from
(select 'DSC_1' pno from dual
union
select 'DSC_3' pno from dual
union
select 'DSC_10' pno from dual
union
select 'DSC_11' pno from dual)
where pno not in (select partnumber from XORDERITEMS);


Thursday, October 10, 2013

Tax customizations to update tax from third party !!

While customizing tax integration with third party, it is important to understand the end points provided by commerce to customize.
Please find below out of box commerce tables and commands that needs to be customized.


INSERT INTO CALMETHOD (CALMETHOD_ID, STOREENT_ID, CALUSAGE_ID, TASKNAME, 
DESCRIPTION, SUBCLASS, NAME) VALUES ((select coalesce((min(calmethod_id)-1),1)
from calmethod), 10701 , -3,'com.custom.commerce.order.calculation.ApplyCalculationUsageCmd', 'custommethod for calculation sales taxes', 12, 'ApplyCalculationUsageSalesTax')

update stencalusg SET CALMETHOD_ID_APP = 
(SELECT CALMETHOD_ID FROM CALMETHOD WHERE TASKNAME = 'com. custom .commerce.order.calculation.ApplyCalculationUsageCmd'
AND STOREENT_ID = 10701 AND CALUSAGE_ID = -3) and calusage_id=-3

insert into CMDREG (STOREENT_ID, INTERFACENAME, DESCRIPTION, CLASSNAME, PROPERTIES, LASTUPDATE, TARGET) values 
(0,'com.custom.commerce.order.calculation.ApplyCalculationUsageCmd','Sales Tax calculation usage for third-party tax 
providers','com.custom.commerce.order.calculation.ApplyCalculationUsageSalesTaxCmdImpl',null,null,'Local')

//out of the box command required to be extended.
public class ApplyCalculationUsageSalesTaxCmdImpl extends ApplyCalculationUsageCmdImpl implements com.custom.commerce.order.calculation.ApplyCalculationUsageCmd{

    public static final String CLASSNAME = ApplyCalculationUsageSalesTaxCmdImpl.class.getName();

    private static Logger LOGGER = Logger.getLogger(CLASSNAME);

   public void performExecute()

    throws ECException
   {
       String methodName = "performExecute";
       if (LoggingHelper.isEntryExitTraceEnabled(LOGGER)) {
           LOGGER.entering(CLASSNAME, methodName);
       }
    
     //get tax from Third party
       BigDecimal orderTax = new BigDecimal(100.00);
       
       Item[] items = super.getItems();
       // set on first order item
       for (int i = 0; i < 1; i++) {
            items[i].setSalesTaxTotal(orderTax);
            items[i].commit();
       }
       if (LoggingHelper.isEntryExitTraceEnabled(LOGGER)) {
           LOGGER.exiting(CLASSNAME, methodName);
       }
   }   


Wednesday, October 9, 2013

Creating Assets in management center and displaying in front end.


Steps in CMC:
1. Go to Assets menu and select the appropriate stores.
2. Create a file, make sure to give a exten (.pdf, jpg), even in the name.
3. Go to Attachment selection inside Asset Menu, Create a attachment, the name given in attachment, can be used in the front end for links.
4. Go to Catalog menu and select a store and create a category inside master catalog categories and reference the attachments created in step 3.

Extended CategoryDataBean:
public void populate() throws Exception{
Enumeration categoriesEnum=CatalogGroupCache.findByIdentifierAndStore(this.getCatIdentifier(),this.getCommandContext().getStoreId());
if (categoriesEnum.hasMoreElements()) {
CachedCatalogGroupAccessBean cgpCached= (CachedCatalogGroupAccessBean) categoriesEnum.nextElement();
catGroupId=cgpCached.getCatalogGroupReferenceNumber();
}
super.setCategoryId(catGroupId);
super.populate(); }

JSP Code:

<wcbase:useBean id="documentsCategory" classname="com.custom.commerce.catalog.beans.EXTCategoryDataBean" >
<c:set property="catIdentifier" value="documents" target="${documentsCategory}" />
</wcbase:useBean>

<c:set var="allAttachemnts" value="${mediaDownloadsCategory.allAttachments}" />
<c:if test="${!empty allAttachemnts}">
<c:forEach items="${allAttachemnts}" var="attachmentDB" varStatus="status">
<c:forEach items="${attachmentDB.attachmentAssets}" var="attachmentAssets" varStatus="status">
<c:if test="${fn:indexOf(attachmentAssets.attachmentAssetPath,'PDF_') > 0 }">
<a href="${hostPath}${attachmentAssets.objectPath}${attachmentAssets.attachmentAssetPath}"><c:out value="${attachmentDB.fileName}"/></a>
</c:if>
<c:if test="${fn:indexOf(attachmentAssets.attachmentAssetPath,'DOCUMENT_') > 0 }">
<div class="image"><img border="0" src="${hostPath}${attachmentAssets.objectPath}${attachmentAssets.attachmentAssetPath}"/></div>
</c:if>
</c:forEach>
</br>
</c:forEach>
</c:if>


Content Assets upload settings in wc-server.xml: Can change the number of files and the interval.

<ManagedFileUpdateEARConfiguration display="false">
        <ContentManagedFileEARUpdate Implementation="com.ibm.commerce.filepublish.util.ContentManagedFileEARUpdateImpl"/>
        <ContentManagedFileHandler Implementation="com.ibm.commerce.filepublish.util.ContentManagedFileHandlerImpl"/>
        <ProductionServerInformation applicationName="WC_demo"/>
        <ModuleInformation moduleName="Stores.war"/>
        <EvaluationCriteria minNumOfFilesForUpdate="4" minSecFromLastUpload="300"/>
    </ManagedFileUpdateEARConfiguration>


CoreMetrics | basics !!

Coremetrics provides web analytics and the other big competitor in this space is Omniture. The analytics integration is provided using Javascript. In Websphere commerce there is a tighter integration in the form of tags that are provided out of the box and  coremetrics reports are provided in management center in newer versions of WCS and older versions still need to use coremetrics site to view reports.

  1. Create a coremetrics account.
  2. Update WC\xml\config\bi\biConfig.xml with correct configuration for coremetrics configuration. clientId is the contract ID is usually one for test environments and 1 for production and ssoKey is generated from Coremetrics support.
  3. Configuration in wc-server.xml 
    • <configuration
                    cmClientID=""
                    password=""
                    serviceURL="https://wscreceiver.coremetrics.com/Receiver/sendEventData"
                    sslKeyPassphrase="WebAS"
                    sslKeyStore="/usr/WebSphere/AppServer/profiles/demo/etc/DummyServerKeyFile.jks"
                    sslTrustPassphrase="WebAS"
                    sslTrustStore="/usr/WebSphere/AppServer/profiles/demo/etc/DummyServerTrustFile.jks"
                    transmitClassName="com.ibm.commerce.bi.events.transmit.CMWebServiceTransmitter"
                    transmitEnabled="false" username=""/&gt
  4. Access Coremetrics reports
    • Open a Web browser to the following URL: https://welcome.coremetrics.com
    • Log in using your Client ID, username, and password. 
    • Starting V7, Feature Pack 3. We can also view reports directly from Management Center using links in the Catalogs, Marketing and Promotions tool.
    There are several tags for CoreMetrics, one example is pageView and most commonly used is cm

    Include the tag library in the pages
    <%@ taglib uri="http://commerce.ibm.com/coremetrics"  prefix="cm" %>

    PageView Tag: Most commonly used tag to track pages.

        <flow:ifEnabled feature="Analytics">
            <c:choose>
                <c:when test="${isCSR}">
                    <cm:pageview pagename="${storeCountryCode}:SEARCH PAGE" extraparms="YES" />
                </c:when>
                <c:otherwise>
                    <cm:pageview pagename="${storeCountryCode}:
    SEARCH PAGE" extraparms="NO" />
                </c:otherwise>
            </c:choose>
        </flow:ifEnabled>


    Conversion tag: For Ajax calls

    <cm:conversion eventId="${WCParam.eventId}" category="WISHLIST" actionType="2" points="10" returnAsJSON="true"/>

    campurl Tag: Mostly for static pages

                                  <cm:campurl espotData="${marketingSpotDatas}" id="clickInfoCommand" url="${clickInfoURLForAnalytics}" 

    References: More tags
    http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/topic/com.ibm.commerce.Coremetrics.doc/refs/rmttagsinstorejsps.htm
    Web 2.0 integration:
    http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/topic/com.ibm.commerce.Coremetrics.doc/concepts/cmtweb20intro.htm



    Wednesday, July 31, 2013

    Keys table EJB | script to correct counter values

    When you do migration from one version of commerce to the next or any other scenarios or due to data load scenarios some times the keys table counters are messed and causes lot of errors in application server logs when using those corresponding EJB's.

    A lot of discretion is warranted when doing stuff to the keys table e.g. counter should be greater than the lower bound and lesser than the upper bound
    You can generate the SQL statements from the script below and run them against the corresponding commerce schema where the issue was found.

    SQL Script to see which tables might need to be fixed:

    select 'select max(' || columnname||')+1 - (select counter from keys where tablename = '''|| tablename||'''), '''|| tablename || ''' from ' || tablename from keys

     SQL script to do the actual updates:
    select concat(concat(concat('update keys set counter=',concat(concat(
    concat(concat('(select max(',columnname),')+1 from ' ),tablename),') where tablename=''')),tablename),''' and counter <= '|| '(select max('||columnname||') from '|| tablename||')' ||';') from keys