Thursday, January 7, 2016

Sitecore Web API for Angularjs MVC integration

Problem Statement
What if there is CMS system hosted in DMZ server and there is no scope of adding any additional requirement due to some reason and still wants to use Sitecore CMS as an option to port content to your digital interface that can be Mobile or other touch screen device installed in stores. Here is the solution to do so.
Recently we did the same implementation and made Sitecore CMS as source system to give data to digital screens and native Iphone App.

Cloud and Sitecore CMS way.
  1. Sitecore CMS hosted in DMZ corporate infrastructure. Expose api's to access required data.
  2. There will be asp.net spa applicaiton developed using asp.net MVC +angularjs and hosted in cloud to consume this CMS system.
Technology
  1. glass mapper 
  2. sitecore CMS 7.2
  3. asp.net web api
Sitecore CMS Items Implementation
We only going to have content hence i created just reference folder within sitecore structure as per screenshot. Remember to take item id GUID for category to lookup through glass mapper.

Create Website Content under reference. As this is not going to be website path page item.

Create Category page item with category template. Keep the Item ID -Guid for glass mapper mapping with object tree to fetch categories.

Template Category

Add content.




Asp.net Web Api Implementation

The sitecore data item will be consumed via glass mapper ORM and can be modelled to get through API controller.

Here is the snapshot of solution explorer

The reference of nuget glass mapper in include configuration. This helps in ORM with sitecore object mapping.


Create Web api Route with respect to Sitecore

using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;

namespace MvcApplication1.App_Start
{
    public class RegisterWebApiRoute
    {
        public void Process(PipelineArgs args)
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

        public void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            // Only JSON response
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
            /*
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            */
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace MvcApplication1.App_Start
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Controller Category to fetch Sitecore Category content


using Glass.Mapper.Sc;
using MvcApplication1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace MvcApplication1.Controllers
{
    public class CategoryController : ApiController
    {
        public CategoryList categoryList { get; set; }
        public const string CATEGORY_ROOT_GUID = "{A547EA1E-D414-4521-80E0-A7C794BA3E8C}";
        
        // GET api/values
        [Route("root/api/category")]
        public List GetCategories()
        {
            //return new List();
            var context = new SitecoreContext();
            List categories = new List();
            categoryList = context.GetItem(CATEGORY_ROOT_GUID);
            var categoryBucket = categoryList.Children.Select(a => new Category() 
            { 
                CategoryId = a.CategoryId,
                Title = a.Title, 
                Description = a.Description, 
                SmallImage = a.SmallImage 
            }).ToList().Where(x => x.Title != null);
            foreach (var v in categoryBucket)
            {
                categories.Add(new CategoryItem() { 
                CategoryId=v.CategoryId,
                Title=v.Title,
                Description=v.Description,
                SmallImage=v.SmallImage
                });
            }
            return categories;
        } 
    }
}

Glass Mapper for Category : Children and Sitecore Parent

using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.Fields;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class Category
    {
        [SitecoreId]
        public virtual Guid CategoryId      { get; set; }
        public virtual string Title         { get; set; }
        public virtual string Description   { get; set; }
        public virtual Image SmallImage     { get; set; }
    }
    public class CategoryItem
    {
        public  Guid CategoryId { get; set; }
        public  string Title { get; set; }
        public  string Description { get; set; }
        public  Image SmallImage { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class CategoryList
    {
        public virtual IEnumerable Children { get; set; }
    }
}

Required Output.
Ensure you place the DLL in bin folder of sitecore website intance to keep this running.


Monday, January 4, 2016

Extend Custom Sort in Sitecore.

Implementation Steps

