Friday, July 22, 2016

What is Desired Capabilities in Selenium ?

We uses Desired Capabilities to configure Web Driver browser instance before running the test cases.

We generally use desired capabilities to set profile data, handling browser cookies , SSL security popup file upload/save ,setting your IE protected mode settings to be the same for all zones , SSl certificates.....

//IE Code

DesiredCapabilities cap = new DesiredCapabilities();
 cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
cap.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, https://testvmm6.partnersonline.com/vmm);
cap.internetExplorer().setCapability("ignoreProtectedModeSettings", true);

System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"//exe//IEDriverServer1.exe");
cap.setCapability("IE.binary", "C:/Program Files (x86)/Internet Explorer/iexplore.exe"); cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

cap.setJavascriptEnabled(true); cap.setCapability("requireWindowFocus", true);

cap.setCapability("enablePersistentHover", false);

// For Firefox Browser
Generally we create profile and capabilities both. In one scenarios we had set up Jenkins CI server. After triggering the build from Server machine ,  web browser was not being launched on node machine. So we have create profile and setup with Firefox browser.

1. Create a profile using below steps:

 Open window in run mode window+R then type "firefox -p -no-remote"
 -no-remote
 
2.  ProfilesIni allProfiles = new ProfilesIni();

     FirefoxProfile profile=allProfiles.getProfile("ExTest"); 

     WebDriver driver = new FirefoxDriver(profile);

 

Saturday, April 9, 2016

Learn How to manage people and be a better Leader

Below are the following characteristics for the Good Leader.
1. Professional Expertise
2. Experience
3. Character Traits
4. Interpersonal Skills
5. Communication

If we build positive relationship with Customers they will keep coming back.

How to maintain good relationship with unhappy customers:

 In case, we have committed "A" to deliver our customer but any reason we couldn't. now how to deal with customers ...

   - Yes last we were failed to deliver few things 
   - Meet with Customer , accept and communicate with him that you can deliver it.
   - Make him feel better that you can do that.

1. Reiterate Customers views: 
   - Say You understand your view(Customer view) and we did not deliver this sample last week. I will make them call to deliver today.

2. Customers Need First:
     Customer is saying , i need sample and you can say i have another idea and you present our new idea and get time to deliver it.

3. Pros and Cons: Convince you customer that if he need sample  in 1 day we can deliver it but quality will be compromised if he is ready to give one more day will deliver with quality and it wont effect much the timeline.

WITH SUBORDINATES 

Don't disregard the people feelings. Be Assertive , Honest and Respectful.

1. Explain The Reason
     Why?
2.  Be Open To Suggestions
3. Accept Responsibility
     Yes its my decision/ or I will take this difficult work.

WITH SUPERVISORS

Know How he prefers to process information
  - Through Visual Graph/Video
 -  Hear- Face to Face / Meetings/ Phone Call
- If He is Experience person then he would like to visit site visits or Product Testing.

CO-WORKERS

If you able to influence co workers to achieve the goals use below approach:

 Push and pull and influencing styles.

PUSH
   - One Push styles is use logic . Points out the loopholes and argument and offer account and proposal.
 - Another Push style is stick and carrot:  Show your co-workers if they will work they will get highlight and prize and if they don't they will get threat.

PULL STYLE
If your team members have ideas and willing to share and they are capable.

 - Be Consultative and ask what do you think ?
  - May be your Co-Workers have some idea and they will share.
  - Every one have some unique skill identify and ask those expertise.

SELF

- Great Responsibilities and Challenges
- Write Down your career goals
- Training- Gives you strength and minimize your weakness.


Help Link: https://www.youtube.com/watch?v=PWmhl6rzVpM

Mobility Testing Overview

This post have some basic testing overview about how to perform mobility testing .

Extension of different OS files.

 1. Android  - .apk (app kit package)
 2. IOS - .ipa (IPhone application)
 3. Windows - .xap (Experience the application)
 4. BlackBerry - .cod

Development Languages for App for Each OS:


Android: Java

IOS: Objective C
Windows: C#

Different Version of Android:


- Gingerbread - 2.3

-Ice Cream Sandwich - 4.0 
- Jelly Bean - 4.1
- Kit Kat - 4.4
- Lolly pop - 5.0
- Marshmallow - 6.0

Mobile Application Testing

- Find testing should be done on what type of device.
>5 - Smart Phone
>5-7  - Phablet - Mini Tablet
>7 - Tablet

Mobile App Architecture/Type

- Native App   - Which is developed in native language (objective c, java ..)
- Web App  (Access through wen url in Mobile)
-Hybrid App (Combination of native language and html)

Mobile Application Testing & Challenges

- IOS  - IPhone  ,4s,5s ,6s, IPad
-Android - Device maker (LG ,samsung.)  , different version
- Native App
-Phone 
- Tablet
- Network Connections (Cellur ,3G,4G,WiFI)
- Device Diversity - 4s,5s 
-Network Connectivity - in Different countries
-Hardware Configuration
- Orientation Challenges


Remote Device Services: There are so many vendors in the market who provides remote access to different type of device for testing purpose:
- Perfecto Mobile
-Smart Bear
-Mobile Lab

Note: There will be performance hit using this virtual labs. If budget constraint have, then go for Simulator/Emulator.


Mobile App Testing Techniques

1. Installation Techniques
2. Un-Installation Techniques
3. Splash Screen Testing
4. Device Orientation Testing
5. UI/UX Testing
6. Crash Discovery Testing
7. Device Resolution/Density Testing
8. Network Connectivity Testing
9. Device Interruption Testing
10. Functional Testing
     10.1  Notification Testing
      10.2 Data Input Testing

Mobile App Logs
- Console Logs : Record all actions. Does not capture crash.
- Crash Log : Contain info what action was doing before crash.

There are two main reason for app crash:
1. Violation of OS policies
2. Code in App

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 + "'");
        }

Thursday, February 18, 2016

Frequently use Git command to maintain the code

1. How to initialize and clone the repository
2. How to know the status

     $Git status

3. Adding , Committing and check in the files into Git repository.
  •    $Git Add LearningGit/
  •    $Git Commit -m "Added Learning Git file"
  •    $Git push origin <remote branch name>
4. Creating , merging , deleting and switching to new branch.
  •  $Git branch <new branch name>
  •  //Switch to new branch
          $Git checkout <branch name>
  •     Short cut to create new branch and checkout
           $Git checkout - v <new branch>
  • //Switch back to master
         $Git checkout master
        
         //Merge into master
        $Git merge <new branch>
 
         //Delete local branch
         $Git branch -D <new branch>

        // Check in of deleted branch into remote repository.
        $Git push  origin <new branch>
        or $Git push --set-upstream origin master


Working on VI Editor.

1. Press i to start entering the text.
2. For save,press esc and :wq  and enter. This will commit with message you typed.
3. For Exit,:q   or :cq   or cquit