Wednesday, March 30, 2016

Few Impoortant Tips for writing XPath

1. In XPath , indexing does not start with zero.

2. '/' absolute path and start with root node where as '//' is relative path start with curretn node.

3. '.' means current node where as '..' is parent node.

4. '*' means all child node from current node or path.

5.   While writing xpath we can not leave /by pass any element.

6. <book>
   <title lang= "en"> Harry Poter</title>
   </book>
lang = "en"  (attribute node)  @
//div[@id = 'file1']   // id is attribute for div.

7. We can select some row based on attribute.
.//*[@id='container']/child::div[1]/div[2]/div[@id = 'file2']/table/tbody/tr/td[3]/div/attribute::title
Means each row which have div tag under that have attribute name  title.
Example:
<div class="l lc d1" title="Diff 1: Change 4 lines (1 - 4, first file) to 4 lines (1 - 4, second file)">
<div class="l lc d1" title="Diff 1: Change 4 lines (1 - 4, first file) to 4 lines (1 - 4, second file)">
<div class="l lc d1" title="Diff 1: Change 4 lines (1 - 4, first file) to 4 lines (1 - 4, second file)">
<div class="l lc d1" title="Diff 1: Change 4 lines (1 - 4, first file) to 4 lines (1 - 4, second file)">
8. We can access last to one element usign last().

<tr>
<td class="diffBar" style="">
<td class="nums">
<td class="content">
Above example we can access "nums" and "Content" using last-1 , last-2 fucntion.


.//*[@id='container']/child::div[1]/div[2]/div[@id = 'file2']/table/tbody/tr/td[last()-2]
.//*[@id='container']/child::div[1]/div[1]/div[@id = 'file1']
.//*[@id='container']/child::div[1]/div[2]/div[@id = 'file2']/table/tbody/tr/td[3]/div/attribute::title

Tuesday, March 29, 2016

Agile Software Development : Scrum


Scrum is a iterative and incremental agile software development framework for managing  development. An Iterative Project Management process. Does not include any engineering practices like XP.
Commonly used for product development 
Split into 3 Areas:
 -Roles  (Product owners, Scrum Master, Scrum Team)
- Ceremonies (Sprint Planning ,Sprint Review, Sprint Retrospective,)
- Artifacts (Sprint Backlog, Product Back log , Burn down chart)
 
Product Owner:
 - Maintain product backlog.
 - Define no of sprint .
 - Know domain knowledge.
 - Should understand business ,market , end user
 
Scrum Master:
- Enforce values and Practices.
- Removes impediments to progress.

 
Planning Meeting:
 - High Level overview of User stories.
 - Attended by all team members.
 - Stakeholders and users may attend.

Sprint Review:
- Shippable product at end of sprint
- Sprint assessed against goals
- Review is held with all team.
- Achieving goal is most important.
 
Sprint Retrospective:
- Attend by all including Product owner.
- 3 Questions:
    - What should be stop doing ?
    - What should be start doing.?
    - What should continue doing.?
Scrum VS XP
- Scrum duration is 2-4 weeks long called sprint
- XP duration is 1-2 weeks long.
- Scrum does not allow changes in sprint where as XP allows changes .
- Scrum product owner prioritizes the product backlog but the team determines the sequence in which they will develop the backlog item.
- Extreme programming team work in strict priority order.
-Scrum does not prescribe any engineering practices. where as extreme programing follow engineering practices like TDD, Pair programming and Continuous integration.

 
                                               Agile Team Practice Fundamentals
Principles:
- Iterative Delivery
- Frequent Feedback
- Transparency  and Openness
- Lean Principles
Extreme Programming(XP)
 Good Practice          Pushed to the  Extreme
 Code Reviews          Pair Programming
  Testing                     TDD and Constant regression
  Software  Design   Relentless Refactoring
  Simplicity                 The Simplest thing could possibly work
  Integration Testing   Continuous Integration
  Short Iterations       The Planning Game
                                            Agile Requirement and Estimation:
A requirement is
     - Independent
     - Negotiable
     - Valuable
      - Estimable
    - Size Appropriately
    - Testable
User Stories
As a <Role> I Want  <features> so that <benefit>.
Given <Context> when <something happens> then <desired result>
Example:

User Story: Customer’s Cash Withdrawal