  1. Go to system ->settings-> subitems sorting create new item with template Sytem/Child Sorting
  2. Create below Demo.Sitecore.Practical.CustomSortComparer.dll and deploy in CMS instance bin folder.
  3. Add Type and class assembly details under Data section for Newly created item Created Date( instance of sitecore Setting Subitems sorting.
  4. You can sort using subitem sorting for any sitecore tree using Custom Created Date.


Class Library

using System;
using System;
using Sitecore.Data.Comparers;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;

namespace Demo.Sitecore.Practical.CustomSortComparer
{
    public class SitecoreCustomDateFieldComparer: Comparer
    {
        protected override int DoCompare(Item item1, Item item2)
        {
            var date1 = GetDateTime(item1);
            var date2 = GetDateTime(item2);
            return date1.CompareTo(date2);
        }

       private static DateTime GetDateTime(Item item)
        {
            var dateField = (DateField)item.Fields["Date"];
            return dateField != null ? dateField.DateTime : DateTime.MinValue;
        }
    }
}


Wednesday, December 16, 2015

Don't be Surprise If your website breaks in IE9 ! Console.log

Don't be surprise if something start breaking up in IE9 after you go for big bang release and customer started complaining website is not working. The reason is pretty straight forward, javascript and client scripting is taking centre stage and all new browsers support them very much. Console.log is common script that most of the developer used to trace the flow of javascript. It happens they forgot to uncomment them while release to production. It is rare case when big enterprise application fails to ensure this is taken care.


http://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function


Tuesday, December 8, 2015

Data Driven Subscription reports in SSRS, what can't be done in sitecore webform marketeers

Its a challenge when we fetch reports out of promotion held through webform markeeters. To our rescue is always a custom db options with custom forms with good security layer giving added advantage and flexibility to business users and end customer.

How it works?
You got loads of data and it takes lot of time to generate a report on demand. It simple design approach we make use of canned report or just allow subscription data driven reports based on user personalization.

This is something we coming up for our client and help them realize the benefits.

To know more, stay tune.

https://msdn.microsoft.com/en-AU/library/ms159150.aspx

Power of SSRS-
https://bineeshthomas.wordpress.com/tag/ssrs-data-driven-subscription-using-stored-procedure/

Data Masking:-
https://www.simple-talk.com/sql/database-administration/obfuscating-your-sql-server-data/

Big Data! It Implies

Twitter, Facebook, world data centre, Amazon and Google all these social networking or ecommerce site has huge footprint in terms of number of users, transactions they perform and data they crunch day in day out. These numbers are so big that it range from
terabyte to petabytes.

  1. Data Explosion
  2. Monetization
  3. Social Media
  4. Data mobilization
  5. Technology Advancement
Big Data -
high amount of data to be processed, produced and available with respect to diversity of source inside and outside.

Areas require Big Data
  • Image processing
  • Video processing
  • Seisemic processing
  • sensor data analysis
  • network analysis
  • enterprise monitoring
  • Enterprise data warehouse
  • Low latency Non Relationship Database
  • Key value - Amazon dynomite
  • Column oriented- cassandra hbase,Riask
  • Document databases- Couch db/Mongodb
  • Graph based- Neoo4j,Allegrograph
Big data analytics aims at fluid architecture. change for future and flexible architecture.

Thursday, December 3, 2015

C# Generics, Lamda Expression, Anonymous delegates, Extensions.

Next time you get chance to write a code.. use action as procedure to do your task.
Recursive Lamda Expression
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Action countdown = null;
            countdown = (i) =>
            {
                if (i > 0)
                {
                    Console.WriteLine(i);
                    countdown(i - 1);
                }
            };
            countdown(5);
            Console.Read();
        }
    }
}

Sunday, November 29, 2015

Redis Cache Architecture point of view

Thinking Redis cache stores key value pair just like any native .net code would do, is not just that. What we don't realize is that the cache can be distributed and centrally stored for multi server or webfarms. Not only cache management even session state management can be easily achieve using azure redis cache.

In theory we able to distribute load on server to certain extent to make it available to end users with better throughout ,low latency and easy data management.

1. Distributed caching
2. Centrally stored
3. Easy session management
4. Easy to clear and revisit cache expiry policy.


https://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/

Modern Web ApI and Cache repository Simpify.

https://code.msdn.microsoft.com/windowsdesktop/ASPNET-WebApi-Use-Redis-as-a0d942a3

Redis Manager

https://github.com/rgl/redis/downloads

Wednesday, November 25, 2015

Sitecore Quick Reference

Tips and Tricks
http://oshyn.com/sitecore-tips-and-tricks-vol-ii

Authoring tool
http://www.marketingtechnologyinsights.com/2013/06/9-sitecore-tips-tricks-content-editor.html

John West
http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2012/04/professional-sitecore-development-chapter-11-sitecore-best-practices-tips-and-tricks.aspx

http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2010/07/ten-things-you-did-not-know-you-could-do-with-sitecore.aspx

https://sitecoreaustralia.wordpress.com/2010/06/16/top-100-cool-things-in-sitecore-completed-list/

http://fes-sitecore.blogspot.com.au/

http://fes-sitecore.blogspot.com.au/2015/03/giving-content-editors-control-over.html#more

Angularjs Quick Reference

Cheat Sheet:-

