View Ravichandran J.V.'s profile on LinkedIn RJV 's Blog Tweet @ravichandranjv

Translate

Tuesday, 19 August 2014

Angular.Js - Funny parser !!

You will need a HTML5 compatible browser to try this but it will be sure to rock you.

The funny part is line # 5. You are welcome to leave funny or witty comments. Please do not get overboard over the technical aspects, though.

If you remove the line, the result will be 5 !!!


The code:

1. < !doctype html >
2. < body >
3. < div ng-app="" ng-init="quantity=1;cost=5" >
4.

5. < p > {{quantity=quantity+1}} < /p >
6. Total in dollar: {{ quantity * cost }}
7.

8.

9.
10.


But the same when used within the scope of an angular module will work predictably as below. This is because the
tag that was the application's main entry point in the above scenario (where ng-init is initializing the 'quantity' variable but the increment was happening inside an AngularJS expression), is now being used as a controller by the module. 


The $scope of the controller is the application (the div tag) it is referred from.


But the good thing is that there is no index out of bounds exception and so the control moves to the next line even if the index used for an array element is out of bounds !!

And, the best part is it works like the good old pointers !!



Result is {{ points[5] }}
Result is {{ points[2]+points[4] }}
Result is {{ points[2+1] }}
Result is {{ points[2*2] }}

Tuesday, 5 August 2014

Patterns and nuts!

Ask yourself this - Why do they always put a nut in a place where the spanner cannot reach it? - when you find the problem and the design pattern not matching.

All problems could be the same. It is only the context, the domain, the applicability, the robustness that the solution must be subject to, the experience and maturity of the solution provider that make problems unique and different.

A psycho's reactions can be easily simulated in a child and for those to whom the child is not visible, from afar or through heresy or by reading about it, both will seem the same. It is this knowledge that is important to make decisions and not whether the similarity of actions with a psycho makes a child a psycho nor whether the psycho is a child.

This knowledge, the ability to dwell deep to the real core of a problem, is what is necessary to know where designs emerge and which design patterns to decide on.

Tuesday, 15 July 2014

Blogger post from ASP.Net

Sample post! It looks like setting a draft post to false on the AtomEntry object does not work or it is simply a matter of providing the postId alongwith the blogId and not setting the URL to default feeds.

Below is the code: (you can use NUGet to install the Google API into your VS project)

using System;
using Google.GData.Client;
using System.Web.UI;

namespace BloggerPost
{
    public partial class _Default : Page
    {
        string blogId = ""; // This id will be part of the query string in your browser address bar when you access your blog
        string username;
        string password;
        private void PostOrUpdateBlogPost(string yourBlogId,bool isUpdate)
        {
            if (yourBlogId != null)
            {
                var service = new Google.GData.Client.Service("","Application Name");
                service.Credentials = new GDataCredentials(username, password);
                AtomEntry newPost = null;
                if (isUpdate)
                {
                    try
                    {
                        // need to correct the URL here
                        newPost = service.Get(yourBlogId);
                        newPost.Categories.Clear();
                        // Setting the isDraft property requires the above URL to contain the postId (need to confirm test this).
                        if (newPost.IsDraft) newPost.IsDraft = false;
                    }
                    catch (Exception ex)
                    {

                    }
                }
                else
                {
                    newPost = new AtomEntry();
                    newPost.Title.Text = "Blogger post from ASP.Net";
                    newPost.Content = new AtomContent();
                    newPost.Content.Content = "Sample post! It looks like setting a draft post to false on the AtomEntry object does not work or it is simply a matter of providing the postId alongwith the blogId and not setting the URL to default feeds.";
                    newPost.Content.Type = "html";
                }
             
                try
                {
                    if (!isUpdate)
                    {
                        Uri blogPostUri = new Uri("http://www.blogger.com/feeds/" + yourBlogId + "/posts/default");
                        newPost = service.Insert(blogPostUri, newPost);
                    }
                    else
                    {
                        newPost = newPost.Update();
                    }
                }
                catch (Exception ex)
                {              
                }
            }
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PostOrUpdateBlogPost(blogId,false); // the boolean is to specify if it is a new post or an update.
            }
        }
 
    }
}

