Thursday, May 23rd, 2013

“Date” is Tricky and Dangerous.. Not in Real Life , but in Javascript

You gotta handle it with Care !!!

Here is code below :

function callOnLoad()
{
var startDate = "2013-5-02" ;
var endDate = "2013-5-23" ;
var d1 = new Date(startDate);
var d2 = new Date(endDate);
var browsername=navigator.appName;
alert("Start Date : " + d1) ;
alert("End Date : " + d2) ;
alert("Compare if Start Date < End Date");
if (d1 < d2)
{
alert ("Result : Start Date < End Date ") ;
}
else
{
alert ("Result : End Date <= Start Date") ;
}
if (browsername.indexOf("Microsoft")!=-1)
{
alert("Now find out why is the difference in " + browsername);
}
}

CompleteJunk

Open “CompleteJunk.html” in Chrome, Mozilla and Internet Explorer and Have Fun !

Category: Javascript  | Leave a Comment
Monday, May 20th, 2013

 

The Microsoft source analyzer for C#, StyleCop can be used to enforce a set of styling and consistency rules among .Net teams in a project/ company. StyleCop can be run as a visual studio plugin or can be integrated with an MSBuild project. StyleCop provides an  extensible framework for plugging in custom rules for the developers.  For implementing a custom rule, the user needs to create a custom rules analyzer class which inherits the SourceAnalyzer and overrides the AnalyzeDocument method to check for violations.
In this post, I’ll show how you can implement extensible custom rules in stylecop by using the visitor pattern.
 
Creating the custom rule analyzer class:
[SourceAnalyzer(typeof(CsParser))]
publicclassMyCodeStandardAnalyzerRules : SourceAnalyzer
{
    publicoverridevoid AnalyzeDocument(CodeDocument document)
    {
        var csDoc = document asCsDocument;
        if(csDoc == null) return;
        if(csDoc.HasEmptyRootElement() ||
csDoc.IsAutoGeneratedCode())
return;
        csDoc.WalkDocument(
                ElementVisitor, null, null
            );
    }
    privatebool ElementVisitor(CsElement element, CsElement parentelement, object context)
    {
        //Implementing the custom rules for CsElement goes here
    }
}
 
Creating the visitor interface
publicinterfaceIVisitor
{
    void SetSourceAnalyzer(SourceAnalyzer alanyzer);
    void Visit(CsElement element);
}
 
Writing the first visitor
publicclassCheckForConstantsHaveUpperCaseNameVisitor : BaseVisitor, IVisitor
{
    publicvoid Visit(CsElement element)
    {
        if (element.ElementType != ElementType.Field || !element.Declaration.ContainsModifier(CsTokenType.Const))
            return;
        if(element.Name.Any(char.IsLower))
            AddViolation(element, RuleNames.CONSTANTS_SHOULD_BE_IN_UPPERCASE,
element.Name, element.LineNumber);
    }
}
publicclassBaseVisitor
{
    privateSourceAnalyzer _sourceAnalyzer;
    publicvoid SetSourceAnalyzer(SourceAnalyzer sourceAnalyzer)
    {
        if (sourceAnalyzer == null) thrownewArgumentNullException(“sourceAnalyzer”);
        _sourceAnalyzer = sourceAnalyzer;
    }
    protectedvoid AddViolation(ICodeElement element, string rule, paramsobject[] values)
    {
        _sourceAnalyzer.AddViolation(element, rule, values);
    }
}
 
Creating the Element class to accept the visitor
publicclassCodeElement
{
    privatereadonlySourceAnalyzer _analyzer;
    privatereadonlyCsElement _element;
    public CodeElement(SourceAnalyzer analyzer, CsElement element)
    {
        _analyzer = analyzer;
        _element = element;
    }
    publicvoid Accept(IVisitor visitor)
    {
        visitor.SetSourceAnalyzer(_analyzer);
        visitor.Visit(_element);
    }
}
 
