26 February 2018

WFFM Web form for marketer fail to submit in Sitecore

I have setup a standard form using WFFM in Sitecore 8.2. It always fail when submit. Error as below,

Error:

Exception: System.Data.DataException
Message: Error executing SQL command: SELECT df.Dropouts, df.Failures, df.Submits, df.Success, dv.Visits FROM
(SELECT [dbo].[Fact_FormStatisticsByContact].[FormId] AS FormId, 
SUM([dbo].[Fact_FormStatisticsByContact].[Submits]) AS Submits, SUM([dbo].[Fact_FormStatisticsByContact].[Failures]) AS Failures,
SUM([dbo].[Fact_FormStatisticsByContact].[Dropouts]) AS Dropouts, SUM([dbo].[Fact_FormStatisticsByContact].[Success]) AS Success
FROM [dbo].[Fact_FormStatisticsByContact] WHERE [dbo].[Fact_FormStatisticsByContact].[FormId] = @FormId
group by [dbo].[Fact_FormStatisticsByContact].[FormId]) df INNER JOIN

(SELECT Count(distinct [dbo].[Fact_FormEvents].[InteractionId]) AS Visits,
[dbo].[Fact_FormEvents].[FormId] AS FormId 
  FROM [dbo].[Fact_FormEvents]
  WHERE FormId = @FormId
  GROUP BY [dbo].[Fact_FormEvents].[FormId]  ) dv ON df.FormId = dv.FormId

Nested Exception

Exception: System.Data.SqlClient.SqlException
Message: Invalid object name 'dbo.Fact_FormStatisticsByContact'.
Source: .Net SqlClient Data Provider
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at Sitecore.Data.DataProviders.Sql.DataProviderCommand.ExecuteReader()


I just realized this is what I missed:

























After run the .sql , the submit works!


14 February 2018

Copy item values to new language version in Sitecore


There is a requirement in multi-lingual sitecore setup, when we create a new non default language version for an item, the content editor keen to have the functionality to copy over all the fields values to save them some time from manually setup all again for each language.

(The code has been tested against Sitecore 8.2 and I cannot see why it does not work for later version.)

First, you need to setup Sitecore multi Lingual properly. reference to link


Then code sample:


using Sitecore.Data.Items;
using Sitecore.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.Data.LanguageFallback;
 
namespace Test.Feature.Language.Pipelines
{
 
    public class CopyEnglishContent
    {
 
        public void OnVersionAdded(object sender, EventArgs args)
        {
            var item = Event.ExtractParameter(args, 0) as Item;
            try
            {
                if (item != null && item.Version.Number == 1)
                {
                    var fallbackItem = item.GetFallbackItem();
 
                    item.Editing.BeginEdit();
                    fallbackItem.Fields.ReadAll();
 
                    foreach (Sitecore.Data.Fields.Field field in fallbackItem.Fields)
                    {
                        if ((!field.Shared && !field.Name.StartsWith("__") && field.Name.Trim() != "") || field.Name == "__Final Renderings")
                        {
                            item.Fields[field.Name].SetValue(field.Value, true);
                        }
                    }
 
                    item.Editing.EndEdit();
                    item.Editing.AcceptChanges();
                }
            }
            catch (Exception ex)
            {
 
                if (item != null)
                {
                    item.Editing.CancelEdit();
                }
            }
        }
    }
}


Apart from above, we just need to put it in the right spot for configuration purpose.


<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
    <events>
      <event name="item:versionAdded">
        <patch:delete />
      </event>
      <event name="item:versionAdded">
        <handler type="Test.Feature.Language.Pipelines.CopyEnglishContent, Test.Feature.Language" method="OnVersionAdded" />
      </event>
    </events>
</sitecore>
</configuration>

That is all.

Example:

1. Select "Fallback version" for Portuguese.






















2. "Add a new version"


























3. A new version have been created for "Portuguese"







Done! Happy Sitecoring!



Reference:

https://doc.sitecore.net/sitecore_experience_platform/setting_up_and_maintaining/language_fallback/setting_up/enable_and_set_up_language_fallback

http://geekswithblogs.net/amaniar/archive/2011/12/12/using-sitecores-pipeline-to-pre-populate-item-in-current-language.aspx



29 November 2015

Test if the server is reachable via ports without telnet in linux

nc -zv 127.0.0.1 80
Multiple ports:
nc -zv 127.0.0.1 22 80 8080
Range of ports:
nc -zv 127.0.0.1 20-30
http://superuser.com/questions/621870/test-if-a-port-on-a-remote-system-is-reachable-without-telnet

30 June 2015

"java.lang.outofmemoryerror java heap space" in Bamboo setup


Been the process of setting up Bamboo environment for the client, keep getting and error of java heap space when fires up the bamboo build. Found the solution from Atlassian wiki page, take the essence of the solution from long documentation and put it down my blog for the future reference.


Setting properties for Windows services from the command line
  1. Identify the name of the service that Bamboo is installed as in Windows (Control Panel > Administrative Tools > Services):
  2. Open a command prompt from Start > Run > type 'cmd' > Enter.
  3. Change directory to the bin directory of your Bamboo installation directory.
  4. Run:
    tomcat7w //ES//%SERVICENAME%
    (info) In the above example, it would be tomcat7w //ES//Bamboo
  5. Click on the Java tab to see the list of current start-up options:
https://confluence.atlassian.com/display/BAMBOO/Configuring+Bamboo+on+start-up

07 June 2015

Using Telstra API to send SMS in ASP.NET

Telstra (https://dev.telstra.com/) is pushing their own API and as a part of the plan, it is giving away 1000 free SMS per month with the limit of 100 per day.

After a simple register and set up, wait about 1 hour for get "MyAPP" approved, it is ready to go.



It requests an access token with your own "key" and "secret" first which expires in 1 hour. Then we need to pass in this token with all the request we are going to make.
The documentation is simple, straight forward and all the sample code is hosted on github. I write a quick C# to test it out and it works well!

public string GetAccessToken()
{
    const string consumerKey = "{yourkey}";
    const string consumerSecret = "{secret}";
    string url =string.Format("https://api.telstra.com/v1/oauth/token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=SMS", consumerKey, consumerSecret);

    using (var webClient = new System.Net.WebClient())
    {
        var json = webClient.DownloadString(url);
        var obj = JObject.Parse(json);
        return obj.GetValue("access_token").ToString();
     }
}
public string SendSms(string token, string recipientNumber, string message)
{
     try
     {
        using (var webClient = new System.Net.WebClient())
        {
            webClient.Headers.Clear();
            webClient.Headers.Add(HttpRequestHeader.ContentType, @"application/json");
            webClient.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);

            string data = "{\"to\":\"" + recipientNumber + "\", \"body\":\"" + message + "\"}";
            var response = webClient.UploadData("https://api.telstra.com/v1/sms/messages", "POST", Encoding.Default.GetBytes(data));
            var responseString = Encoding.Default.GetString(response);
            var obj = JObject.Parse(responseString);
            return obj.GetValue("messageId").ToString();
                    // Now parse with JSON.Net
        }
     }
     catch (Exception e)
     {
        Console.WriteLine(e.Message);
     }
        return string.Empty;
 }

04 June 2015

Install MongoDB in Debian

