Sunday 7 June 2015

Upload a file using selenium web driver in c#

 Upload a file using selenium web driver in c#

        selenium can not identify the Input tag having attribute as file. Also selenium is not able to handle windows popup like Open File Dialog.
Ex: 
<input type="file" id="browse1" name="browse"> </file>
So To handle such kind of situation in selenium we have to use third party tools like Autoit, Point Position etc....

Prerequisite/Requirements:

  1. Visual Studio

  2. NUnit: Testing Framework.

  3. Autoit V3: To Handle Windows OpenfileDialog.

  4. Point Position software / Tool: to find the X and y coordinate of "Browse" Button.    

  1. procedure:

    1. Run visual Studio
    2. Select Test under project Template
    3. Select UnitTest  from right window
    4. Ex: select File->New->project->select Test -> under that select Unit Test Project.
    5. Give the project name as "UploadingFileOnNaukri"
    6. Under Solution / Project select References -> Right click it on it->add WebDriver.dll and webDriver.Support.dll
    7. Add another Reference to project "System.Windows.Forms"
    8. Add another Reference to project "System.Drawing"
     


Remove Namespace named "using Microsoft.VisualStudio.TestTools.UnitTesting"
Remove attribute "TestClass" and "TestMethod" from class and method.
Add Namespace Named as  using NUnit.Framework;
Add Namespace using OpenQA.Selenium.Firefox;
Add Namespace using OpenQA.Selenium.Support.UI;
Add Namespace using OpenQA.Selenium;
Add Namespace using System.Windows.Forms;
Add Namespace using System.Drawing;
Add Namespace using System.Threading;
Add Namespace using System.Diagnostics; 


Lets consider I want to upload a file which is present on D:\Avinash\Fileupload.txt.

Code :

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
using System.Threading;
using System.Diagnostics;

namespace UploadingFileOnNaukri
{
    [TestFixture]
    public class FileUpload
    {

        IWebDriver driver = null;
        IWebElement element = null;
        int xCoordinate = 0;
        int yCoordinate = 0;
   
        [SetUp]
        public void SetUp()
        {
           
ChromeOptions options = new ChromeOptions();
            options.AddArgument("start-maximized");
            driver = new ChromeDriver("G:\\Selenium_Csharp\\Jar\\chromedriver_win32", options);
        }

        [Test]
        public void TestFileUpload()
        {

            driver.Navigate().GoToUrl("http://my.naukri.com/manager/createacc2.php?othersrcp=11499&wExp=N");
            Thread.Sleep(300);
            ((IJavaScriptExecutor)driver).ExecuteScript("window.scrollTo(0,600);");
            Thread.Sleep(5000);
            xCoordinate = 537;
            yCoordinate = 331;      
            
            MouseEvents.LeftMouseClick(xCoordinate,yCoordinate);
            xCoordinate = 545;
            yCoordinate = 345;
            MouseEvents.LeftMouseClick(xCoordinate,yCoordinate);
            Thread.Sleep(6000);
            Process.Start("G:\\Autoit\\NaukriFileUpload.exe");
            Thread.Sleep(10000);


        }

        [TearDown]
        public void TearDown()
        {
            element = null;
            driver.Quit();
        }
    }
}



Note:
  1. Add another Class names as "MouseEvents.cs" in current project.
  2. It handles the mouse click event by using C# low level Handle.

Select project -> Right click -> Add new Class -> Give Name as "MouseEvents.cs"

code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;

namespace UploadingFileOnNaukri
{
    class MouseEvents
    {
       
private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;
        private const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;

        [System.Runtime.InteropServices.DllImport("user32.dll")]
       
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, uint dwExtraInf);

        public static void LeftMouseClick(int xpos, int ypos)
        {
           
int x = Convert.ToInt16(xpos);  //set x position
            int y = Convert.ToInt16(ypos);  //set y position
            Cursor.Position = new Point(x, y);
            mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);  //make left button down
            mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);  //make left button up

        }
    }
}


Note: 
Download the Autoit Testing tool i.e. autoitau3
Install it.
open  the SCiTE Script Editor.
open the Autoit V3 Window info 



SCite Script Editor: 

  •        It is used to write the script to handle windows open file dialog.
  •        It will select the file to be Uploaded from the given file path.
  •        it will upload the selected file by pressing "Open" button on fileDialog.

AutoIt V3 Window Info:

  •       It is used to Identify the parameter or information of text box and open button on Filedialog.
  •       It will gives the information of parameters like Title of FileDialog , class, Id of each control on a   OpenFileDialog.


Code in autoit:

  1. Open SCiTE Script Editor.
  2. Write below code:

ControlFocus("Open", "", "Edit1")
ControlSetText("Open", "", "Edit1", "D:\Avinash\FileUpload.txt")
ControlClick("Open", "", "Button1")


Save file as FileUpload.au3

Go to that file where above file is saved and right Click on it-> select Compile -> creates FileUpload.exe file.

Screen Shot to identify the above parameters like- "open"  , "Edit1"  , "Button1"  .





See Also Below Links:



















8 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Selenium Automation Blogs By Avinash Pande: Upload A File Using Selenium Web Driver In C >>>>> Download Now

      >>>>> Download Full

      Selenium Automation Blogs By Avinash Pande: Upload A File Using Selenium Web Driver In C >>>>> Download LINK

      >>>>> Download Now

      Selenium Automation Blogs By Avinash Pande: Upload A File Using Selenium Web Driver In C >>>>> Download Full

      >>>>> Download LINK Uh

      Delete
  2. I am facing an issue, I have the autoit script and I am executing it in my C# code.
    The thing is, when I execute the script when the 'File Upload' OS level dialog is open it successfully uploads the file. But when the same script is executed in the code, I can see the image path in the 'Edit1' field but then the dialog closes and file is not selected or uploaded.
    Can you help? I Have tried many other way like sending an enter key instead of click in the script it works running the script alone but not in the code.
    Thanks,
    Faris

    ReplyDelete
  3. You Just follow the steps which i have mentioned in above example. There are three statement from AutoIt scripts are very important. Set focus, set text/path and Click on ok button. It should work. Even I have checked on my machine it works fine. Please follow the above steps you will get what you want.

    Before you hit OK/open button make sure that, A file which you want to upload that should be present on the specified path (path which you have written/mentioned in Auto It scripts).

    ReplyDelete
    Replies
    1. Thank you for the reply. I followed the exact steps as you mentioned but its the same behavior. The file upload dialog box opens up the file path is displayed and then the dialog disappears and the rest of the code continues to execute.
      I have tried on both Firefox and Chrome browsers its the same behavior.
      The thing that I failed to understand is I already mentioned. When the script is executed outside the code like when the AutoIT script editor is open and by pressing F5 while the 'file upload' dialog is open it works perfectly and I can see the file uploaded too!!
      but the same script won't upload the file when ran through the rest of the code.

      Delete
  4. Selenium Automation Blogs By Avinash Pande: Upload A File Using Selenium Web Driver In C >>>>> Download Now

    >>>>> Download Full

    Selenium Automation Blogs By Avinash Pande: Upload A File Using Selenium Web Driver In C >>>>> Download LINK

    >>>>> Download Now

    Selenium Automation Blogs By Avinash Pande: Upload A File Using Selenium Web Driver In C >>>>> Download Full

    >>>>> Download LINK 0U

    ReplyDelete