The visitor dispatcher to resolve all visitors (Using a dependency injection container is much easier J)
publicclassVisitorDispatcher
{
    privatestaticVisitorDispatcher _dispatcher;
    privatestaticreadonlyobject _lockObject = newobject();
    publicList<IVisitor> Visitors { get; privateset; }
    publicstaticVisitorDispatcher Instance
    {
        get
        {
            if (_dispatcher == null)
            {
                lock (_lockObject)
                {
                    _dispatcher = newVisitorDispatcher();
                    var visitors = from type inAssembly.GetExecutingAssembly().GetTypes()
                                    where type.IsAssignableFrom(typeof(IVisitor))
                                    selectActivator.CreateInstance(type)
asIVisitor;
                    _dispatcher.Visitors = newList<IVisitor>(visitors);
                }
            }
            return _dispatcher;
        }
    }
}
 
Finally visiting the element with the visitors
privatebool ElementVisitor(CsElement element, CsElement parentelement, object context)
{
    if (element.IsAutoGenerated()) returntrue;
    var codeElement = newCodeElement(this, element);
    VisitorDispatcher.Instance.Visitors.ForEach(codeElement.Accept);
    returntrue;
}
The last step is to build your project and drop the new project’s dll into the StyleCop installation directory and run the style cop
rules on your projects. Style cop will automatically look for assemblies in the directory and pick up the new rules for your team.
Author:
Monday, May 20th, 2013

It could happen that you may have authentication and also authorization in your web application.
The authorization could be at page level and you need to enforce that in every page of your web application.

In these kind of scenarios httpmodule could turn out to be very handy. Httpmodule could be made
to behave like an gate keeper who on every request would check with the page being requested if the
request is from valid user or not. Below C# example would make it clear what I am talking about,

//Define interface which every page is required to implement
public interface IAuthorization
{
bool IsPageAccessible();
}

public partial class RequestedPage : Page, IAuthorization
{
public bool IsPageAccessible()
{
//Your authorization check logic goes here
}
}