Publishing a post using the Google API for Blogger!

It is not as easy as many have posted on the web! Many posts indicate that all you need to do

is send in your credentials to the service object. Not as simple as that !

Blogger API Post


This post was created with the Blogger API v3

Tuesday, 17 June 2014

Two singularly complex problems - Arrays and Lists

The delightful aspect of programming in C# is the large number of possibilities, to resolve a problem, available to a programmer in the form of different forms of implementations across versions of the underlying technology and framework.

It is delightful because two different programmers may provide a solution to the same problem, without differing in technique, because the implementation of the same language feature across the different versions of the C# language compiler are different.

It can be torrid, though, if you do not enjoy the intricacies of working with different types in the CLR and/or the underlying unmanaged types of the Windows platform.

1. Unmanaged array - the 'mysterious' object[*]

The Microsoft.Office.Interop,Excel Chart object presents a challenge in the way it exposes the Chart's series collection's data values.

For instance, if you want to read the Chart's Source Data range/Data Table, the problem is in the way the series collection exposes each series' data values. Being a System.ComObject, the series.Values (that represent each Chart Series values) returns an unmanaged array !! What is so surprising, you may ask?

The surprise is that you may convert it to an object array but may inadvertently leave out testing it as it will compile ok. At runtime, though, an error that an object of type [,] cannot be converted to an object of type [] will be thrown!

The exasperating aspect of this error has to be experienced to really appreciate the nature of the error !!

The reason it is exasperating is because you may try creating an Array with CreateInstance and while it should work, at a glance,

var array = System.Array.CreateInstance(
                            typeof(object),
                            new int[] { totalColumns },
                            new int[] { totalRows });
array = series.Values;

it does not !

The solution is to iterate through the series.Values as below:

// --- 1. Get ChartObjects in worksheet
//-- 2. iterate through the chart object's series collection

foreach (object seriesValue in series.Values as System.Array)
{
double d = (double)seriesValue;
list.Add(d);
}

The trick is to convert the unmanaged array values into an array while iterating through it !

Best Practice
3. If you are using a System.ComObject in a for... or foreach... loop make sure to release the COM object with Marshal.ReleaseComObject in the System.Runtime.Interopservices namespace in the finally block of a try...catch as below:

foreach (..... ComObject in ...){
try{
....
}
catch{}
finally{
if (object!=null)
Marshal.ReleaseComObject.(...);
}
}

Remember, you cannot set a ComObject used in a loop to null ! A runtime exception will be thrown if you attempt to do so.


2. Compare two Lists or Arrays

The option to obtain the iterated value into an array or a list is as per your requirement.

In both the cases, you may want to work with both the array or the list. 

Below are two techniques to compare, using, first, the TrueForAll Linq method (make sure to add the System.Linq namespace) as below.

                            var list = new System.Collections.Generic.List();
                            var list1 = new System.Collections.Generic.List();

                                            if (list.TrueForAll(list1.Contains) && list1.TrueForAll(list.Contains))
                                            // --

Or, convert the array into a List and use the System.Array's SequenceEqual check for an array,

object[] rangeValueArray = (from item in list select item as object).ToArray();
object[] seriesValueArray = (from item in list1 select item as object).ToArray();

if (rangeValueArray.SequenceEqual(seriesValueArray))
// --
else if (!rangeValueArray.SequenceEqual(seriesValueArray))
// --

This method helps check if the elements are equal plus in sequence !

Thursday, 15 May 2014

Logic or laundry list?

Just as a person with a good understanding of English and nodding in understanding , when told that "E is equal to MC square", does not make for a genius, similarly, piling up a list of 'permutations and combinations' does not make for good application of logic.

Below is such an example that I came across recently.

A file being opened from a Open Dialog box, of the same name and from within the same file.