  • $routeProvider /URL#Redirect
  • TemplateURL +Controller Binding
  •  when('/ShowOrder/:orderId',
  • = $route.current.
  • otherwise({redirectTo

  • Ng-view
  • Ng-Include
  • ng-repeat-start
  • ng-repeat-end

http://viralpatel.net/blogs/angularjs-routing-and-views-tutorial-with-example/
 

Regular Expression


Jquery Quick Reference

The below reference help you code selectors appropiately.

http://www.w3schools.com/jquery/trysel.asp

Basic Selectors:
Attribute    $("[href]")
ID             $("#ID")
Class         $(".className")
tags            $("p")





Thursday, November 12, 2015

Known Issue: Predictive Search- Accessibility

UX and technical design specifications, framework and guideline must be lay out for predictive search.

The best example is google predictive search.

Now remember one thing we sometime create custom predictive search with UL/LI with div tag and predictive search text box.

Important to note here:-

Dropdownlist aka combo box default behaviour does have up and down arrow keys to navigate through list items but this behaviour needs to be constructed when we use div-UL-LI options.

So remember next time when you working on something like this do take care of input field with predictive search.

I've seen developer using ARIA
Role=Status
Role=ALert
Aria-live=assertive
Autocomplete="off"
aria-labelledby="typeahead"

The only problem with this tags are they do not have universal acceptance. They works in some device, OS , browsers etc. 

Known Issue: Accessibility -Select Picker Item behaviour in Iphone Voice over

The select html combo box behaviour in Iphone voice is causing problem with accessibility. It doesn't enable the focus on picker selection of IOS when we double tap to activate the picker control( Select Id= > Option in html.

Now this very well works out in IOS 8.0 and above. There is some defect in IOS 7.0 and higher version. Having said that , the focus and default behaviour of picker for voice over is still a problem.

1. Double tap does not set the focus on picker item values.
2. After picker item is selected focus never moves to next element.


Bottom line is:-

Combo box aka dropdown box( select Option) must be customised to suit requirement.

Do add Label for at least for select .

 

Wednesday, November 4, 2015

Accessibility AA Tip and tricks


 
Accessibility:
·         Flow of information
·         Correct proof reading
·         Right colour contrast and text size to help users with visual problems
·         Right tabbing , focus and click ordering. Logical arrangement of information’s. Right speech, right flow of speech with correct pause. Simple example.. Go Slow, work is in progress. Well what if speak tool reads out in this way. Go pause, slow work is in progress. There should be balance of proper read out in very meaningful way. Instruction text and design has to be considered while accessibility is taken care. Content author must be trained to understand such implications with good examples.
 
§  Visually – Colour medium to communicate
 
o   Problem statement- The color Red with Arrow indicates you are here in this section whereas grey without bottom arrow indicates there are sub menu item to be viewed.

 
·         List of headings
 
·         Headings structure and hierarchy
 
·         Logical orders of tabbing
 
·         Skip Links back to top
 
·         Text size 200% in IE Or Zoom
 
·         Colour Contrast and Text size
 
·         Progress Bar- Such as you completed 1 of 3 step
 
·         Avoid abbreviation like Q&A , FAQ
§  FAQ read as Fack and so on.
 
·         Reading out numbers , units etc
§  Take care MB, cents, Dollar, KB, telephone number, credit card sample numbers etc.
 
·         Button should be informative.
§  Submit button and Review Button. If there are case where text on a button is very generic in nature such as continue, Read more, Add, More information,View . We can make information more elaborate for visually challenged users.
§  For e.g what do you mean by more information, related to what . These are the questions that may be reviewed and assessed.
§  Role=button
 
·         Anchor tag
§  Target=_blank its important to add explicit Opens in new window. If there is link with download, mention what is going to be downloaded like PDF, word doc and so on
§  Ensure we have role=button, role=link appropriately marked in anchor tag for IOS, android to call it as interactive element
§  Ensure href got some value. Href=”#!”
 
·         Call out table structure properly
·         Most used ARIA tags
§  Aria-hidden
§  Aria-label

 

Some handy Jquery To set focus

$('select').on('change', function () { $(this).next().focus(); });

 

For Empty Alt text attribute

 

//empty image alt tags
$("img").each(function (index) {
    $('.ccs1).attr('alt', "");
    $('.ccs2').attr('alt', "");
    $('.ccs3').attr('alt', "");
});
 
 

Thursday, October 29, 2015

Accessibility Forms -IOS/Android

Technical Specification


  • OS-IOS
  • IDevice :Iphone/IPAD/MAC
  • Browser: Safari
  • Speak Tool : Voice Over

  • OS : Android ALL Version
  • Device: Samsung/Nexus etc
  • Browser: Chrome
  • Speak Tool : Android Talkback


Form Accessibility

  • Placeholder supported in IOS not in Android chrome
  • Title tag supported in IOS as well as in Android chrome
  • Aria-label supported in both

What are the guidelines?
1. Required field for Label field 
2. Required field feature for input fields attributes such as  <input type=text "Required"
3.Placeholder attribute
4. Label for Text field, combo box. 
5. Error message should be read out before input fields.
6. Checkbox, combobox, radio button, input fields should be read out by assistive technology.
7. Tab sequence should be followed.

Common Issue:

1. If item selected in combo box, the focus will go to the top of the page. Reason no Label FOR




Wednesday, October 21, 2015

Sitecore CMS 7.2 Performance Engineering

Every single improvement counts if we consider performance tuning in sitecore. There are unnecessary logs that generates at runtime which can be assessed and switch off , if it does not solve the purpose.
Ofcourse these are debugging logs but one should ensure if there is custom application logs written for specific purpose.

Logs:-

  1. Crawling.log
  2. Search.log
  3. WebDAV.log
This will reduce I/O read and write operation for certain extend. Just look at this scenario , where there is web farm with many servers and there is requests served by these servers every time and it generates tons of tons of logs which is not necessary at all.


IIS related Settings-Best Practice and Recommendation

  1. Set permissions on /website and /data
  2. Ensure the data and indexes folders are outside of the web root and update the web.config to point to the data folder
  3. In IIS ensure that Maximum Worker Processes for the Application Pool is set to 1 (under advanced settings)
  4. In IIS ensure that Load User Profile settings of the Application Pool is set to "true" (under advanced settings)
  • In IIS ensure anonymous access is denied for:
  •  /App_Config
  •  /sitecore/admin
  •  /sitecore/debug
  •  /sitecore/webservice
  1. In IIS Enable HTTP keep alive
  2. In IIS enable static content compression
  3. In IIS on the CMS server, enable dynamic content compression
  4. In IIS disable execute permissions on the upload folder
  5. In IIS enable content expiration using HTTP response headers, especially for the /sitecore folder (optional)

Sitecore Configuration Changes

  1.  Ensure the /data and /indexes folders are outside of the web root and update the dataFolder setting to point to the data folder.
  2. Include the path to static media files (header images, css files, JavaScript files) in the IgnoreURLPrefixes settings to prevent Sitecore from intercepting the requests.
  3. Disable unused search indexes by setting Indexing.UpdateInterval to 00:00:00.
  4. Update the standard cache sizes for prefetch, data, item and item as recommended (see the scaling guide), and then test for further adjustments.
  5. Ensure presentation components that are candidates for caching are set to cacheable.
  6. For 64-bit systems with the available memory, disable cache size limits using Caching.DisableCacheSizeLimits.
  7. Disable performance counters using Counters.Enabled as they add overhead.
  8. Disable WebDav by removing the references in , , .
  9. Disable memory monitor by removing the hook from .
  10. Restrict access to .XML, .XSLT and .MRT files using the section.
  11. Disable the upload watcher by removing it from the - Sitecore.Resources.Media.UploadWatcher.
  12. Optionally disable client RSS feeds by removing the Sitecore.Shell.Feeds.FeedRequestHandler.
  13. Remove unneeded headers from the responses.  For example X-Aspnet-Version, X-Powered-By, X-AspNetMVC-Version.
  14. If possible check disablebrowsercaching=false , if there is no form data and cookies in your system. This is recommeded for most generic, centric content website.
  15. Diable crawling.log, publishing.log and search.log in delivery boxes.
  16. Remove 404 errors
  17. Remove viewstate if we use traditional asp.net .
  18. Disable Webdav if not in use
  19. Use output caching.

Sitecore HTML Caching


1. Caching.DefaultHtmlCacheSize : Determines the default size of the html cache of a site specify the value in bytes or append the value with KB, MB or GB
Default Size=10mb
setting name="Caching.DefaultHtmlCacheSize" value="10MB"

site name="website" ... cacheHtml="true" htmlCacheSize="10MB"
 
 
 
 
 
 
 
 

Saturday, October 3, 2015

Accessibility - Checklist and Rule Book

Accessibility AA WCAG 2.0 must have technical guideline to achieve accessibility in very good form however Accessibility has got broader meaning and guidelines in terms of usability.

In Nutshell, if website has to be accessible and must be accessed through assistive technology, here is the following ask:-

1. Each information in the website must be easy to navigate and located.
2. Instructions in the device based on assistive technology must be very much supported. Such as use up and down or tab to navigate . Double tap to activate or deactivate and so on.
3. Color contrasts, font size and content placement has to be designed considering the flow of the information is very logical and making sense for listener, reader and viewer.
4.Entry and exit points has to be well defined otherwise the whole purpose of the given web page will beat the overall purpose.
5. Indicative , informational and Non contextual images must be defined and called out clearly.

Web Content Accessibility Guidelines (WCAG)
ARIA
Accessible Rich Internet Applications (ARIA)
Assistive Technology
  • Android Talkback
  • Jaws IE
  • Voice  IOS
Most Common Defects:
    1. Check Empty Heading tags H1,H2,H3 etc.
    2. Check hierarchy of heading tags
    3. Never use Headings without content. Try to use div
    4. If table always use Table header as best practice
    5. If Image contains subtitle. Never use Alt..keep this empty. As assistive technology reads out twice.
    6. Take care of Anchor tag..make use of aria, role and title to spell out opens in window for target= _blank
    7. If there is more generic link such as more information or View button mention title to indicate the purpose.
    8. Checking tabbing order and ensure navigation help easy access to elements and content.
     
     
The following checklist is based on WebAIM's WCAG 2.0 Checklist. It is intended for training purposes and includes only the Level A and AA success criteria
http://webguide.gov.au/accessibility-usability/accessibility/
Vision Australia
http://www.visionaustralia.org
AA Compliance Checklist
http://www.unimelb.edu.au/accessibility/training/wcag-checklist.html


Friday, September 18, 2015

Sitecore CMS : Client Browser cache Nightmare

If there is a system with CMS and CMS supplies data to non CMS system very frequent changes then one has to keep in mind about the browser cache.

There can be a scenario , your application is hosted in self kiosk mode where it has to get refresh after every 2 mins to reflect right data and don't go into sleep mode. Either you enabled attract screen or get the fresh data from the server to keep it going.

Now imagine a situation where content author has published some content and your browser refresh after 2 mins and content is not changes. BOOO......!

What if, it is browser cache is not clear and we are using angularjs to give the best user experience.

Here is the brute force method of disabling browser client side caching mechanism. This will reduce the efficiency and response time of application before you apply this.

 

Wednesday, September 2, 2015

Mixed Content Error http vs https


 Problem:

Mixed Content: The page at 'https://sitename.com/abc/def' was loaded over HTTPS, but requested an insecure script 'http://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&sensor=false'. This request has been blocked; the content must be served over HTTPS

Solution:
The browser will load with the correct protocol. This goes for images as well. Then if the user comes from http, it will load http, https if https.

 How to Fix the Problem

If the problem appears on regular HTTPS secured pages with content that is being loaded via the insecure HTTP protocol, you can control how the content behaves.
Links with “http://” extensions need to change to contain the “s” part of HTTP protocol (https://) pointing out to an SSL-reserved port. A more elegant way of handling different protocols is to have only slashes where port is expected “//”. so that page can use the protocol used to open the page itself:

Reference:
http://stackoverflow.com/questions/30473172/mixed-content-error-http-vs-https

Monday, July 20, 2015

Kiosk Website Guideline


 

To share my experience and help you think proactively for any such application in future , here is the quick know-how.

 

1.       Disable Zoom in touch screen- This will be disturb UX.

2.       Hide vertical scroll bar.

3.       Disabled left and right touch scroll to avoid back and forward history.

4.       Screen resolution of Kiosk.

5.       Attract Screen, if in case kiosk site is offline. This attract screen should be screen saver. This screen saver is set of content managed screens so that we can display some information about specials or products.

6.       Kiosk refresh after 2 mins. So that it fetch timely feeds from CMS system.

7.       For Kiosk refresh ensure browser cache is disabled. Real Time Data

8.       For Kiosk Refresh mode ensure server side caching is disabled. Real Time Data .need Assessment so as to enable this based on more static or persistent content.

9.       For touch device there is concept called Pinch Zoom and Flicker pen touch. Check the setting for touch device. This comes handy.

10.   Access restriction to Kiosk Application hosted in cloud.

 

That’s it! J

Wednesday, July 8, 2015

MY CSS Kit

. BottomMarginDiv{
bottom-margin: 20px;
}


style="clear:both"

How to Restrict IP to website in Asp.net ?

 
 
This is essential when we want to allow only given set of ip address or domain. This is called white list IP range allow or blacklist IP range deny
 
Remember
  1. Private IP will not work , use public IP
  2. Private IP is machine /device ip
  3. Public IP is internet IP that connects from your computer /device to help you browse website.
 
 
 
 
http://www.victor-ratajczyk.com/post/2011/12/21/Webconfig-ipSecurity-Allow-specific-IP-addresses-Deny-all-others.aspx