Thursday, April 20, 2017

Rules Based Engine using Tuples

Dynamic Rules Defined Using Tuple

  1. Input: Define Rules Case Conditions
  2. Output :Define Results based on Rules case conditions

       

          
   
    class Program
    {
        static void Main(string[] args)
        {
            var options = GenerateRulesBasedResults(true, false, false, false, true);
            foreach (var option in options)
            {
                Console.WriteLine (option.ToString());
                /* Ford
                 * BMW
                 * Mercedes
                 */
            }
            Console.Read();
        }
        public static List<CarSale> GenerateRulesBasedResults(bool isCruiseControl, bool isAutomatic, 
                                                               bool isUnderWarranty, bool isOnSale, bool isOnRoadOffSale)
        {
            List<CarSale> options;
            Results.TryGetValue(Tuple.Create(isCruiseControl, isAutomatic, isUnderWarranty, isOnSale, isOnRoadOffSale), out options);
            return options;
        }

        //I/P Rule Case Condition variant
        private static readonly Tuple<bool, bool, bool, bool, bool> RuleCaseCondition1 = Tuple.Create(true, false, false, false, true);
        private static readonly Tuple<bool, bool, bool, bool, bool> RuleCaseCondition2 = Tuple.Create(false, true, false, false, true);       

        //O/P Rule based results.
        private static readonly Dictionary<Tuple<bool, bool, bool, bool, bool>, List<CarSale>> Results =
            new Dictionary<Tuple<bool, bool, bool, bool, bool>, List<CarSale>>
        {
                { RuleCaseCondition1, new List<CarSale> {   CarSale.Ford , CarSale.BMW, CarSale.Mecedes} },

                { RuleCaseCondition2, new List<CarSale> {   CarSale.Suzuki , CarSale.Mazda} },
        };

        public enum CarSale
        {
            Honda,
            BMW,
            Mazda,
            Suzuki,
            Mecedes,
            Wolkswagen,
            Ford
        }

  

  
       
 

Tuesday, April 11, 2017

Sitecore MVC best practice Avoid Multiple types were found that match the controller

Scenario


Pre- production cleanup and performance improvement. In terms of security and performance optimization, sitecore logs, iis logs, http sys logs or event logs are best place to look upon. It give detailed behavour of application in terms of errors, redundant calls and other user specific details that are security threats. Having said that keeping production environment clean is good for application overall health. Below is the one of the example that we may ignore. This can be viewed in event logs mostly.


Event Log

Multiple types were found that match the controller named 'Authentication'. This can happen if the route that services this request ('sitecore/shell/api/sitecore/{controller}/{action}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter. The request for 'Authentication' has found the following matching controllers: Sitecore.Controllers.AuthenticationController My.MVC.Areas.MyAPI.Controllers.Api.AuthenticationController at System.Web.Mvc.DefaultControllerFactory.GetControllerTypeWithinNamespaces(RouteBase route, String controllerName, HashSet`1 namespaces) at System.Web.Mvc.DefaultControllerFactory.GetControllerType(RequestContext requestContext, String controllerName) at System.Web.Mvc.DefaultControllerFactory.System.Web.Mvc.IControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, String controllerName) at Sitecore.Mvc.Controllers.SitecoreControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, String controllerName) at System.Web.Mvc.MvcRouteHandler.GetSessionStateBehavior(RequestContext requestContext) at System.Web.Mvc.MvcRouteHandler.GetHttpHandler(RequestContext requestContext) at System.Web.Mvc.MvcRouteHandler.System.Web.Routing.IRouteHandler.GetHttpHandler(RequestContext requestContext) at Sitecore.Mvc.Routing.RouteHandlerWrapper.GetHttpHandler(RequestContext requestContext) at System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context) at System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

BottomLine

Never use sitecore or .net intrinsic names for controller

Sunday, April 9, 2017

Add Sitecore AD Membership Provider at runtime

Before you refer this blog, refer this blogpost
https://santoshpoojari.blogspot.com.au/2017/03/sitecore-active-directorysitecoreadmemb.html

I have taken more generic approach to add this. I have refined the above method with c# generic constraint.


Things to be taken care.      

We cannot use below Providers add due: Exception Details: System.NotSupportedException: Collection is read-only.

//Membership.Providers.Add(provider);
Therefore we should use utility class that give extension method AddTo.

http://stackoverflow.com/questions/1432508/programmatically-adding-a-membership-provider

Generic Membership Provider

  
 public static void InitialiseProviders <T>(T provider, string providerName, NameValueCollection providerConfiguration) where T : MembershipProvider
        {
            provider.Initialize(providerName, providerConfiguration);
            provider.AddTo(Membership.Providers);
            //We cannot use below Providers add due: Exception Details: System.NotSupportedException: Collection is read-only.
            //Membership.Providers.Add(provider);
        }

Utility Extension Method

public static class ProviderUtil
{
    static private FieldInfo providerCollectionReadOnlyField;

    static ProviderUtil()
    {
        Type t = typeof(ProviderCollection);
        providerCollectionReadOnlyField = t.GetField("_ReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
    }

    static public void AddTo(this ProviderBase provider, ProviderCollection pc)
    {
        bool prevValue = (bool)providerCollectionReadOnlyField.GetValue(pc);
        if (prevValue)
            providerCollectionReadOnlyField.SetValue(pc, false);

        pc.Add(provider);

        if (prevValue)
            providerCollectionReadOnlyField.SetValue(pc, true);
    }
}


Initialize the LDap AD Configuration and call the generic method

 public static NameValueCollection LdapSitecoreProviderConfiguration
        {
            get {

                 NameValueCollection config = new NameValueCollection();                                 
                 config["type"] = "LightLDAP.SitecoreADMembershipProvider";
                 config["name"] = "SomeProviderName";

                 config["connectionStringName"] = "LDAPConnString";
                 config["applicationName"] = "sitecore";
 
                 config["connectionUsername"] = ConfigurationManager.AppSettings["AppSettingKeys-UserName"];
                 config["connectionPassword"] = ConfigurationManager.AppSettings["AppSettingKeys-Password"];
 
                 config["minRequiredPasswordLength"] = "1";
                 config["minRequiredNonalphanumericCharacters"] = "0";
                 config["requiresQuestionAndAnswer"] = "false";
 
                 config["requiresUniqueEmail"] = "false";
                 config["connectionProtection"] = "secure";
 
                 config["attributeMapUsername"] = "sAMAccountName";
                 config["enableSearchMethods"] = "true";
 
                 config["customFilter"] = "(memberOf=Your org custom filter)";
                 return config;
            }
        }
InitialiseProviders(new SitecoreADMembershipProvider(), "someldapName", xyz.LdapSitecoreProviderConfiguration);

Saturday, April 1, 2017

Devops- VSO and Git!

Azure :Continuous Delivery Preview

Donovan Brown Channel 9 Session

Devops Systematic Integration 
  • Build -CI 
  • Deploy Release -CD
Helped me create first end to end devops CI and CD pipeline using continuous delivery preview.

https://channel9.msdn.com/events/Visual-Studio/Visual-Studio-2017-Launch/WEB-105

I face one issue with nuget restore and it is because of this error causing constant issue.
http://stackoverflow.com/questions/32254439/nuget-packages-are-missing
After configuring continuous delivery with resource group and app service plan. It asks for repository and setup build and release pipeline by itself. In fact zero configuration.

























Options : Multiple configuration To queue parallel build on different agents


Even you can apply above magic directly from powershell script.

Create New: Yo team



Update existing CI and CD:Yo team/pipeline

Build Agents

  • No physical controller
  • Work side by side with XAML
  • Agents are XCOPY deployed and auto updated from server
  • Agent pool and collection assign to machine Agent

Gear Icon

Important Information
  • Download agents
  • Unblock the folder
  • Run ConfigureAgent.Ps1
  • Copy Team foundation server url
  • Give working folder name
  • Run as window service or interactive mode

Note:
  • Agent Capability in relation with Build General Tab -> Demand.
  • Demand can be used to run build on Premise agent or cloud agent.

Monday, March 27, 2017

Solr Basic Authentication : Secure through key vault

If you are using key vault and you want to secure solr basic authentication credential, it is good practice to fetch it from appsettings which will retrieve from key vault server for specific environment at runtime. In order to do that you may have to configure solr configuration programmatically. Below is the useful sitecore stackexchange link that can come handy.



http://sitecore.stackexchange.com/questions/5112/how-to-initialize-solr-end-point-connection-with-basic-authentication-programmat/5145#5145

namespace MyClassLibrary
{
  public class MyBasicAuthHttpWebRequestFactory : IHttpWebRequestFactory
  {


    public MyBasicAuthHttpWebRequestFactory(string username, string password)
    {
      this.username = ConfigurationManager.AppSettings["username"];
      this.password = ConfigurationManager.AppSettings["password"];
    }

    public IHttpWebRequest Create(string url)
    {
      return this.Create(new Uri(url));
    }

    public IHttpWebRequest Create(Uri url)
    {
      HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
      string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(this.username + ":" + this.password));
      request.Headers.Add("Authorization", "Basic " + base64String);
      return (IHttpWebRequest) new HttpWebRequestAdapter(request);
    }
  }
}

http://sitecore.stackexchange.com/questions/5062/update-the-sitecore-configs-at-runtime-possible/5076#5076

Tuesday, March 21, 2017

Devops Cheat sheet

Try new Continuous Delivery Preview:




Scan your build with Whitesource for open source code base.

https://blogs.msdn.microsoft.com/visualstudioalm/2017/03/07/open-source-scanning-in-visual-studio-team-services-with-whitesource-bolt/

Build


Release Pipeline: 

Environment:

Set Pre-approval or post approval before someone deploy the release into test or prod.


Sitecore Active Directory:SitecoreADMembershipProvider Initialize and add provider at runtime in application_start

Key : Know and how

These are the following set of queries may be asked once we able to roll out , design or implement sitecore ldap module.

  • Whether Membership, role or profile provider required. Choose wisely, if membership is required just use that. 
  • The project requirement might be to use sitecore custom or out box role so active directory ldap role might not be worth to include.
  • Ensure you don't allow admin to action delete , edit of active directory users from sitecore. This may have implications. The rational: There could be service account or group created for content author and administrator user will be different from centralized security team. Let one team handle the removal of users from active directory server rather handle through sitecore.(Ensure you give read only permission to service account that is created in active directory server) This will allow one direction add and delete of users. This will help avoid accidental deletion from sitecore.
  • Understand Role and profile provider does not support SSL whereas membership support SSL only when it is trusted and known. (Need to explore more.) Therefore sometimes port 636 will not accept ssl certificate however sign and seal options are available with port 389 check ConnectionProtection attribute of LightLdap SitecoreAdMembership membership provider., the LDAPS connection should use a certificate which is properly validated by a Root CA:
  • This should be validated as per environment ‘sign-and-seal’ only works if the client (Web App VM) is on the same domain as the Server (AD Domain Controller) .Check below article web post by microsoft.
  • Consider credentials to be stored in key vault for azure environment. Downside the ldap membership provider of sitecore stores it in custom configuration unlike connectionstring or appsettings. For this to overcome you have to configure and initialize the sitecore membership provider at runtime in Application_start. I have given some reference code block to help you get around this.

https://social.technet.microsoft.com/wiki/contents/articles/2980.ldap-over-ssl-ldaps-certificate.aspx


Anton Jason, Has helped me with below solution reference. Later it helped me integrate this further.



Remember to add reference LightLdap.dll

public class ApplicationStartup
{
      
        public static void Startup()
        {
           
        }

        public virtual void Process(object args)
        {          
                SitecoreADMembershipProvider provider = new SitecoreADMembershipProvider();
                NameValueCollection config = new NameValueCollection();
                SitecoreADMembershipProvider provider = new SitecoreADMembershipProvider();
                 NameValueCollection config = new NameValueCollection();
                 // Configure your provider here. 
                 config["type"] = "LightLDAP.SitecoreADMembershipProvider";
                 config["name"] = "SomeProviderName";
 
                 config["connectionStringName"] = "LDAPConnString";
                 config["applicationName"] = "sitecore";
 
                 config["connectionUsername"] = ConfigurationManager.AppSettings["AppSettingKeys-UserName"];
                 config["connectionPassword"] = ConfigurationManager.AppSettings["AppSettingKeys-Password"];
 
                 config["minRequiredPasswordLength"] = "1";
                 config["minRequiredNonalphanumericCharacters"] = "0";
                 config["requiresQuestionAndAnswer"] = "false";
 
                 config["requiresUniqueEmail"] = "false";
                 config["connectionProtection"] = "secure";
 
                 config["attributeMapUsername"] = "sAMAccountName";
                 config["enableSearchMethods"] = "true";
 
                 config["customFilter"] = "(memberOf=Your org custom filter)";
 
                 provider.Initialize("SomeProviderName", config);
                 provider.AddTo(Membership.Providers);
        }
}

I used jetbrains dotpeek to look into sitecore LightLdap and it helped me understand how sitecore has created a custom wrapper
to implement its membership, role and profile.

Remember one thing there is struct MembershipProviderSettings which has all the above configuration defined.
This is protected if you planning to extend create custom class and inherit SitecoreADMembership provider. This is the only way out.


namespace LightLDAP
{
  public class SitecoreADMembershipProvider : MembershipProvider
  {
    protected bool initialized;
    protected MembershipProviderSettings settings;
    protected PartialDataSource source;

    public override string ApplicationName { get; set; }


    public SitecoreADMembershipProvider()
      : this((IAdMembershipProvider) new AdMembershipProvider())
    {
    }

    public SitecoreADMembershipProvider(IAdMembershipProvider innerProvider)
    {
      this.InnerProvider = innerProvider;
      this.settings = new MembershipProviderSettings();
    }

    public override void Initialize(string name, NameValueCollection config)
    {
      try
      {
        this.ApplicationName = config["applicationName"];
        this.settings.Initialize(config);
        config.Remove("serverPageTimeLimit");
        config.Remove("useNotification");
        try
        {
          bool isInnerFailed = false;
          try
          {
            this.InnerProvider.Initialize(name, config);
          }
          catch (Exception ex)
          {
            isInnerFailed = true;
          }
          try
          {
            this.settings.InitializeHidden(this.InnerProvider, isInnerFailed);
            this.source = DataStorageContainer.GetPartialSource(this.settings.AdsPath, this.settings.UserName, this.settings.Password, this.settings.AttributeMapUsername, this.settings.UseNotification);
            this.initialized = true;
          }
          catch (Exception ex)
          {
          }
          base.Initialize(name, config);
        }
        catch (Exception ex)
        {
          Log.Error("The AD membership provider couldn't be initialized: " + ex.Message, ex, (object) this);
        }
      }
      catch (Exception ex)
      {
        Log.Error("AD:", ex, (object) this);
        throw;
      }
    }
  }
}

Thursday, March 16, 2017

Sitecore Active Directory 1.3 Bug Reported: ProviderStatus throws error Unable to cast object of type 'Sitecore.Support.Security.SwitchingMembershipProvider' to type 'Sitecore.Security.SwitchingMembershipProvider'.

When you installed and setup Sitecore Active directory module 1.3 for update 8.2.1 it will throw below error. We reported this bug with sitecore support and they came up with required fix.


https://kb.sitecore.net/articles/520134

Tuesday, March 14, 2017

Sitecore Best Practice Avoid using sitecore intrinsic Controller name and action

Conflict with Sitecore Controller name: Multiple controller with same name

Avoid using AuthenticationController, HomeController and something more relevant to sitecore.

https://community.sitecore.net/developers/f/8/t/1634

This is the case when you are done with your development and you have enough time to check the event , iis and sitecore logs to cleanup your solution to meet good code and performance bench mark. Do consider this check before you come to this stage of clean-up. This will save time. I understand its cloud and such error doesn't matter. However its good to have less warnings in your logs. This will help you drill down to most critical error in production defects.

Having said that , scrutinize your logs during development using sitecore  log viewer or analyzer.


Monday, February 27, 2017

Sitecore Aligned Azure Cheat sheet

Access KUDU Service 

https://somewebsitename-staging.scm.azureservices.abc.com.au

Access File System- App Service Editor

https://somewebsitename-staging.scm.azureservices.abc.com.au/dev/wwwroot

Azure Key Vault

This required to safe guard important configuration key value pair.

https://docs.microsoft.com/en-us/azure/key-vault/key-vault-whatis


Sitecore Azure Diagnostics

https://marketplace.sitecore.net/Modules/Sitecore_Azure_Diagnostics.aspx

Sitecore Azure Blob storage logging

Features:
• Append regular, WebDAV, Search, Crawling and Publishing Sitecore diagnostics
• Based on Azure Blob Storage
• Append Blobs are used to store diagnostics as a text data
• Text data is compatible with Sitecore Log Analyzer tool
• Support multiple Web Apps instances
• Clean up out-of-date blobs using Sitecore Agent
• Support Sitecore Log Viewer application to open, download and deleted blobs.

Azure Storage Append Log

https://blogs.msdn.microsoft.com/windowsazurestorage/2015/04/13/introducing-azure-storage-append-blob/


Sitecore Azure Application Insights

https://doc.sitecore.net/sitecore_experience_platform/setting_up_and_maintaining/sitecore_on_azure/analytics/analyze_sitecore_logs_with_application_insights


https://mwenhao.wordpress.com/2017/02/06/ehh-where-is-my-sitecore-azure-log/

Sitecore Quick Cheatsheet

Introduction 

Just want to keep log of quick stuff that can act as quick reference. This will be work in progress , I'll keep adding as an when I come across things like this.

Protect Sitecore Item

Hide Sitecore Item


Package Sitecore Roles & Users

You can package sitecore Roles and Users. Refer screenshot. Add roles and users.

Sunday, February 26, 2017

Sitecore.Net Performance Findings & Recommendation 1

WeformView vs RazorView

Glimpse.axd: Performance output. 

Findings: 

Each view rendered with two view engines:Razor & WebForm. 

Type

Redundant + Overhead processing

Recommendations: 

Switch off unnecessary view engine if not required.



References:

http://blog.getglimpse.com/
http://stackoverflow.com/questions/5912980/turning-off-the-webformviewengine-when-using-razor






Thursday, February 23, 2017

Preview Transform and Add Transform OOB Issue with other config type

Configuration Transformation: Evironment Configuration


XDT: Transform

In recent times I have been working sitecore configuration config transformation for different environment and I came across the scenario where Add transform and Preview is supported in Visual studio only for web.config files not for other configuration. To fix this I just install Slow Cheetah extension and restarted my visual studio with project solution , everything works fine.

https://marketplace.visualstudio.com/items?itemName=WillBuikMSFT.SlowCheetah-XMLTransforms


Sitecore config builder
https://marketplace.sitecore.net/Modules/S/Sitecore_Custom_Config_Builder.aspx?sc_lang=en
https://marketplace.sitecore.net/modules/sitecore_configbuilder.aspx