I have seen some teams go into a frenzy of analysis over such a simple use-case of "Open a file" and believe it to be a thorough analysis whereas, it is the classic example of "over-kill", "over-analysis" (similar to it in normal life is what is called "Beating about the bush"), where a person uses a crane to pick up a bucket just because, being an Engineer, the 'world' (a collection of people hardly numbering above two digits) would be agreeable to the idea.

There are some fine boundaries that define every field of study, and logic, due to the increase in population, has become multi-layered for some types of people (maybe due to lack of maturity, knowledge or clarity in attitude and approach towards life) but that does not in anyway redefine the application of logic.

Even if "a 'kid' can program nowadays" adage may be true but the fact remains that the many other 'layers' in the above example, like education, training, time, context and many etcs that come before it will make a difference in either speeding up the "kid's" application of logic or in becoming a totally useless application of a  'laundry list' of scenarios that may just affect the design, performance, speed and security of the program logic!!

So, what then is 'solid logic' in today's world?

Nothing.

Only that logic that stands up to tests and succeeds, is 'logical'.

Not the knowledge of operators or all that computer science nonsense jargon but simply, tests.

Not tests as 'software testers' believe tests to be but tests that have a conceptualization point before any implementation of logic - what is called Tests Driven - Development or Design.

What makes this (TDD) the most workable technique is because of the multi-layers that the external world imposes on an use-case even before it reaches a design table.

It is like trimming and sprucing a problem to find what is the real problem that needs to be solved because unless you know what the real problem is, will you not simply be 'beating about the bush' ? :)

Sunday, 23 March 2014

Agile Test Driven Design - Design evolving out of tests

Pre-requisites before you read this - Knowledge of the WCF framework, Web Service Consumption, Unit and Mock Tests and a basic understanding of the difference between a HTTP session context and an examination context (time allotted for tests, questions etc) and a lot of detached reading ability (Nothing directed at anyone personally even though it may seem so) :)

The code and the tests are executable-ready and tested so please do not troll with useless questions or responses.

Agile and the pleasure of Test Driven Design Development

Agile is not so much a pleasure when working with an Agile team as it is a pain when confronted with argumentative, subjective 'technical' experts; when the latter happens, you begin to realize how difficult it is to explain simplicity to these 'expert' project managers to accept their shortcomings and accept that they are not project managers but experts in creating crises and then managing it !

Documentation is 'Tests'

Documentation is the 'D' word - it is like the threat of a nuclear holocaust, the moment the word crops up in a team it is indicative that some reactive measures has crept into the development steps adopted by the team.

The incident of a tester not knowing how to open a VS TS and work with builds but still having the 'confidence' to pull up developers is an indicator of how some believe that having a 'team' writing some nonsense lines on Skype group chat or referring to each other as 'team' is what a team means and that 'testers' have read somewhere that customers write tests in Agile and therefore, being a tester means that the tester is a customer !

There are better PJs doing the rounds than having to encounter such 'poor jokes' within your work environment and that, too, which stinks so much!

Getting back to the D word - the best form of documentation that a team could be blessed with is when a test (Unit, mock or acceptance) 'tells' or 'communicates' how the design of the class, the signature of the method or even the data type of a data member should be.

It is really fortunate that I came across a 'real' example where I could demonstrate how Tests actually works, communicates and evolves a design into a near perfect one - and in far less time than you could conceive of.

I am extracting a simple service out of the whole system below to show how tests should be used to design, right from the beginning of a project.

The requirement

A service model (WCF) that enables a candidate to log in to an online examination application with a service contract as,

using System.ServiceModel;

namespace ABC.LoginService
{
    [ServiceContract]
    public interface ILoginService
    {
        [OperationContract]
        UserInfo DoLogin(string email, string password);

        [OperationContract]
        CandidateSessionInfo GetCandidateSession(UserInfo userInfo);
    }
}

and two data contracts for Candidate's session (not the HTTP session) and user information.

namespace ABC.Service
{
    [DataContract]
    public class CandidateSessionInfo 
    {
        int _id;
        string _title;
        DateTime _startDate;
        DateTime _startTime;
        DateTime _endTime;

        [DataMember]
        public int ID
        {
            get { return _id; }
            set { _id = value; }
        }