public class AuthorizerHttpModule : IHttpModule
{
void httpModule_AuthorizeRequest(object sender, EventArgs e)

{

IAuthorization pageToAuthorize = HttpContext.Current.Handler as IAuthorization;

//Enforce authorization to be implemented.
if(pageToAuthorize == null) { //throw exception}

if(!pageToAuthorize.IsPageAccessible()){ //Redirect to unauthorized page}

}

}

Category: .Net, Security | Tags: , ,  | Leave a Comment
Friday, May 17th, 2013

I: “I have a simple requirement to be accomplished using Javascript. Can you help me on this?”
You: “Not Again !!!!”
I: “Write a function to return sum of two number passed as arguments”
[By the time I finish reading the requirement you will have the below code]
You: “Here you go !” [With a teasing smile and a dirty look at me ]

function add(x,y)
{
return x + y;
}

Now, the usual thing : Requirement Changes :P
I: “Instead of two parameters I want to pass 10 values as parameters and get the sum of the values. Can you do this?”
You: “You are wasting my time, but still I can do this simple task”
[After thinking for a while you start rewriting the function by adding 10 parameters....I wait and watch and by the time you complete adding 9th parameter...]
I: “Oops ! Requirement changes again, now I need the function to work for 50 parameters..”
You: “Get Lost ! I am not doing this”
I: “Let increase the complexity and add 50 more…and more…and more…”
You:!!!!????

Don’t worry! Dynamic Parameter Handling in Javascript will come for your help

Testing Javascript

/*
Function Name : addFunction
Parameters : Dynamically Passed during Invokation
Description : This Function is used to add the numbers passed as parameters
Input : param1,param2.....paramN
Output : This Function will display the Sum in alert box
*/
function addFunction()
{
var total = 0;
for (var i=0;i<addFunction.arguments.length;i++) //Retrieving the arguments passed
{
total += addFunction.arguments[i];
}
alert('Sum of numbers = ' + total);
}

/*
Function Name : callOnLoad
Parameters : N/A
Description : This Function is invoked on Page Load
Input : N/A
Output : This Function will inturn invoke addFunction();
*/
function callOnLoad()
{
addFunction(10,20,10,10); //Invoking Function with 4 Parameters
}

Category: Javascript  | Leave a Comment
Sunday, May 12th, 2013

 

Every imperative operation in the system represents a command in CQRS. A Command is simply a DTO-type of object that contains the data necessary to make one specific change to the state of the system. The service method that accepts a command does not returns any values. In case of WCF services, if the command execution failed, a fault contract exception is thrown. The method that accepts the command is responsible for validating the command via a command validator object (remember SRP :) ) before passing it to a
handler object to execute the command.
Below is an example of a DTO that encapsulates the command information in our sample. Note that the commands have an Identity object in our sample.
public class RespondToRsvpCommand : ICommand
{
    public Guid RsvpReferenceId { get; set; }
    public bool Response { get; set; }
    public override string ToString()
    {
        return“Respond to RSVP”;
    }
}
 
The command handlers are responsible for executing the commands.
You can normally group commands to an aggregate in a command handler as given
below.
public class RsvpCommandHandler : ICommandHandler<RespondToRsvpCommand>, ICommandHandler<ConfigureRsvpCommand>,
                                    IDependencyResolver
{
    [InjectionConstructor]
    public RsvpCommandHandler()
    {
        ResolveDependencies();
    }
    private ICommandValidator<RespondToRsvpCommand> RespondToRsvpCommandValidator { get; set; }
    private ICommandValidator<ConfigureRsvpCommand> ConfigureRsvpCommandValidator { get; set; }
    public void Process(RespondToRsvpCommand command)
    {
        //RSVP
processing logic goes here
    }
    publicbool Validate(ConfigureRsvpCommand command)
    {
        returntrue;
    }
    publicvoid Process(ConfigureRsvpCommand command)
    {
        //throw
new NotImplementedException();
    }
    publicbool IsValid(RespondToRsvpCommand command)
    {
        return RespondToRsvpCommandValidator.Validate(command);
    }
    publicbool IsValid(ConfigureRsvpCommand command)
    {
        return ConfigureRsvpCommandValidator.Validate(command);
    }
    publicvoid ResolveDependencies()
    {
        RespondToRsvpCommandValidator = Container.Current.Resolve<ICommandValidator<RespondToRsvpCommand>>();
        ConfigureRsvpCommandValidator = Container.Current.Resolve<ICommandValidator<ConfigureRsvpCommand>>();
    }
}
 
As you can see, I’ve used the ICommandValidator instances to validate the respective commands in the context. I’ve also used the unity dependency container as my dispatcher object to dispatch the respective command handlers.
Next: Events
Sunday, May 05th, 2013

CQRS is an object oriented architectural pattern built on the principle that every method should either be a command that performs an action, or a query that returns data to the client, but not both.

A typical CQRS scenario involves 2 DB’s, a write DB which is used to store transitional data for long running processes.  For a process where a service expects multiple messages, it needs a way to temporary store data before the all the messages arrives. For e.g. to make a customer a preferred customer needs an approval from the management, which takes some time to process the request. The service will need a temporary storage for the preferred customer state change request till the approval comes. The write DB is used to store these kinds of data. The Read DB is not updated till the approval comes.

When the approval finally comes, the service will take the customer information from the write DB, complete the registration process and write it to the read DB. At this time, the temporary customer information in the write DB has done its job and can be removed from the write DB. For simpler process such as change customer first name, the change can be written to the read DB right away. Writing to the write DB is not required because there is no temporary data in this case.

This simple approach brings following benefits (from Rinat Abdullin’s blog)

  • Denormalized query persistence is optimized for the reads (which usually make up the most of the persistence IO) resulting in better performance and user experience;
  • We can optimize our read side for the needs of the UI (i.e.: fetching dashboard for the user in a single query) which will result in better development experience and less risk of breaking something on the write side.
  • Read side can be put on some cloud storage, which is inherently optimized for the reads, could be partitioned, replicated and even distributed via CDN;
  • By offloading data reads to synchronous queries we automatically increase the performance of the write side – now it has lower stress and lower probability of hitting a deadlock

This blog is an attempt to implement the principles of CQRS in a very simple way, for demonstrating the concepts of CQRS like:

  • Commands
  • Command Handlers (validation and execution)
  • Queries
  • Query parameters and Query results
  • Command Dispatchers.
Next : Commands

 

Author:
Wednesday, May 01st, 2013

In this post I will present my views on various aspects of software architecture. These views are not limited to any specific technology.

What is Software Architecture?

A software architecture is typically a set of design decisions to address various non-functional requirements and attributes of a software system/application. It primarily focuses on aspects such as performance, reliability, scalability, testbility, maintainability and various other attributes, which can be key both structurally and behaviorally of a software system.

Architecture phase Architecture vs design

All architecture is design, but not all design is architecture

A new software product development requires a strong focus on some of these non-functional attributes based on the domain and the nature of the application. It establishes the context for design and coding. Example: A banking application may require special attention on security and availability of the application. Architectural decision have to be well thought to setup a strong base and long term view into consideration; its not only very difficult to change these decisions later on, but, will have significant ripple effects on the software.

Some of the things to keep in mind when architecting a software solution are:

  1. A, do not reinvent the wheel policy – Best architects copy solutions that are already proven in the software world. Architects are the one who adapts them to the current context, improve upon their weaknesses and design in such a way that it enables incremental improvements.
  2. Simplest architectures are the best – One always has to remember that there will be trade-offs. Example: For a highly scalable system you will trade off cost. Attempting to put an architecture in place which addresses all the non-functional attributes, you are asking for the trouble. By this approach you are not only creating complexity into the system but, making it extremely difficult for the design and implementation team.
  3. Demo’able architectural blueprint – A software architecture blueprint should ultimately be converted into executable code. It should not be a mere sketch on a paper or a soft-copy of the model, which the software designers find impossible to visualize and construct.
  4. Key responsibilities - Define and validate the system’s architecture, maintain the conceptual integrity of the system, assess and attack technical risks to the system, resolve the design and implementation teams conflicts, document the architecture.
  5. Keep tool set upto date – Modern day software requires architects to have updated tool sets in their bag to fulfill various challenges. They particularly have to be aware of how to effectively use them. There are several out of the box architectural tactics, patterns to help architect solve recurring problems.

I plan to cover some of these patterns and tactics in my next post.

 

Category: General  | Leave a Comment
Wednesday, May 01st, 2013

 

Most of the tests for a product backlog are defined in terms of UI as that’s how the P.O or stakeholders think of the user story. Creating
UI tests is also important for agile teams as it is a way of telling our customers that the user acceptance scenarios are tested and  verified on every release and he/ she is going to use the application which is intended to work as he/ she expects. But integrating the UI automation tests with the builds (CI) comes with some challenges like browser configurations, non-interactive sessions etc. For these reasons frameworks that do not drive an actual browser, but simulate browser behaviors are becoming popular among agile teams.
 NHtmlUnit is a .Net wrapper of HtmlUnit a UI-less browser for Java programs. It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc… just like you do in your ”normal” browser. NHtmlUnit can be easily integrating with other unit testing frameworks like NUnit, MSTests etc.
A simple example of testing web pages using NHtmlUnit is as given below.
[TestClass]
public class SampleAppSmokeTestSuite
{
    private WebClient _webClient;
    [TestInitialize]
    public void TestInitialize()
    {
         _webClient = newWebClient(); 
    }
    [TestCleanup]
    publicvoid TestCleanup()
    {
        _webClient.CloseAllWindows();
    }
    [TestMethod]
    publicvoid UserLoginAcceptanceScenario()
    {
        var loginPage = _webClient.GetPage(“http://localhost:42017/Home.aspx”) asHtmlPage;
        Debug.Assert(loginPage != null, “loginPage !=
null”
);
        var header = loginPage.GetElementById(“header”);
        Assert.AreEqual(header.TextContent, “NHTML UNIT”);
        var txtUserName = loginPage.GetElementById(“txtUsername”);
        var txtPassword = loginPage.GetElementById(“txtPassword”);
        txtUserName.SetAttribute(“value”, “user@mailserver.com”);
        txtPassword.SetAttribute(“value”, “password”);
        var submitButton = loginPage.GetElementById(“btnLogin”);
        var homePage = submitButton.Click() asHtmlPage;
        Debug.Assert(homePage != null, “homePage !=
null”
);
        var homeHeader = homePage.GetElementById(“header”);
        Assert.IsTrue(homeHeader.TextContent.Contains(“Welcome”));
    }
}
The test initialize methods creates a WebClient object, which is the starting point for NHtmlUnit tests. This object acts as your browser simulator. The GetPage method returns the html page for the Uri passed to the method. The IPage object represents a single web page along with all of the client’s data including HTML, JavaScript, and CSS etc. You can now use this HtmlPage object to access the DOM elements by using methods like GetElementById, or GetElementByClass or GetByXPath etc. Once the elements are accessed you can use the object model to get or set values on these elements and perform actions like Click to simulate the actual behavior of the user. By integrating with an existing unit testing framework, you can do your assertions to validate the results.
Author:
Wednesday, May 01st, 2013

In most webpages we judiciously use jQuery and a few other JS plugins. Plus some of our own JS files. We also have a bunch of CSS files and images. Which means when our webpage is loaded in the browser, it has to make several requests to the server to get all the additional files. Sure, the browser tries to fetch several files in parallel. But most browsers put an upper limit to how many parallel requests to make. In most cases this limit is 6. That means if your web page refers to more than 6 files, then some files will have to wait till others have been downloaded. Its easy to see examine this behavior using your browser’s developer tools (Chrome developer tools, Firebug or IE’s F12 window). On most browsers you can hit F12 key to access developer tools. You can find out which files are being requested by your browser and in what order from the Network tab. Here’s an example of how it looks in Chrome:

chrome dev tools

As you can see from the picture some files are loaded after other have finished. Hence you can significantly reduce the load time of your page by referring as few files as possible. There are also tools/libraries that can help you combine several JS files into one (CSS files too). If you are using images to achieve a gradient look, try using CSS gradient instead. May be some files are not needed in a some pages. Anyways, you can figure out a suitable solution once you know what’s going on and the Network monitoring feature of your browser can help you figure out just that.

Firefox users can use Firebug: http://getfirebug.com/network

IE users can use Internet Explorer Developer Tools: http://msdn.microsoft.com/en-us/library/gg130952(v=vs.85).aspx

Happy optimizing!

- Anand Gothe

Category: CSS3, General, HTML5  | One Comment
Author:
Saturday, April 27th, 2013

Any development project leads to maintenance at some point. It is very natural and expected as customers start using the software over a period of time. A scrum team having done several successful development sprints finds it really challenging to adapt such a change. Some of the challenges are:

  • Rapidly changing release dates and priority.
  • More flexibility and responsiveness is expected from the team.
  • Team requires a different kind of thought process as it involves a lot of analysis, for instance to reproduce customer reported issue, dig deep into the existing code base to identify flaw in the code and then eventually put a fix in place.
  • Team communication with customers or Product Owner also is a challenge, as you may require his/her help to reproduce a scenario and also assistance during the analysis.
  • Sprint goals can vary. As maintenance sprint would also require to address ad-hoc emergency bug fixes and testing.
  • Code quality and some other practices like code review generally takes a back seat

and the list goes on….The question arises, Is scrum or agile a best fit for maintenance or legacy projects?

The answer is YES!!!. Why? Because, the primary purpose of agility is to help the team handle lots of uncertainty, adapt to change, shorter release cycles, production ready software. These attributes are more essential and makes more sense (or equal) when a team is doing a maintenance sprint than a development sprint.

Some techniques that I found to be very effective for maintenance sprints are:

  • Maintenance bucket: Allocate a percentage of sprint capacity of the team for addressing maintenance issues. This will ensure that the other sprint goals not related to maintenance are intact. A Product Owner can choose the percentage depending on the number of issues that the customer reports and application stability. This makes more sense when team is focusing both on development and maintenance stories in same sprint.
  • Just enough Refactoring – Ensure that every possible opportunity is utilized to refactor the code as you touch the legacy code. This is possibly the best phase to reduce the technical debt.
  • Automate bugs - Often you’ll see that the customer reported issues shows up more than once. Developer usually blames the lack of quality code, unit tests and so on. Automating fixed scenarios will ensure that you don’t see them again. Its not the only and the best solution, but, fits best when you don’t have time to refactor/redesign code to make it more unit testable.
  • Development sprints should have a focus on reducing technical debt – Its very difficult to always focus on step 2. because teams usually do not have enough time to refactor code when customers are waiting for a fix. Team also don’t refactor because they are afraid of making mistakes. A wise approach in such situations would be to allocate time in every development sprint to add more stability factor into the code. Refactor Incrementally!!
  • Collaboration and communication with Product Owner and customers – Its strange, but true. Working closely with PO and customer is more essential during maintenance sprints than probably required during development sprints. This is because team has to be on top of things to do adequate analysis, team has to understand the customer usage scenarios, reproducing the problem, understand the context in which the old code was written and providing solutions.

To summarize, A maintenance sprint can be hard to stick to practices and process that the team has been following in development sprints. However, Agile methods if applied as discussed, team will be able to leverage its benefits and perform well.