As a part of Sitecore 8 setup, we need to install MongoDB in Debian.

  1. Check Debian version. The MongoDB 3.xx requires at least Debian 7.1



  2. So we need to upgrade to Debian 7.1 at least. Here is how to do it.

    Edit your /etc/apt/sources.list file and change all instances of squeeze to wheezy. Once you have finished, your /etc/apt/sources.list should resemble the following:

       /etc/apt/sources.list


      
    deb http://ftp.us.debian.org/debian/ wheezy main
    deb-src http://ftp.us.debian.org/debian/ wheezy main
    
    deb http://security.debian.org/ wheezy/updates main
    deb-src http://security.debian.org/ wheezy/updates main
    
    # wheezy-updates, previously known as 'volatile'
    deb http://ftp.us.debian.org/debian/ wheezy-updates main
    deb-src http://ftp.us.debian.org/debian/ wheezy-updates main




    How to use "vi" http://www.howtogeek.com/102468/a-beginners-guide-to-editing-text-files-with-vi/
  3. Go through the update process.

    Enter the following command to update your package lists:
    apt-get update

    Keep getting the error of " GPG error: http://ftp.us.debian.org wheezy Release: The following signatures couldn't be verified because the public key is not available: Try this and ignore the warning.
    apt-get install debian-archive-keyring
  4. More info: http://serverfault.com/questions/337278/debian-how-can-i-securely-get-debian-archive-keyring-so-that-i-can-do-an-apt-g
  5. Enter the following command to grab the latest versions of key system utilities:
  6. apt-get install apt dpkg aptitude
  7. After the package updates have completed, upgrade your system by entering the following command. The upgrade will download and install numerous packages. This step may take a while to complete.
    apt-get dist-upgrade


  8. After "reboot", check the debian version again. 
  9.            cat /etc/debian_version









  • Install MongoDB

    The Debian package management tools (i.e. dpkg and apt) ensure package consistency and authenticity by requiring that distributors sign packages with GPG keys.

    Import the public key used by the package management system.

    Issue the following command to add the MongoDB public GPG Key to the system key ring.
    apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10

    Create a /etc/apt/sources.list.d/mongodb-org-3.0.list file for MongoDB.

    Create the list file using the following command:
    echo "deb http://repo.mongodb.org/apt/debian "$(lsb_release -sc)"/mongodb-org/3.0 main" | tee /etc/apt/sources.list.d/mongodb-org-3.0.list


    If your Debian installation does not have lsb_release installed, you may install it using sudoapt-get install lsb-release.

    Reload local package database.

    Issue the following command to reload the local package database:
    apt-get update
    root@debian-x64:~# apt-get update
    Ign http://58.162.66.11 squeeze Release.gpg
    Ign http://58.162.66.11/linux/debian-6.0.1a-x64/ squeeze/main Translation-en
    Ign http://58.162.66.11/linux/debian-6.0.1a-x64/ squeeze/main Translation-en_AU
    Hit http://58.162.66.11 squeeze Release
    Ign http://58.162.66.11 squeeze/main Sources/DiffIndex
    Ign http://58.162.66.11 squeeze/main amd64 Packages/DiffIndex
    Hit http://58.162.66.11 squeeze/main Sources
    Ign http://58.162.66.11 squeeze/main amd64 Packages
    Hit http://58.162.66.11 squeeze/main amd64 Packages
    Ign http://repo.mongodb.org squeeze/mongodb-org/3.0 Release.gpg
    Ign http://repo.mongodb.org/apt/debian/ squeeze/mongodb-org/3.0/main Translation-en
    Ign http://repo.mongodb.org/apt/debian/ squeeze/mongodb-org/3.0/main Translation-en_AU
    Ign http://repo.mongodb.org squeeze/mongodb-org/3.0 Release
    Ign http://repo.mongodb.org squeeze/mongodb-org/3.0/main amd64 Packages
    Err http://repo.mongodb.org squeeze/mongodb-org/3.0/main amd64 Packages
    404 Not Found
    Get:1 http://ftp.au.debian.org squeeze-updates Release.gpg [836 B]
    Hit http://security.debian.org squeeze/updates Release.gpg
    Ign http://security.debian.org/ squeeze/updates/main Translation-en
    Ign http://security.debian.org/ squeeze/updates/main Translation-en_AU
    Ign http://ftp.au.debian.org/debian/ squeeze-updates/main Translation-en
    Ign http://ftp.au.debian.org/debian/ squeeze-updates/main Translation-en_AU
    Hit http://security.debian.org squeeze/updates Release
    Hit http://security.debian.org squeeze/updates/main Sources
    Hit http://security.debian.org squeeze/updates/main amd64 Packages
    Get:2 http://ftp.au.debian.org squeeze-updates Release [113 kB]
    Err http://ftp.au.debian.org squeeze-updates Release
    Fetched 837 B in 5s (158 B/s)
    Reading package lists... Done
    W: A error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://ftp.au.debian.org squeeze-updates Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553
    W: Failed to fetch http://repo.mongodb.org/apt/debian/dists/squeeze/mongodb-org/3.0/main/binary-amd64/Packages.gz 404 Not Found
    W: Failed to fetch http://ftp.au.debian.org/debian/dists/squeeze-updates/Release
    W: Some index files failed to download, they have been ignored, or old ones used instead.

    gpg --keyserver pgpkeys.mit.edu --recv-key 8B48AD6246925553
    gpg -a --export 8B48AD6246925553 | apt-key add -

    Install the MongoDB packages.

    You can install either the latest stable version of MongoDB or a specific version of MongoDB.
    export LANGUAGE=en_US.UTF-8
    export LANG=en_US.UTF-8
    locale-gen en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    dpkg-reconfigure locales
    
    

    Install the latest stable version of MongoDB.

    Issue the following command:
    sudo apt-get install -y mongodb-org 

    Install a specific release of MongoDB.

    Specify each component package individually and append the version number to the package name, as in the following example:


    3.0.2 mongodb-org-server=3.0.2 mongodb-org-shell=3.0.2 mongodb-org-mongos=3.0.2 mongodb-org-tools=3.0.2
    If we get this error as below, go to


    [FAIL] Starting database: mongod failed!
    invoke-rc.d: initscript mongod, action "start" failed.
    dpkg: error processing mongodb-org-server (--configure):
     subprocess installed post-installation script returned error exit status 1
    Setting up mongodb-org-mongos (3.0.2) ...
    Setting up mongodb-org-tools (3.0.2) ...
    dpkg: dependency problems prevent configuration of mongodb-org:
     mongodb-org depends on mongodb-org-server; however:
      Package mongodb-org-server is not configured yet.

    dpkg: error processing mongodb-org (--configure):
     dependency problems - leaving unconfigured
    Errors were encountered while processing:
     mongodb-org-server
     mongodb-org
    E: Sub-process /usr/bin/dpkg returned an error code (1)

    Make sure remove "/tmp/mongodb-27017.sock" if there is any.
    Also, go to "/var/log/mongodb/mongod.log" to see the logs.
    If the log showing insufficient space related error.
    Put "smallfiles=true" in the etc/mongod.conf to get over it for now and raise up with CAV to give more spaces for the related path.


  • 24 May 2015

    LockObtainFailedException and SwitchOnRebuildLuceneIndex in Sitecore 7

    "LockObtainFailedException" is a common error in Sitecore 7. For most of the cases, it will occur when you try to access the index file while the index is still building. The error will looks like something like below,


    In Sitecore 7, it introduces the "SwitchOnRebuildLuceneIndex". (Sitecore.ContentSearch.LuceneProvider.SwitchOnRebuildLuceneIndex) It will create a "xxx_sec" .e.g "sitecore_index_web_sec)" index folder and build a new set of indexes for Sitecore to switch on when rebuilding index is happening.
    
    
    

    I recommend Sitecore set this as default provider.

    WFFM Web form for marketer fail to submit in Sitecore

    I have setup a standard form using WFFM in Sitecore 8.2. It always fail when submit. Error as below, Error: Exception: System.Data.DataE...