        [DataMember]
        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }

        [DataMember]
        public DateTime StartDate
        {
            get { return _startDate; }
            set { _startDate = value; }
        }

        [DataMember]
        public DateTime StartTime
        {
            get { return _startTime; }
            set { _startTime = value; }
        }

        [DataMember]
        public DateTime EndTime
        {
            get { return _endTime; }
            set { _endTime = value; }
        }
    }

    [DataContract]
    public class UserInfo
    {
        int _id;
        string _name;
        string _email;

        [DataMember]
        public int ID
        {
            get { return _id; }
            set { _id = value; }
        }

        [DataMember]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        [DataMember]
        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }
    }
}

WYTNWYG (What You Think Is Not What You Get) 

This is an example of preconceived notions i.e., WYTNWYG  of Design principles. 

The service contract is simple - it outlines two basic requirements of a login operation but the design begins to go awry in the data contracts that is to provide the login infastructure. 

Let me demonstrate how, through the below tests written in Rhino Mock and NUnit.

using Rhino.Mocks;
using ABC.Service;
using NUnit.Framework;

#if DEBUG
using WebOperationContext = System.ServiceModel.Web.MockedWebOperationContext;
#endif

namespace ABC.MockServices
{
    [TestFixture]
    public class ServicesTests
    {
        WebServiceClient client;
        ILoginService sstudentMock;
        UserInfo studentUnderTest,obj;
        int loginId;
        CandidateSessionInfo sessionObj, sessionUnderTest;

        [SetUp]
        public void init()
        {
            sstudentMock = MockRepository.GenerateMock();
            client = new WebServiceClient(sstudentMock);
        }
        [Test]
        public void testStudentLogin()
        {
            studentUnderTest = new UserInfo();

            studentUnderTest.Email = "abc@gmail.com";
            studentUnderTest.ID = 1;
            studentUnderTest.Name = "abc";
            sstudentMock.Expect(t => t.DoLogin("abc@gmail.com", "pass")).Return(studentUnderTest);
            loginId = client.Login("abc@gmail.com", "pass");
            Assert.AreEqual(studentUnderTest.ID, loginId);
            sstudentMock.VerifyAllExpectations();
        }
        //[Test]
        //public void testSessionForLoginTime()
        //{
        //    sessionUnderTest = new SessionInfo();
        //    sessionUnderTest.ID = 1;
        //    sessionUnderTest.Title = "abcSession";
        //    sessionUnderTest.StartDate = DateTime.Now;
        //    sessionUnderTest.StartTime = DateTime.Now;
        //    sessionUnderTest.EndTime = DateTime.MaxValue;
        //    loginId = client.Login("abc@gmail.com", "pass");
        //    sstudentMock.Expect(t => t.GetSession(obj)).Return(sessionUnderTest);
        //   // sessionObj=student.GetSession(obj);

        //   // Assert.AreEqual(sessionUnderTest.StartTime, sessionObj.StartTime);
        //    //sstudentMock.VerifyAllExpectations();
        //}
        //[Test]
        //public void testSessionForLoginSessionTitle()
        //{
        //    sessionUnderTest = new SessionInfo();
        //    sessionUnderTest.ID = 1;
        //    sessionUnderTest.Title = "AbcSession";
        //    sessionUnderTest.StartDate = DateTime.Now;
        //    sessionUnderTest.StartTime = DateTime.Now;
        //    sessionUnderTest.EndTime = DateTime.MaxValue;
        //    loginId = client.Login("abc@gmail.com", "pass");
        //    sstudentMock.Expect(t => t.GetSession(obj)).Return(sessionUnderTest);
        //    //sessionObj = student.GetSession(obj);           
        //   // Assert.AreEqual(sessionUnderTest.Title, sessionObj.Title);
        //    //sstudentMock.VerifyAllExpectations();
        //}

    }
}

The first test, testStudentLogin, is fine but it is when you move to the next user story - 'getSession...' that the tests, related to the CandidateSessionInfo object tells you, "Hey, as per your design, you need to supply a UserInfo object, where is it?" 

