Sunday, 4 December 2016

Retirement of MD5 hash algorithm


Recently, one of my clients got a letter from Bendigo bank mentioning that bank would no longer support MD5 and we need to change from MD5 to SHA-256


Changing MD5 to SHA-256 is not difficult the only tricky part is how to use secure secret key to generate hash.

To generate secure hash we need to Hex Decode the Secure Secret and use it in HMACSHA256 hasher. Hex decoding is independent of the character encoding.

This the proven way that bank needs it.


Tuesday, 29 November 2016

System.Web.WebPages.BuildManagerWrapper.IsNonUpdateablePrecompiledApp Method not found

If you get the following issue

Server Error in '/' Application.

Method not found: 'Boolean System.Web.WebPages.BuildManagerWrapper.IsNonUpdateablePrecompiledApp(System.Web.Hosting.VirtualPathProvider, Microsoft.Internal.Web.Utils.IVirtualPathUtility)'.

Description: An unhandled exception occurred.

Exception Details: System.MissingMethodException: Method not found: 'Boolean System.Web.WebPages.BuildManagerWrapper.IsNonUpdateablePrecompiledApp(System.Web.Hosting.VirtualPathProvider, Microsoft.Internal.Web.Utils.IVirtualPathUtility)'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[MissingMethodException: Method not found: 'Boolean System.Web.WebPages.BuildManagerWrapper.IsNonUpdateablePrecompiledApp(System.Web.Hosting.VirtualPathProvider, Microsoft.Internal.Web.Utils.IVirtualPathUtility)'.]
   System.Web.Mvc.BuildManagerViewEngine.GetPrecompiledNonUpdateable() +0
   System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +141
   System.Web.Mvc.BuildManagerViewEngine.get_IsPrecompiledNonUpdateableSite() +136
   System.Web.Mvc.BuildManagerViewEngine.FileExists(ControllerContext controllerContext, String virtualPath) +43
   System.Web.WebPages.DefaultDisplayMode.GetDisplayInfo(HttpContextBase httpContext, String virtualPath, Func`2 virtualPathExists) +51
   System.Web.WebPages.DisplayModeProvider.GetDisplayInfoForVirtualPath(String virtualPath, HttpContextBase httpContext, Func`2 virtualPathExists, IDisplayMode currentDisplayMode, Boolean requireConsistentDisplayMode) +157
   System.Web.Mvc.VirtualPathProviderViewEngine.GetPathFromGeneralName(ControllerContext controllerContext, List`1 locations, String name, String controllerName, String areaName, String cacheKey, String[]& searchedLocations) +466
   System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache) +203
   Castle.Proxies.Invocations.IViewEngine_FindView.InvokeMethodOnTarget() +274
   Castle.DynamicProxy.AbstractInvocation.Proceed() +111
   Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context, TimerResult& timerResult) +64
   Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +32
   Castle.DynamicProxy.AbstractInvocation.Proceed() +448
   Castle.Proxies.IViewEngineProxy.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache) +334
   System.Web.Mvc.<>c__DisplayClass6.<FindView>b__5(IViewEngine e) +45
   System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths) +114
   System.Web.Mvc.ViewEngineCollection.FindView(ControllerContext controllerContext, String viewName, String masterName) +242
   System.Web.Mvc.ViewResult.FindView(ControllerContext context) +118
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +143
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +90
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +833
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +833
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +710


There is a good chance that one of the following nuget packages  hasn't been updated properly.

  • Glass.Mapper.Sc.Core
  • Microsoft.AspNet.Mvc
  • Microsoft.AspNet.Razor
  • Microsoft.AspNet.WebPages

It happens when you have few projects in solution and you have forgotten to update all the projects to use same version.
the easiest way is to right click on solution and select "Manage NuGet packages for solution..." then look into consolidate tab.


resource:
http://stackoverflow.com/questions/25279024/upgrading-to-mvc-5-2-0-0-causes-exception-method-not-found-boolean-system-web

Thursday, 24 November 2016

seeing sitecore logs realtime, debugging tool

If you want to see sitecore logs in real time and you don't want to refresh and re-open the log to see new logs you can use free tool called mTAIL. mTAIL is a Windows Program that works like the Unix Command TAIL
you can download it from here
http://ophilipp.free.fr/op_tail.htm


Wednesday, 23 November 2016

It gets me every time

If you are trying to attach a db to your sql server and you are getting the following error, you need to run your management studio in administrator mode. Simply right click on Microsoft SQL Server Management Studio and select "Run as Administrator"

TITLE: Microsoft SQL Server Management Studio
------------------------------

Attach database failed for Server 'xxxxxx\sqlexpress'.  (Microsoft.SqlServer.Smo)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=13.0.14500.10+((SSMS_Rel).160415-0249)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Attach+database+Server&LinkId=20476

------------------------------
ADDITIONAL INFORMATION:

An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

------------------------------

Unable to open the physical file "xxxxxxx\data\Sitecore.Exm.mdf". Operating system error 5: "5(Access is denied.)". (Microsoft SQL Server, Error: 5120)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=12.00.2269&EvtSrc=MSSQLServer&EvtID=5120&LinkId=20476


Monday, 21 November 2016

Sitecore file explorer

One of the greatest debugging tools called Sitecore file explorer has been removed from sitecore menu since version 7.5
Sitecore file explorer is accessible by browsing /sitecore/shell/default.aspx?xmlcontrol=FileExplorer





When you don't have RDP access to Sitecore servers or when you don't have access to CI/CD servers logs to see which version has been pushed to server.
You can easily browse sitecore files with file explore. The main scenario is when QA team assign a bug to you and you cannot replicate it on your local machine. It would be a good idea to download the rendering or dll and user reflector and compare it with your local code. If you know when was the last release you can check your commit history but I found comparing files on server easier to find the root cause of the potential issue.

Note:
you can update files or upload files with sitecore explorer but it's not good idea to do that because of following reasons.


  • It's against all of the best practices 
  • You might have different content delivery servers and content authoring server. Updating files on one server doesn't automatically updates other servers.
  • If you update any config file it resets sitecore app pool



resource:
http://www.newguid.net/sitecore/2015/sitecore-8-enable-developer-center-xpath-builder-file-explorer/

Thursday, 10 November 2016

How to troubleshoot Tracker.Current is not initialized error in sitecore

If you are getting the following error 

Tracker.Current is not initialized
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Tracker.Current is not initialized
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:

[InvalidOperationException: Tracker.Current is not initialized]
   Sitecore.Analytics.Pipelines.StartAnalytics.StartTracking.Process(PipelineArgs args) +335
   (Object , Object[] ) +74
   Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +484
   Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, Boolean failIfNotExists) +39
   Sitecore.Analytics.Pipelines.StartAnalytics.StartAnalyticsPipeline.Run() +363
   Sitecore.Mvc.Analytics.Pipelines.MvcEvents.RequestBegin.StartTracking.Process(RequestBeginArgs args) +137
   (Object , Object[] ) +74
   Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +484
   Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain) +22
   Sitecore.Mvc.Pipelines.PipelineService.RunPipeline(String pipelineName, TArgs args) +193
   Sitecore.Mvc.Routing.RouteHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +74
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +923
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +157

There are few steps that you can follow to find the root cause of problem

0- Look into your sitecore logs

1- Look into Sitecore.Analytics.Model.config make sure all the custom interfaces you are defined are valid, configs might have been added on custom config file. It might be a good idea to look into /sitecore/admin/showconfig.aspx page and find all under model/elements/* and model/entities/facets/*

If you have element or facet pointing to invalid namespace you might get the above error.
You can comment out the custom ones and see if that fixes the issue. Then you can add elements and facets back one by one to find the culprit.

2-  make sure all the classes inherited from Sitecore.Analytics.Model.Framework.Facet are Serializable for more information have a read of this blog post https://mhwelander.net/2016/08/24/tracker-current-is-not-initialized/

3- Look settings of Sitecore.Analytics.Tracking.config and check how your shared state set it up.
make sure your connectionStringName is in your ConnectionStrings.config file and it's valid.

 <sharedSessionState defaultProvider="mssql">
        <providers>
          <clear/>
          <!-- To enable inProc, replace mssql provider with inProc
              <add name="InProc" type="System.Web.SessionState.InProcSessionStateStore" />
              SOPA CHANGES
          -->
          <add name="mssql"
               type="Sitecore.SessionProvider.Sql.SqlSessionStateProvider,Sitecore.SessionProvider.Sql"
               connectionStringName="sharedsession"
               pollingInterval="2"
               compression="true"
               sessionType="shared" />
        </providers>

        <manager type="Sitecore.Analytics.Tracking.SharedSessionState.SharedSessionStateManager, Sitecore.Analytics">
          <param desc="configuration" ref="tracking/sharedSessionState/config" />
        </manager>

        <config type="Sitecore.Analytics.Tracking.SharedSessionState.SharedSessionStateConfig, Sitecore.Analytics">
          <param desc="maxLockAge">5000</param>
          <!-- If an item in session state is already locked, this parameter is the time in milliseconds that the system is idle before making another attempt to apply a lock. -->
          <param desc="timeoutBetweenLockAttempts">10</param>
        </config>
      </sharedSessionState>


more read:
https://community.sitecore.net/technical_blogs/b/getting_to_know_sitecore/posts/introducing-contact-facets

Friday, 21 October 2016

Gulp webserver and live reload boilerplate


If you decided to have your site up and running without relying on iis.  Then I have a boiler plate for you.
Recently, I attended #SheHacks2016 hackathon. Every team member had different operating system. We narrowed done the tech stack that we were going to use. Also, we needed to find a neat way to host the web application. We used gulp-connect plugin to run a webserver. It worked absolutely well for us.


Why gulp?

Gulp helps to automate the repetitive tasks. It can be run on windows or mac operating systems. It also platform agnostic and has been integrated nicely into all major IDEs and can be used with PHP, .NET, Node.js, Java. Gulp is easy to learn and simple to use.

Here is the boiler plate that you can easily copy and pate and use it.


What you need to follow is


1- Download and install node.js 

2- Install gulp by running

npm install --global gulp-cli

2- Copy package.json and gulpfile.js from above gist and paste them into your root folder

3- Run npm install and node should install required packages.

npm install 

4- Run gulp , It should open a browser tab and load index.html

gulp 

5- If you start changing js or html files, gulp watch will reload the page automatically


references:

Thursday, 20 October 2016

How to have responsive hamburger menu and brand logo with boot strap v4 alpha

If you look into nav bar documentations of boot strap 4 you will notice the responsive  nav bar with hamburger menu like we used to have in boot strap 3 is missing.

The nav bars in version 4 are having different UX. In my opinion, there are so many sites based on boot strap 3 navbar and people get used to the way it is working. 
I personally would  prefer to stick with what people are used to than introducing new way of nav bar.


Here is the sample that you need to follow   

Friday, 14 October 2016

What is Flux?





Flux is the application architecture that Facebook introduced for building client-side web applications. It's a pattern rather than a framework. When you get the idea what flux does, it’s easier to understand and learn react.

If you have worked with angular, you know that angular follows two-way binding approach. Flux is going on the opposite direction and it follows unidirectional dataflow.
Flux architecture has three major concepts
  • Dispatcher 
  • Store/emitter
  • React component



What's actually happens behind the scene is, react initializes each react component and virtually renders them based on values has been set in getInitialState method. 

Then, react will compare the virtual Dom with browser Dom and updates only the differences.

React component needs to know when to re-render the view if initial data changes. It happens by registering itself to store/emitter and asking store to run a specific call back method if some changes happens. What needs to be done in this call back method is simply updating the state and setting it to the new value coming from Store, which will force a re-render of this component.

This setting easily can be done in componentDidMount and they can be unregistered from listening in componentWillUnmount method.

When a user interacts with any react components (views). React component lets the dispatcher know that an action has occurred, and the dispatcher let's every store/emitter (which have registered to be notified) know that that action has occurred.

It’s up to the store on what to do with that action, and the data that the dispatcher dispatches along with it.

Important point to notice is that the store doesn't need to emit what has changed. It only needs to emit the event that something has changed because all React needs to do is re-render its virtual DOM based on all the data, and then the DOM diffing algorithm will do the hard work of figuring out what to actually do inside the browser DOM.


React Life Cycle Involved in Flux architecture


getInitialState: Invoked once before the component is mounted. The return value will be used as the initial value of this.state.
componentDidMount: Invoked once, only on the client (not on the server), immediately after the initial rendering occurs.
componentWillUnmount: Invoked immediately before a component is unmounted from the DOM.

Dispatcher


An application can only one dispatcher. When user interact with React component. React component call the Dispatch method of Dispatcher and pass on the action and data.
 A dispatcher has two main methods:
Register: It register all the callbacks (Stores/emitters) that need to be executed/notified
Dispatch:  executes all the callbacks that registered to be executed and pass received data from react component

Emitter


An application can have multiple stores/emitters. Emitters have two main methods:
On:  registers the call-back methods which needs to be executed when a particular event occurs
Emit: executes all the callbacks that registered to be executed when this particular event has occurred

references:
https://facebook.github.io/flux/docs/overview.html
https://www.pluralsight.com/courses/react-flux-angular


Tuesday, 4 October 2016

React in nutshell


After my first failed attempt to learn react last year. I decided to give it a go again and learning it. I started watching Cory house’s(@housecor) tutorial on plural sight.
https://www.pluralsight.com/courses/react-flux-building-applications
Surprisingly, this time I found it fun to learn and easier to understand. The main thing that you need to keep in mind when you start learning react is, you need to forget what you have learnt in the past.
Prepare your brain to stop over analysing react with what you have known before and give react time to set in your brain. For years, we as developer, were putting our java scripts codes into html.  With react and jsx, you need to put html into java script files. We have learnt this approach as a bad practice in the past and our brain starts to guard against it as soon sees it. Look into react with open mind.

React in nutshell

React is a light weight view layer library and has a pluggable nature. It is only responsible for rendering views. Some saying that react is responsible for V in MVC and some argue that react is responsible for VC in MVC.
React is fast and responsive. It is efficient in how and when it manipulates the dom. It also eliminates layout thrashing by using virtual dom. It can work with ES5 (2009) or ES6 (2015) with Babel transpiler.


Reconciliation process

When react component is first initialized, the render method is called, generating a lightweight representation of the view. From that representation, a string of markup is produced, and injected into the document. When the data changes, the render method is called again. In order to perform updates as efficiently as possible, react differentiate the return value from the previous call to render with the new one, and generate a minimal set of changes to be applied to the DOM. The data returned from render is a lightweight description of what the DOM should look like.

React is component base and you can have multiple nested components.  It creates components by invoking the React.createClass() method which expects a render method.


Props and State concept

The Top level component(Controller/View) keeps the state of component and it passes down the data to its stateless children(components) via Props.
React thinks of UIs as simple state machines. You update a component's state, and then render a new UI based on this new state. React takes care of updating the DOM in the most efficient way.


React Life Cycle

React component has different life cycle phases and various methods are executed at specific points in a component's lifecycle. I categorizesh them into four categories as you can see in following.

1- Initialization
2- Mounting
3- Updating
4- Unmounting

Initialization:

  • getInitialState
    Invoked once before the component is mounted. The return value will be used as the initial value of this.state.
  • getDefaultProps
    Invoked once and cached when the class is created. Values in the mapping will be set on this.props if that prop is not specified by the parent component 


Mounting:

  • componentWillMount
    Invoked once, both on the client and server, immediately before the initial rendering occurs
  • componentDidMount
    Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. 


Updating:

  •  componentWillReceiveProps
    Invoked when a component is receiving new props. This method is not called for the initial render.
  • shouldComponentUpdate
    Invoked before rendering when new props or state are being received. 
  • componentWillUpdate
    Invoked immediately before rendering when new props or state are being received. This method is not called for the initial render.
  • componentDidUpdate
    Invoked immediately after the component's updates are flushed to the DOM. This method is not called for the initial render.

Unmounting: 

  • componentWillUnmount
    Invoked immediately before a component is unmounted from the DOM.




@tylermcginnis33  showed the pipeline nicely in above diagram.




resources:
https://facebook.github.io/react
https://www.pluralsight.com/courses/react-flux-building-applications
https://tylermcginnis.com/an-introduction-to-life-cycle-events-in-react-js-aa3796ad85aa











Thursday, 18 August 2016

Episerver Alloy Demo kit

If you are new to Episerver like me you need to start looking at
https://github.com/episerver/AlloyDemoKit

what is missing in their document is after cloneing and getting latest version you will get

The serviceUrl cannot be empty

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Configuration.ConfigurationErrorsException: The serviceUrl cannot be empty


the reason is in your web.config you need to update following settings

<episerver.find serviceUrl="" defaultIndex="" />

simply create an an account with
http://find.episerver.com/

go to
http://find.episerver.com/MyServices/AddFreeIndex

put and index name and select english and then select create index







Saturday, 13 August 2016

SOLID Principles for beginners with real world examples

Did you know around 47 percent of projects had higher-than-expected maintenance costs? But why is that?

Have you ever worked on a project that is?
1-Rigid
The design is hard to change. It is very difficult to modify, either to change existing functionality or add new feature. Most of tasks are under estimated and you keep hearing “oh man, it was a lot more complicated than I thought.” from engineering team
2-Fragile
There is no design . Changes cause cascading effects to many places. The code breaks in unexpected places that have no conceptual relationship with the changed area. fixing the problems causes new problems. Keep hearing “not again” a lot from testing team
3-Immobility - Non-reusable
The design is hard to reuse
the code is so tangled that it is impossible to reuse anything
imagine you want to reuse a login module than has been developed by another team and
hearing “a module could be reused but the effort and risk of separating it is too high and takes longer than writing it from scratch” from engineering team


In object oriented programming is based on three pillars
1- Encapsulation
2- Inheritance
3- Polymorphism

 Robert C. Martin (uncle bob) introduced five basic principles of object-oriented programming and design in the early 2000s.Luckily, if we apply those together, it helps us to create a system that is easy to maintain and extend over time.

What is SOLID?

1.Single-Responsibility Principle (SRP): 

A class should have only one reason to change.

A responsibility is “a reason for change” in this context, when a class has more than one responsibility, there are also more triggers and reasons to change that class.

It doesn’t mean a class should have only one method, it means all the methods in the class should be related to the class's primary function. In other words, it should have only one job to do.

Real world non-technical example:
Imagine each body organ is a class. If you think about it. you can quickly realize each of them does only one job and they have one responsibly. Your heart is responsible for pumping blood. Your lungs are responsible for absorbing oxygen and removing carbon dioxide.

Imagine your kidney was responsible for your pumping blood and filters blood and takes the waste?
how would be difficult if a surgeon wants to do kidney transplant or small surgery?
how much time will it take for a small surgery?
how much knowledge your surgeon should gather and analysis before operation?
what would be the side effects after surgery?


2.Open–Closed Principle (OCP): 

Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

“Open to extension” means that you should design your classes so that new functionality can be added as new requirements are generated.
“Closed for modification” means that once you have developed a class no one should modify it.
but how does it possible? how can we extend a class without modifying it!!! These two parts of the principle appear to be contradictory!
A class is closed, since it may be compiled, stored in a library and used by client classes. But it is also open, since any new class may use it as parent, adding new features. When a descendant class is defined, there is no need to change the original or to disturb its clients

Real world non-technical example:
Imagine you have a kid and you want your kid learns how to swim, do you take him to doctor and ask for operation appointment so you kid can swim! No! you don’t modify your kid’s abilities.
You take him/her to activity centre and enrol him in swimming class and extend his abilities to float, to dog paddle and to swim


3.Liskov Substitution Principle

if S is a subtype of T, then objects of type T may be replaced with objects of type S

code that uses a base class must be able to substitute a subclass without knowing it. An object should be substitutable by its base class (or interface).

Real world non-technical example:
Imagine of dishwasher tablet as base class with one public method clean, you go to super market and chose any dishwasher tablet because they all inherited from same base class and when you get home and put it dish washer you expect it to cleans dishes and doesn’t explode the dishwasher!
4.Interface-Segregation Principle

client should not be forced to depend on methods it does not use

This means that when one class is dependent to another, the number of members in the interface that is visible to the dependent class should be minimised.

Real world non-technical example:

Do you remember you wanted to extend the swimming abilities of your kid and took it to activity centre to extend your kids abilities to swimming? Imagine the principle says, sorry you cannot enrol your kid only to learn swimming. Since our class are bundled and in order you kid learns how to swim he needs to go to tap dancing classes and drawing and singing and you need to pay for all together although your kid doesn’t want to go to those classes.

5.Depency-Inversion Principle
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.

Real world non-technical example:
Imagine in your organization you need to deliver a website (high level module). The website shouldn’t be dependent on individuals (Eric, Lisa, …) or how they do their job. It should depend on disciplines (abstracts) like developer, BA, PM, Tester!

Also your PM(abstraction) shouldn’t be depend on individuals. Let’s say our PM only can work with Tess and Eric! Your PM can work with other disciplines (abstracts) (designer, UX, Developer and tester)

Applying solid principle to your code is not hard and it doesn’t need massive investment, but the benefit you will get by applying it is not ignorable.  Your code will be easily extended, modified, tested, and refactored without any problems.

May SOLID become a part of you and your code 

slides:
https://docs.google.com/presentation/d/1wov4uJh-geJF0VoT_GwhFPJJ1D0M2kGZFRhEooMD-pc/edit?usp=sharing

resources:
http://www.cnet.com/news/62-percent-of-it-projects-fail-why/
https://en.wikipedia.org/wiki/Single_responsibility_principle
https://en.wikipedia.org/wiki/Open/closed_principle
https://en.wikipedia.org/wiki/Liskov_substitution_principle
https://en.wikipedia.org/wiki/Interface_segregation_principle
https://en.wikipedia.org/wiki/Dependency_inversion_principle
http://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/

Light Streamer Step by Step on windows

Lightstreamer(http://www.lightstreamer.com/) is a high-performance push/streaming engine based on the AJAX-Comet paradigm that delivers real-time textual data to Web browsers and to thick applications.

I found their documents all over the place so I decided to aggregate all the steps we need to follow in one place.


To test and see how lightstreamer wroks
1- download MODERATO from http://www.lightstreamer.com/download/
Lightstreamer Moderato edition can be used for free even in production environments and does not require any license key. http://www.lightstreamer.com/ls-features
2- unzip downloaded folder 
4- you need to copy lightstreamer.js from \ Lightstreamer\DOCS-SDKs\sdk_client_web_unified\lib  to \Lightstreamer-example-HelloWorld-client-javascript\src
5- edit  \Lightstreamer-example-HelloWorld-client-javascript\src\index.html and change 
     var client = new LightstreamerClient(null,"HELLOWORLD");
to
    var client = new LightstreamerClient("http://push.lightstreamer.com/", "HELLOWORLD");
6- open /Lightstreamer-example-HelloWorld-client-javascript/src/index.html in browser and you should be data getting updated 


 

As you see above, data get pushed from http://push.lightstreamer.com/ to our html page.
Light streamer server has two responsibilities 
1- host Adapters and get data from them 
2- Serve Clients and send data that adapters has been provided

An Adapter is a software component that connects Light streamer Server and provides data.
A Client connects and subscribe to Light streamer Server to get the real-time data.

How to Set Light streamer Server locally on windows 
1- You need a Java SE platform implementation installed on your system.
You can get the latest version from Oracle (you can choose either the
Server JRE or the JDK):

2- Open notepad in admin mode and open \Lightstreamer\bin\windows\LS.bat file and update the value of JAVA_HOME to location of your java sdk
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_102

3- in command prompt go to the \Lightstreamer\bin\windows directory and execute
"Start_LS_as_Application.bat".

4- to verify your Light streamer server is working and is listening to tcp ports, browse http://localhost:8080

Now the Light streamer server is ready to host Adapters and Clients, stop service by entering Ctrl+C in command prompt to stop service

*Update client to point to our local server
1- edit  \Lightstreamer-example-HelloWorld-client-javascript\src\index.html and change 
var client = new LightstreamerClient("http://push.lightstreamer.com/", "HELLOWORLD");
to
var client = new LightstreamerClient("http://localhost:8080/", "PROXY_HELLOWORLD");

*Set .Net Adapter to send data to light streamer
2- copy ProxyHelloWorld  folder from \deploy\Deployment\Deployment_LS\ProxyHelloWorld and past it  to \Lightstreamer\adapters

*Run server and .net adapter and client
1- in command prompt go to the \Lightstreamer\bin\windows directory and execute "Start_LS_as_Application.bat".

2- in another command prompt window go to the \deploy\Deployment\Deployment_DotNet_Server   directory and execute “adapter_csharp.exe”
3- open /Lightstreamer-example-HelloWorld-client-javascript/src/index.html in browser and you should be data getting updated 

Wednesday, 6 July 2016

What to do if you don't see sitecore habitat specflow tests in visual studio 2015 test explorer


I opened Habitat.TestScenarios.sln solution and noticed my visual studio 2015 test explorer is sad and empty.

however when I tried ReSharper I could run tests with it after installing "xUnit.net Test support for resharper". You can install it easily by going to Resharper and then extension manger in visual studio.





To get list of your tests into Visual studio Test Explorer window you need to add "xunit.runner.visualstudio" nuget package to your projects. you can easily add it by right clicking on your solution and selecting "Manage NuGet Packages for solution" and then in Browse tab search for "xunit.runner.visualstudio" and select all the sitecore feature projects and select install.

after that you should be able to see list of tests.



resource
https://github.com/xunit/xunit/issues/295
https://resharper-plugins.jetbrains.com/packages/xunitcontrib/

Sunday, 26 June 2016

unity and umbraco


If you are getting following error after upgrading your umbraco


The current type, Umbraco.Core.Models.IPublishedContent, is an interface and cannot be constructed. Are you missing a type mapping?

you are not alone :) I spent my precious Sunday afternoon to resolve it. 

Tuesday, 21 June 2016

copy/transfer sitecore content items from web to master

Have you ever switched to web and accidentally add content nodes and later realize the nodes are missing in master?

way 1:
Right click on the item in the content tree and select coping>transfer



way 2:
go to sitecore desktop and select Control panel and then select Move an item to another database
source:


the rest is straghit forward you select the destination db and folder and sitecore copies the item to master or core db.



Friday, 6 May 2016

My notes on security

Basic Authentication in ASP.NET Web API


Advantages       
Internet standard.
Supported by all major browsers.
Relatively simple protocol.
Disadvantages
User credentials are sent in the request.
Credentials are sent as plaintext.
Credentials are sent with every request.
No way to log out, except by ending the browser session.
Vulnerable to cross-site request forgery (CSRF); requires anti-CSRF measures.

HMAC: Hash base Message Authentication Code

Advantages
Data integrity: The data sent by the client is intact and not tampered.
Request origination: The request comes from a trusted client.
Not a replay request: The request is not captured by an intruder and being replayed.






aws: Authenticating Requests Using the REST API


aws api gateway




Azure: Secure ASP.NET Web API 2 using Azure Active Directory


var clientCredential = new ClientCredential(clientId, secret);
 var authContext = new AuthenticationContext("https://login.microsoftonline.com/" + Maccount, false);

 AuthenticationResult authenticationResult = authContext.AcquireToken(MclientId, clientCredential);

Tuesday, 12 April 2016

Migrating cloned item to Sitecore 8.1 and above


After migrating content from 7.2 (rev. 140526) to 8.1 (rev. 151003). We noticed Sitecore shows the standard value like $name token instead of original value for unchanged fields on cloned items. Also, “Created from” field on cloned items shows “unknown” instead of linkage to the source item.




As you can see in the following link, Sitecore has introduced a new field named “__Source Item” in version 8.1 to increase the performance of getting item operation for regular and cloned items.


https://community.sitecore.net/developers/f/5/t/2062

To solve this problem we have to run a query on items and updated the cloned items. After setting the value for “__Source Item” field on cloned items, Sitecore shows the expected values for all of the unchanged fields and showing linkage to source item on “Created from” field.
For having better performance making sure we are not killing the web server I followed the following strategies:

1- Created a new sitecore admin page to update the fields, It's password protected and only accessible to administrators

2- Disabling indexing while updating the cloned items fields

3- Running the updates asynchronously by splitting the update process into 11 tasks (11 threads)

Monday, 25 January 2016

Web forms for marketers missing formItem


I encountered the following issue in our test environment I thought it worth to share it here.
If you get the following issue it means WFFM couldn't find the location of your forms.
By default forms are stores under "/sitecore/system/Modules/Web Forms for Marketers/Website" sitecore item node. The forms root can be overwritten in site node.

To resolve the issue make sure formsRoot is pointing to valid path

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <sites>
      <site name="llcomauthortest" patch:before="site[@name='website']" hostName="ll.dev.xxxx.com" virtualFolder="/authortest" physicalFolder="/test" rootPath="/sitecore/content/xxxx/test" startItem="/home" database="master" domain="extranet" allowDebug="true" cacheHtml="true" htmlCacheSize="10MB" enablePreview="true" enableWebEdit="true" enableDebugger="true" disableClientData="false" mvcarea="xxxx" mvcNamespaces="xxxxxx" formsRoot="/sitecore/content/xxxx/Shared/Forms" enableItemLanguageFallback="true" appendSlashes="true" siteResolving="true" />
    </sites>
  </sitecore>
</configuration>


formItem

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: formItem

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[InvalidOperationException: formItem]
   Sitecore.Form.Core.Configuration.ThemesManager.RegisterCssScript(Page page, Item form, Item contextItem) +822
   Sitecore.Forms.Shell.UI.CreateFormWizard.OnLoad(EventArgs e) +599
   Sitecore.Forms.Shell.UI.InsertFormWizard.OnLoad(EventArgs e) +108

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +76
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +211
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
   Sitecore.Web.UI.Sheer.ClientPage.OnLoad(EventArgs e) +337
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178

Thursday, 21 January 2016

All you need to know about creating branch and sending git pull request with Visual Studio Team Services

We can benefit a lot from by simply adding pull request and code review in our process of application development. In my opinion code review should be must and not optional. It may take time to bring everyone on board but every single person can benefit from the change later.


1- Reduce number of bugs because we find bugs early
2- It helps to keep code consistent 
3- More people are across the same user story (business rules, code implementation)
4- Developers have better view and bigger picture of solution
5- Teaching and sharing knowledge on best practices 

Mapping working item and git commit:

It would be a good practice if we ask everyone to add #{work item id} in their commit. It will help to track commits in TFS.
It would be easier for testers/managers to see if any work has been done for the particular bug or task, also it will save time for trouble shooting in future.


If you add #taskID in your commit visual studio team services picks the commit and maps it with work item





resource:
https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/4038344-associate-a-git-commit-with-a-work-item
http://www.codewrecks.com/blog/index.php/2013/01/31/associate-work-items-to-check-in-in-a-tf-service-git-enabled-repository/

Creating New branch:

For creating branch we need to follow the following steps

1-     Switch  to your master branch
2-     Make sure having the latest version on our local
3-     Create a new branch based on  your master branch

Using Team Explorer:

Open Team Explorer  view in visual studio

1-     Switch  to your master branch
open branches tab
2-     Make sure you have the latest version running
right click on your master branch and select checkout



3-     create a branch
right click on the local master branch ( the one you want to create a branch from ) and select New Local Branch from... 




Using visual studio Online:

Go to https://{yourdomain}.visualstudio.com
Select Project and then click on Code then select Explorer
https://{yourdomain}.visualstudio.com/DefaultCollection/_git/{yourproject}





Using git bash:

Open git bash, go to your repository directory

1-     switch  to your master branch
git checkout feature
2-     make sure you have the latest version by running
git pull origin <master branch name>
3-     create a branch
git checkout –b <branch name>



More read:
 https://www.atlassian.com/git/tutorials/using-branches/git-branch


Pull Request:

Using team Explorer:




Click on New Pull Request



Using visual studio Online:

Go to https://{yourdomain}.visualstudio.com
Select Project and then click on Code then select Pull Requests
https://{yourdomain}.visualstudio.com/DefaultCollection/_git/{project name}







Add Reviewers:



Approve review:

https://{yourdomain}.visualstudio.com/DefaultCollection/_git/{project name}








More resource:
https://channel9.msdn.com/Events/Visual-Studio/Connect-event-2015/207
http://blogs.msdn.com/b/visualstudioalm/archive/2014/06/10/git-pull-request-visual-studio-online.aspx

Friday, 8 January 2016

Are you behind proxy?


node js and proxy

npm config edit --global

proxy=http://yourIP:Port/
https-proxy=http://yourIP:Port/
strict-ssl=false

or run this following command lines
npm config set proxy http://yourIP:Port/
npm config set https-proxy http://yourIP:Port/


Bower and proxy
add proxy to your .bowerrc file

{
  "directory": "./packages",
  "proxy": "http://yourIP:Port/",
  "https-proxy": "http://yourIP:Port/",
  "strict-ssl": false

}


Git and Proxy

git config --global -e

[http] 
        proxy = http://yourIP:Port/
        sslVerify = false 
[https] 
        proxy = http://yourIP:Port/

or directly run this following commands

git config --global http.proxy http://yourIP:Port/
git config --global https-proxy http://yourIP:Port/
git config --global strict-ssl false


Showing markers on google map v3 with dynamic zoom level by leveraging sql server to show closest landmarks to the specific latitude and longitude


Latitude measures how far north or south of the equator a place is located. The equator is situated at 0°, the North Pole at 90° north (or 90°, because a positive latitude implies north), and the South Pole at 90° south (or –90°). Latitude measurements range from 0° to (+/–)90°.

Longitude measures how far east or west of the prime meridian a place is located. The prime meridian runs through Greenwich, England. Longitude measurements range from 0° to (+/–)180°.

Well-known text (WKT) is a text markup language for representing vector geometry objects on a map

POINT(Longitude  Latitude )


Steps

1- Create a table in sql server database to store all of your landmarks latitudes and longitudes. 
2- Create a web API/Service that gets the position (latitude and longitude) and returns back the list of land marks closest to the point – it’s configurable to set number of expected landmark and radius of search)
3- Implement UI 




Good reads:
https://technet.microsoft.com/en-us/library/bb964711(v=sql.120).aspx
http://weblog.west-wind.com/posts/2012/Jun/21/Basic-Spatial-Data-with-SQL-Server-and-Entity-Framework-50
http://www.sql-server-helper.com/sql-server-2008/convert-latitude-longitude-to-geography-point.aspx
http://www.spyriadis.net/2010/07/calculate-distance-between-locations-in-sql-server-2008-using-geography/

Similar scenarios:

http://stackoverflow.com/questions/15719951/google-maps-api-v3-auto-center-map-with-multiple-markers
http://stackoverflow.com/questions/19304574/center-set-zoom-of-map-to-cover-all-markers-visible-markers
http://stackoverflow.com/questions/5405539/google-maps-v3-why-is-latlngbounds-contains-returning-false

Wednesday, 6 January 2016

How to set windows authentication for sitecore websites on IIS



These are few steps that you need to follow to have windows (AD) authentication on your local environment.


1- Add windows Authentication Feature to IIS
2- Enable Windows Authentication
3- For making sure TDS is working as expected enable Anonymous Authentication
4- Add DisableLoopbackCheck to your registery


1.          Click Start, click Run, type regedit, and then click OK.

2.          Locate and then click the following registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa

3.          Right-click Lsa, point to New, and then click DWORD Value.

4.          Type DisableLoopbackCheck, and then press ENTER.

5.          Right-click DisableLoopbackCheck, and then click Modify.

6.          In the Value data box, type 1, and then click OK.

Tuesday, 5 January 2016

How to reuse web forms for marketers forms in sitecore - without coding

The problem that I had to find a solution for was basically our content editors wanted to create a form with WFFM and reuse it on different pages. 
By default if you use page editor and try to insert form. You have two options one is creating a new form and another one is coping form existing form which you will end up with multiple copies of a same form.

The solution that I came up with is 


1- Copy /sitecore/layout/Renderings/Modules/Web Forms for Marketers/Mvc Form and give it a name "Custom Form"

2- Set the Data source location


3- Add the new rendering to place holder settings 
/sitecore/layout/Placeholder Settings/content


--------------------------------------

When I twitted about my post I got a message from @jammykam that he solved same issue with coding which is nicer approach.

You can read his post here
https://jammykam.wordpress.com/2015/10/05/webforms-for-marketers-allow-selection-of-existing-forms/