As a Customer,
I want to withdraw cash from an ATM,
So that I don't have to wait in line at the Bank
 
                                                                   Estimation
Based on Size and complexity ,not duration
Story Points Value: Story points are unit of measure for expressing the overall  size of a user story , feature or task.
Use Planning Poker
    - XS,S,M,L,XL,XXL
    - 1,2,3,5,8,13,20,,40
    - 1,2,4,8,16,32
 
Sprint Velocity:Velocity is the number of story points completed by a team in an iteration.
 
We need velocity to: Predict how much scope can be delivered by a specific date Predict a date for a fixed amount of scope to be delivered Understand our limits while defining the amount of scope we will commit for a sprint -
How do we calculate velocity? Simple! We do some basic math.

Scenario: Our team delivers 3 user stories. The sum of the story points equals 20. Our velocity is then 20.

If, in the next iteration, our team delivers 30 story points, then our average velocity is 25, or (20 SP + 30 SP) divided by 2 iterations = 25 SP.
 
 
                                                  Burn - Down Chart
The sprint tracking is usually done using Burn-Down Chart. Burn-Down Chart shows the remaining effort in day-wise number of hours. For example, let us consider a 2-week sprint -
Sprint Duration: 2 Weeks
No. of Days per Week: 5
No. of Hrs. per Day: 6
No. of Resources: 6
Hence, total remaining effort at the beginning of sprint is 2*5*6*6 = 360 hrs.

Burn-up Chart

Burn-up chart’s mechanics is basically the same. The only difference is that instead of tracking how much work is left to be done, we track how much work we’ve completed, so the curve is going up, not down.

Agile Advantages:
  -Customer Satisfaction by rapid, continuous delivery of useful software.
  -People and interactions are emphasizing rather than process and tools.
 - Continuous attention and technical excellence and good design using TDD ,refactoring.
  - Regular adaption to changing circumstances.
  - Early return on investment.
  - Feed back from Real customers.
   - Build right product. 


Note: Creating Scrum Board using JIRA tool , follow below link for more info...
https://confluence.atlassian.com/agile/jira-agile-user-s-guide/creating-a-board
 

 

Read/Write operation on Excel using C#

First thing we need to take reference of below namespace:

using Excel = Microsoft.Office.Interop.Excel;

Classes used :
  • Excel.Application -Top level object in the Excel object model, used to specify application level properties and application level methods
  • Excel.Worbook - Represents a single workbook within the Excel application
  • Excel.Worksheet - A member of the Worksheets collection in the Workbook object 
Initializing the Class Variable:

MyApp = new Excel.Application();
MyApp.Visible = false;   // Run Excel in background.
MyBook = MyApp.Workbooks.Open(DB_PATH);
MySheet = (Excel.Worksheet)MyBook.Sheets[1];

// Explicit cast is not required here
lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;

MySheet .Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex


// Reading rows from used row.
 
 
//I presume you are actually looking for the last used row. In that case you need to write like this:

Range UsedRange = worksheet.UsedRange;
int lastUsedRow = UsedRange.Row + UsedRange.Rows.Count - 1;
 
  // Writing data into excel files.
        internal static void WriteToFile(Excel.Application myExcelApp,
  Excel.Workbook xlWorkBook,
  Excel.Worksheet xlWorkSheet,
  Dictionary<int, string> file1Diff,
  Dictionary<int, string> file2Diff)
        {
            //Difference between column/rows and cell
            int i= 2;  
            
            foreach (KeyValuePair<int, string> pair in file1Diff)
            {
                xlWorkSheet.UsedRange.Rows.Cells[i, 1] = pair.Key.ToString();
                xlWorkSheet.UsedRange.Rows.Cells[i, 2] = pair.Value.ToString();
                    i++;
            }
            i = 2;
            foreach (KeyValuePair<int, string> pair in file2Diff)
            {
                xlWorkSheet.UsedRange.Rows.Cells[i, 3] = pair.Key.ToString();
                xlWorkSheet.UsedRange.Rows.Cells[i, 4] = pair.Value.ToString();
                i++;
            }
            xlWorkBook.Save();
        }

 

Thursday, March 24, 2016

Automating Windows Open Dialog Box using C#

We can automate Dialog boxes using C# library without using AutoIT ,if we are using Selenium Web Driver.