Because 

1. Being on the web platform, you need to send the userinfo object to the getsession...method after the candidate logs in successfully or 
2. Refactor the design.

It is not as simple as choosing between the two - a design, when you arrive or decide it, must have 'testable' artifacts to justify the decision and this is where 'tabled design' fails and test driven design scores!

The test above has communicated (the feedback) that either the contract of the getsession...method is wrong or your programming logic that is not able to maintain the user info object state.

The answer now becomes simple. Your development efforts (and therefore the logic part) has not even started so obviously the choice is clear - refactor the operation contract. (Of course, this explanation of how to make this design decision is only for explanatory purposes - the actual parameters to making this decision could be entirely different based upon the composition of a team or the architect's experience and maturity.)

To  continue...with explanation on why the tests are commented out.

Saturday, 22 March 2014

Agile anecdotes (repeat)

Scenario: Newly married. 


1. Agile stresses on Early Releases


Husband, newly inspired by Agile; wife, waterfall model!:P


End of iteration - Wife frustrated, customer satisfied, husband, disgusted with Agile,

declares "Agile No good"



2. Agile stresses on more testing


Scenario: House Owner - Tenant


Owner, newly inspired by Agile


Due to water scarcity, owner wants to test if the tenant closes all the taps before going out 

of house and starts running the water motor after the tenant leaves the house.


End of iteration - Due to exploitation over water, tenant kills owner. 

Friday, 21 March 2014

Holi Hai ! :) List of Colors - C#

Working with colors is always fun but for that you must have the colors first.

It is like an old joke of mine -

To be or not to be a Macbeth is not the question; the real question is, Lady Macbeth has to be for Macbeth to be or not to be!

So, when I ventured to have a user select a color from a drop-down list for a software module, I was a little surprised (like the cat in the tree on seeing a dog climbing up to say hello to her) that it was not as simple as that.

Lady Macbeth may have known how to poison her husband but she had the poison and that is the crux of the matter - a resourceful woman, for her times!

Then I chanced upon the fact (Google search is almost a fact now) that Reflection (as in System.Reflection) had the solution but the real problems are faced only when you work towards the solution.

Lady Macbeth, too, must have thought it would be hunky-dory all the way until she found  that she really could not taste the poison herself to know what quantity to give to Macbeth ! :D

It is not as if she had to mix Coke or Pepsi with some other drink - she really could not know the taste of poison so, how could she ensure that her prey, her husband, would not find it distasteful and throw it away before drinking it?

The problem is that System.Drawing.Color is not really an enumeration that can be enumerated upon as it does not have a colors collection! So, how to compare the color values after the user inputs the color, when asked "Tippi, tippi, tap, what color do you want?" ?

The solution is to compare the name of the colors by storing the 'reflected' colors into an array of strings and then compare using a foreach loop to match the selected color.

Below is the code:

public class MyColorList{

private string[] colors = null;
private string colorSelected = null;

            private void listAllColors(){
                int colorIndex = 0;
                System.Type colorType = typeof(System.Drawing.Color);
                System.Reflection.PropertyInfo[] colorInfoList =                                                                                               colorType.GetProperties(System.Reflection.BindingFlags.Static |
                    System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Public);

                colors = new string[colorInfoList.Length];

                foreach (System.Reflection.PropertyInfo propertyColor in colorInfoList) {
                    colors[colorIndex] = propertyColor .Name ;
                    colorIndex++;
                }
            }
            private string getColor(string colorName)
            {
                foreach (string color in colors)
                {
                    if (colorName.ToLower() == color.ToLower())
                        colorSelected= color;
                }
                return colorSelected;
            }
}
// Method Calls
            listAllColors();
            currentColor = getColor(ColorAsString);

(c) Of course, needless to say, what happened between Lady Macbeth and Macbeth was their own private affair and none of the world's business but because Shakespeare disagreed with the view that I thought of highlighting it, safe with the knowledge that it was probably not as private as the English Royalty would have it, if it was discussed so vividly in public.