Step 1: Take reference of below dll
1. UIAutomationClient
2. UIAutomationProviders
3. UIAutomationTypes

Step 2: Use UISpy tool to identify the object .

Step 3:  Code


using System;
using System.Threading;
using System.Windows.Automation;
using Microsoft.VisualStudio.TestTools.UnitTesting;

 public class WindowPopUpHandler
    {

        public void OpenDialog(string windowTitle, string dialogName, string filePath)
        {
            try
            {
                AutomationElement desktopRoot = AutomationElement.RootElement;
                if (dialogName == null) throw new ArgumentNullException("dialogName");
              
                 var app = desktopRoot.FindAll(TreeScope.Children,
                    new PropertyCondition(AutomationElement.NameProperty, windowTitle));
              
              if (app == null)
                    return;

                var openDialog= app[0].FindAll(TreeScope.Children,
                    new PropertyCondition(AutomationElement.NameProperty, dialogName));

                AutomationElementCollection childrenTemp =
                openDialog[0].FindAll       (TreeScope.Children,System.Windows.Automation.Condition.TrueCondition);          
              
              ValuePattern fileName = (ValuePattern)childrenTemp[2].GetCurrentPattern (ValuePattern.Pattern);

                fileName.SetValue(filePath);
                Thread.Sleep(4000);
               
               var Open = pdfWindow[0].FindFirst(TreeScope.Children,
               new PropertyCondition       (AutomationElement.NameProperty, "Open"));
             
                InvokePattern open = (InvokePattern)Open.GetCurrentPattern(InvokePattern.Pattern);
                open.Invoke();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
     }

Wednesday, March 2, 2016

Doing Unit Testing through Mocking

What is MOQ:

Moq is a third party library/framework that enables you to create the dummy class and its methods’ dummy implementation without actually creating a class with actual method implementation. Here you need to note that you need to provide the interface name for creating dummy class which will implement interface methods as dummy. This is very useful in the scenarios where you want to test the functionality of a class without implementing the other classes and their methods on which the test candidate class is dependent on.
 

How to install “Moq” in your test project ?

You can install “Moq’ in your test project using “NuGet Package Manager” UI or console. You can find “Manager NuGet Package” by right clicking on your project solution. When you click on it you will get a UI where you can search “Moq” online and install it to your test project. Now you are ready to go with using “Moq”.

How to use “Moq” in your project to test library classes?

Lets say that you have a class “DefaultMailer” which implements interface “IMailer” with method “SendMail”. SendMail needs an object, of type “IMailClient” as parameter, which will be used to actually send the mail.
Here, IMailer has only four properties, for simplicity, which are necessary to send mail.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YourNamespace.Utility.Interfaces
{
    public interface IMailer
    {
        string From { get; set; }
        string To { get; set; }
        string Subject { get; set; }
        string Body { get; set; }

        bool SendMail(IMailClient mailClient);
    }
}
IMailClient has only one methods which is used to send mail. It has only two properties i.e. Host and port. Here you can have many MailClients for supported mail servers like gmail, yahoo, hotmail etc.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YourNamespace.Utility.Interfaces
{
    public interface IMailClient
    {
        string Server { get; set; }
        string Port { get; set; }

        bool SendMail(string from, string to, string subject, string body);
    }
}
DefaultMailer implements IMailer interface.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YourNamespace.Utility.Interfaces;

namespace YourNamespace.Utility
{
    public class DefaultMailer : IMailer 
    {
        public string From { get; set; }
        public string To { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }

        public bool SendMail(IMailClient mailClient)
        {
            return mailClient.SendMail(this.From, this.To, this.Subject, this.Body);
        }
    }
}
Now we will see how to test if your DefaultMailer > SendMail method is working as expected. To do this, create a UnitTest project in your solution and install Moq using NuGet package manager. Create a UnitTest class as below.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using YourNamespace.Utility.Interfaces;
using YourNamespace.Utility;
using Moq;
using Moq.Matchers;

namespace YourNamespace.Utility.TestFixtures
{
    [TestClass]
    public class MailerTestFixtures
    {
        [TestMethod]
        public void SendMailTestFixture()
        {
            //Create a mock object of a MailClient class which implements IMailClient
            var mockMailClient = new Moq.Mock<IMailClient>();

            //Mock the properties of MailClient
            mockMailClient.SetupProperty(client => client.Server, "chat.mail.com").SetupProperty(client => client.Port, "1212");

            //Configure dummy method so that it return true when it gets any string as parameters to the method
            mockMailClient.Setup(client => client.SendMail(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())).Returns(true);

            IMailer mailer = new DefaultMailer() { From = "from@mail.com", To="to@mail.com", Subject="Using Moq", Body="Moq is awesome"};

            //Use the mock object of MailClient instead of actual object
            var result = mailer.SendMail(mockMailClient.Object);

            //Verify that it return true
            Assert.IsTrue(result);

            //Verify that the MailClient's SendMail methods gets called exactly once when string is passed as parameters
            mockMailClient.Verify(client => client.SendMail(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
        }
    }
}
Now I will explain the syntax of Moq I have used in the above test case. This is the most simple test case you can use. I have kept it simple here so that you can at least get started with its basics without worrying about the other complex syntax of Moq.

Creating the object of dummy class which implements an interface.

//Create a mock object of a MailClient class which implements IMailClient
var mockMailClient = new Moq.Mock<IMailClient>();
In this example, I have created dummy class which implements the interface IMailClient. The result would be a factory which will give me object of this dummy class by using its property Object.

Setup the properties of dummy class as per your need.

/Mock the properties of MailClient
mockMailClient.SetupProperty(client => client.Server, "chat.mail.com")
              .SetupProperty(client => client.Port, "1212");
You can set the default value for the properties of your dummy class objects using the “SetupProperty” provided by Moq.

Setup the methods of dummy class as per your need.

//Configure dummy method so that it return true when it gets any string as parameters to the method
mockMailClient.Setup(client => client.SendMail(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())).Returns(true);
Here we are setting up the SendMail method of your dummy class.  The meaning of the statements is that “When someone invokes the method “SendMail” of dummy class object with four parameters, which may be any string value, then return true. You can modify the statement to configure the cases where user passes null or empty or particular string.

Use the mock/dummy object to test your class “DefaultMailer”

//Use the mock object of MailClient instead of actual object
var result = mailer.SendMail(mockMailClient.Object);

//Verify that it return true
Assert.IsTrue(result);
Here we are using the object of mock/dummy class instead of actual IMailClient implementation. The reason behind this here is that we need to test our class “DefaultMailer” without depending on any other classes. We should assume here that other classes are working fine as we should have written separate test cases to test them.

Verify that the particular method of the interface was invoked

//Verify that the MailClient's SendMail methods gets called exactly once when string is passed as parameters
mockMailClient.Verify(client => client.SendMail(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
Here we verify that the method of the client was actually invoked by DefaultMailer to send mail. We also ensure that the method was invoked just once. In case, it was not invoked or invoked more than once then it will fail the test case.

The AAA Syntax (Arrange, Act, Assert) for writing Test

A very common approach to structuring your unit tests is using the AAA syntax. The AAA syntax is only a way of structuring your unit tests, and is supported by any framework.
The basic idea is that you create all the dependencies required by your method under test (Arrange), run your method under test (Act) and verify that the requirements of your test were met (Assert).

[Test]
public void Save_CustomerIsNotNull_GetsAddedToRepository()
{
    //Arrange
    Mock<IContainer> mockContainer = new Mock<IContainer>();
    Mock<ICustomerView> mockView = new Mock<ICustomerView>();

    CustomerViewModel viewModel = new CustomerViewModel(mockView.Object, mockContainer.Object);
    viewModel.CustomersRepository = new CustomersRepository();
    viewModel.Customer = new Mock<Customer>().Object;

    //Act
    viewModel.Save();

    //Assert
    Assert.IsTrue(viewModel.CustomersRepository.Count == 1);
}

 

Windows Dialog Box handling using .Net framework in Selenium

As we know that through selenium we can not automate Windows dialog boxes . There are different way to handle this.

1. Use AutoIT
2. Use System.Windows.Automation library

Will focus on second approach. To identify the control and dialog boxes id we can use UISpy tool.

Here by default , windows desktop is a root element and all the open application will be considered as child element.


// First method is for windows authentication .

public bool Authenticate(string windowTitle, string userName, string password)
        {
            string checkProperty = "AutomationId";
            string userNameId = "1003";
            string passwordId = "1005";
            string okButoonId = "1";
            try
            {
                AutomationElement desktopRoot = AutomationElement.RootElement;
                AutomationElement app = desktopRoot.FindFirst(TreeScope.Children,
                    new PropertyCondition(AutomationElement.NameProperty, windowTitle));
                if (app == null)
                    throw new AutomationException("Window '" + windowTitle + "' is not found.");

                this.WaitForCondition(app, checkProperty, userNameId, 5000);
                AutomationElement userNameTextBoxElement = GetRequiredElement(app, checkProperty, userNameId);
                var userNameTextBox = (ValuePattern)userNameTextBoxElement.GetCurrentPattern(ValuePattern.Pattern);
                userNameTextBox.SetValue(userName);

                AutomationElement passwordTextBoxElement = GetRequiredElement(app, checkProperty, passwordId);
                var passwordTextBox = (ValuePattern)passwordTextBoxElement.GetCurrentPattern(ValuePattern.Pattern);

                AutomationElement okButton = GetRequiredElement(app, checkProperty, okButoonId);
                var okButtonelement = (InvokePattern)okButton.GetCurrentPattern(InvokePattern.Pattern);
                okButtonelement.Invoke();

                return true;
            }
            catch (Exception e)
            {
                throw new AutomationException("Authenticate Method Failed due to exception '" + e.Message);
            }
        }

// Save Dialog box.


        public void SaveDialog(string windowTitle, string dialogName)
        {
            AutomationElement desktopRoot = AutomationElement.RootElement;
            if (dialogName == null) throw new ArgumentNullException("dialogName");

            var app = desktopRoot.FindAll(TreeScope.Children,
                new PropertyCondition(AutomationElement.NameProperty, windowTitle));
            if (app == null)
                return;
            var pdfWindow = app[0].FindAll(TreeScope.Children,
                new PropertyCondition(AutomationElement.NameProperty, dialogName));


            AutomationElementCollection childrenTemp = pdfWindow[0].FindAll(TreeScope.Children, System.Windows.Automation.Condition.TrueCondition);

            foreach (AutomationElement element in childrenTemp)
            {
                if (element.Current.Name.Equals("OK"))
                {
                    InvokePattern ok = (InvokePattern)element.GetCurrentPattern(InvokePattern.Pattern);
                    ok.Invoke();
                }
            }
        }

  private AutomationElement GetRequiredElement(AutomationElement parentElement, string criteria, string text)
        {
            foreach (AutomationElement element in parentElement.FindAll(TreeScope.Descendants, Condition.TrueCondition))
            {
                if (IsRequiredElement(element, criteria, text))
                    return element;
            }
            return null;

        }

        private Boolean IsRequiredElement(AutomationElement element, string criteria, string text)
        {
            //Check property exists and has value.
            if (!(element.Current.GetType().GetProperty(criteria) == null) && !(element.Current.GetType().GetProperty(criteria).GetValue(element.Current, null) == null))
            {
                //Check property is 'System.String' as it has a different logic to extract the value.
                if (element.Current.GetType().GetProperty(criteria).GetValue(element.Current, null).GetType().ToString().Equals("System.String")
                    || element.Current.GetType().GetProperty(criteria).GetValue(element.Current, null).GetType().ToString().Equals("System.Int32"))
                {
                    if (element.Current.GetType().GetProperty(criteria).GetValue(element.Current, null).ToString() == text)
                        return true;
                }
                else
                {
                    if ((((AutomationIdentifier)(element.Current.GetType().GetProperty(criteria).GetValue(element.Current, null))).ProgrammaticName) == text)
                        return true;
                }
            }
            return false;
        }

        private Boolean WaitForCondition(AutomationElement parentLocator, string criteria, string text, int timeout)
        {
            DateTime actualtimeouttime = DateTime.Now.AddMilliseconds(timeout);
            DateTime currTime = DateTime.Now;
            while (currTime < actualtimeouttime)
            {
                AutomationElement element = GetRequiredElement(parentLocator, criteria, text);
                if (element != null)
                {
                    return true;
                }
                Thread.Sleep(timeout / 100);
                currTime = DateTime.Now;
            }
            throw new AutomationException("Element with search criteria '" + criteria + "=" + text + "' was not found even after '" + timeout + "'");
        }