Monday 2 November 2015

Posting JavaScript objects with Ajax and ASP.NET MVC

As websites become more and more interactive the need frequently arises to send data back and forth between web clients and servers using Ajax. ASP.NET combined with jQuery makes this process simple to implement for web developers.
For this example, we’re going to POST the following JavaScript object to our server, and return a Boolean value indicating if the data was correctly received.
var tommy = {
    name: "Tommy",
    birthday: new Date(1921, 0, 1),
    hobbies: ["Pinball", "Holiday camp"]
};
The server side
The first thing we need to do on the server side is define a data structure corresponding to the JavaScript object we wish to send.
public class Person
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
    public string[] Hobbies { get; set; }
}
Notice how the casing of the variable names in the JavaScript and C# objects doesn’t have to match. We can declare our JavaScript object properties in camel case and our C# properties in Pascal case and the model binder will work just fine.
Now let’s write our method. All we need to do is create a standard ASP.NET MVC controller method which takes a single parameter of the Person type, like so.
public bool ProcessData(Person person)
{
    return person != null;
}
As mentioned, I’m returning a Boolean value indicating whether the person object was successfully received.
That’s all we need to do on the server side. Let’s writ the client-side code.
The client side
The first thing we’ll do is use jQuery to write the Ajax call.
$.ajax({
    url: "@Url.Action("ProcessData", "Home")",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({ person: tommy }),
    success: function(response) {
        response ? alert("It worked!") : alert("It didn't work.");
    }
});
Here we’re invoking the ubiquitous “ajax” method, passing it an object containing all the information it needs to get the job done in the form of field values. Let’s take a brief look at each one.
url
The url field contains the dynamically-calculated address of our target method.
type
The type field indicates the type of HTTP request we wish to send. In this case it is a POST request.
contentType
Here we are specifying that the data is of the JSON format. This is important as it provides the server with the knowledge it needs to be able to deserialise our data into a POCO object.
data
The data field contains the actual data that we want to send in the POST request. There are two things of note here. The first is that we have assigned our “tommy” object to a field named “person” in a new anonymous object. Why is this? Well, the JSON object that we send to the server needs to correspond to the signature of the method that will receive the request. As our method looks like this:
public bool ProcessData(Person person)
We need to send it an object that looks like this:
{ person: [our person object] }
The second thing to note is that we invoke the JSON.stringify method in order to serialise the whole thing into a JSON string. This JSON string is what the server will receive and attempt to deserialise when we make the Ajax call from a web browser. We need to do this because “person” is a complex object and not a primitive JavaScript value, such as a string. Were we to send an object to the server consisting entirely of primitive values, this stringify call would not be necessary.
success
This function executes if the request succeeds. While in this case I’ve used an anonymous function, I could also have externalised this method and set “success” to a function pointer instead.
This is all the server side code we need. Let’s fire up our website and run the code to see what happens.
Making the call
If we insert a breakpoint in our ProcessData method and execute our JavaScript, this the result we get in Visual Studio.
As you can see, the model binder has done a wonderful job. Not only has it instantiated our object and mapped the simple Name property, but it has also translated the JavaScript Date value into a valid C# DateTime object, and mapped out our string array perfectly. We can now go ahead and do what we like with the data.


Monday 16 June 2014

Sample Selenium Interview Question along with Answers


1) Which is the command used for displaying the values of a variable into the output console or log?
The command used for displaying the values of a variable into the output console or log–echo
If you want to display a constant string. The below mentioned command can be used
echo <constant string>
ex: echo “The sample message”
If you want to display the value of a variable it can be written like below
echo ${<variable name>>
ex: echo ${var1}
2) What are the capabilities of Selenium WebDriver or Google WebDriver or Selenium 2.0?
Capabilities of Selenium WebDriver or Google WebDriver or Selenium 2.0 are:
One should use WebDriver when requiring improved support for
1. Mult-browser testing including improved functionality for browsers not well-supported by Selenium-1.0.
2. Handling multiple frames, multiple browser windows, pop-ups, and alerts.
3. Page navigation.
4. Drag-and-drop.
5. AJAX-based UI elements.
3) Which are the browsers supported by Selenium RC?
Browsers supported by Selenium RC are:
1. *firefox
2. *mock
3. *firefoxproxy
4. *pifirefox
5. *chrome
6. *iexploreproxy
7. *iexplore
8. *firefox3
9. *safariproxy
10. *googlechrome
11. *konqueror
12. *firefox2
13. *safari
14. *piiexplore
15. *firefoxchrome
16. *opera
17. *iehta
18. *custom
4) What are the Operating Systems supported by Selenium?
Operating Systems supported by Selenium are:
Selenium IDE
Works in Firefox 2+ Start browser, run tests Run tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others whichever supports Firefox 2+
Selenium Remote Control
Used for starting browser and run tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
Selenium Core
Used for running tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
5) What is the difference between an assert and a verify with Selenium commands?
Assert: Will fail and abort the current test execution.
Verify: Will fail and continue to run the test execution.
6) If a Selenium function requires a script argument, what would that argument look like in general terms?
StoreEval(script, variable) and storeExpression(expression, variableName).
7) If a Selenium function requires a pattern argument, what five prefixes might that argument have?
Five prefixes that Selenium pattern argument are:
glob, regexp, exact, regexpi.
8) Why Selenium RC is used?
We use Selenium RC for:
Selenium-IDE does not directly support:
1. Condition statements.
2. Iteration.
3. Logging and reporting of test results.
4. Error handling, particularly unexpected errors.
5. Database testing.
6. Test case grouping.
7. Re-execution of failed tests.
8. Test case dependency.
9. Capture screen shots on test failures.
The reason behind why Selenium-IDE does not support the above mentioned requirements is IDE supports only HTML language. Using HTML language we cannot achieve the above mentioned requirements. Because HTML does not support conditional, looping and external source connectives.
To overcome the above mentioned problems Selenium RC is used.
9) How many testing frameworks can QA Tester use in Selenium RC?
Testing frameworks aren’t required, but they can be helpful if QA Tester wants to automate test cases. Selenium RC supports Bromine, JUnit, NUnit, RSpec (Ruby), Test::Unit (Ruby), TestNG (Java), unittest (Python).
10) What is the architecture of Selenium RC?
The Selenium Server launches and kills browsers and acts as an HTTP proxy for browser requests.
Client libraries for various programming languages, each of which instructs the Selenium Server in how to test the AUT by passing it your test script’s Selenium commands.
The client libraries communicate with the Server passing each Selenium command for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands. The browser, using its JavaScript interpreter, executes the Selenium command, which effectively, runs the check you specified in your Selenese test script.
11) Does Selenium support mobile internet testing?
Selenium supports Opera and opera is used in most of the Smart phones. So whichever Smart phone supports opera, selenium can be used to test. So, one can use Selenium RC to run the tests on mobiles.
12) What are the basic annotations used to run TestNG tests in Selenium?
The basic annotations used to run TestNG tests in Selenium RC:
1. @BeforeClass: The annotated method with @BeforeClass will be run before the first test method in the current class is invoked.
2. @AfterClass: The annotated method with @AfterClass will be run after all the test methods in the current class have been run.
3. @BeforeMethod: The annotated method with @BeforeMethod will be run before each test method.
4. @AfterMethod: The annotated method with @AfterMethod will be run after each test method.
5. @Test: Marks a class or a method @Test with as part of the test.
13) What is the difference between Thread.Sleep() and Selenium.setSpeed()?
Selenium.setSpeed:
1. takes a single argument in string format
ex: selenium.setSpeed(“2000″) – will wait for 2 seconds
2. Runs each command in after setSpeed delay by the number of milliseconds mentioned in setSpeed.
Thread.sleep:
1. takes a single argument in integer format
ex: thread.sleep(2000) – will wait for 2 seconds
2. Waits for only once at the command given at sleep.
14)  How to configure Selenium RC with eclipse to run Junit Tests?
1) Download eclipse. click here to download the software
2) Open eclipse -> Workspace Launcher window will open
3) Create a workspace by giving meaningful name
3) Click on Workbench
4) Create a project of type java
5) Create a package under src folder of the package
6) Add Junit to the build path
7) Add selenium rc java client driver to the build path
8) Now drag and drop your test script (.which is exported from Selenium IDE) to the package created.
15) Actual end user simulation, Is the test conducted using this tool equivalent to an end user action?
Selenium performs actions in the background on the browser. It modifies the DOM structure of the HTML page in order to perform actions on the page. To be more precise it executes JavaScript on UI objects within the webpage to perform actions like click, type, select etc. This is the reason why you can execute tests with the browser minimized.
QTP claims to perform end user simulation, in other words executing QTP scripts are equivalent to a person performing those steps manually on the application.
16) Is it possible to use Selenium for multi-user Load Testing?
Yes, but it requires a LOT of hardware. We recommend you check out BrowserMob, which does load testing with real browsers and is powered by Selenium.


Wednesday 22 January 2014

Copying the One Excel sheet to another excel sheet and Update test cases staus using Java and JXL

import java.io.File;

import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class SampleExcelStatus
{
      @BeforeTest
      public void setup() throws Exception
     
      {
           
      }

      @Test
      public static  void SecondExcelFile() throws Exception
      {   
        Workbook workbook = Workbook.getWorkbook(new File("E:/6409_TestCases_Checkout.xls"));
        WritableWorkbook copywb = Workbook.createWorkbook(new File("E:/6409_TestCases_CheckoutResultsSatya.xls"), workbook);
        WritableSheet sheet1=copywb.getSheet(0);
       
        for(int URowcount=12; URowcount<sheet1.getRows();URowcount++)
            {
                   Label label = new Label(10,URowcount-1,"Pass");
                   WritableCellFormat cfobj=new WritableCellFormat();
                    /*cfobj.setBackground(Colour.GREY_25_PERCENT);
                    cfobj.setAlignment(Alignment.LEFT);
                    cfobj.setOrientation(Orientation.HORIZONTAL);*/
                    cfobj.setBorder(Border.ALL, BorderLineStyle.THIN,Colour.BLACK);
                    label.setCellFormat(cfobj);
                   
                    sheet1.addCell(label);
            }
       
        copywb.write();
        copywb.close();
        workbook.close();
       
      }
     
            @AfterClass
            public void tearDown()
            {
            //    driver.close();
            }  
}

Monday 7 October 2013

Maveen Central Repository & Download from Reposotoriy

When you build a Maven’s project, Maven will check your pom.xml file, to identify which dependency to download. First, Maven will get the dependency from your local repository Maven local repository, if not found, then get it from the default Maven central repositoryhttp://repo1.maven.org/maven2/
This is how the Maven central repository website looks like


According to Apache Maven :
Downloading in Maven is triggered by a project declaring a dependency that is not present in the local repository (or for a SNAPSHOT, when the remote repository contains one that is newer). By default, Maven will download from the central repository.
In Maven, when you’re declared library does not exist either inlocal repository nor Maven center repository, the process will stop and output error messages to your Maven console.

1. Example

The org.jvnet.localizer is only available at Java.net repository.
pom.xml
    <dependency>
        <groupId>org.jvnet.localizer</groupId>
        <artifactId>localizer</artifactId>
        <version>1.8</version>
    </dependency>
When you build this Maven project, it will fail and output dependency not found error message.
Updated 12/12/2012
The
org.jvnet.localizer is now available in Maven center repository.

2. Declare Java.net repository

To tell Maven to get the dependency from Java.net, you need to declared a remote repository in your pom.xml file like this :
pom.xml
    <repositories>
        <repository>
            <id>java.net</id>
            <url>https://maven.java.net/content/repositories/public/</url>
        </repository>
    </repositories>
Now, Maven’s dependency library look-up sequences is changed to :
  1. Search in Maven local repository, if not found, go step 2, else exit.
  2. Search in Maven central repository, if not found, go step 3, else exit.
  3. Search in java.net Maven remote repository, if not found, prompt error message, else exit.
Maven’s dependency mechanism help to download all the necessary dependency libraries automatically, and maintain the version upgrade as well.



Changing the Maven Local Repository




The maven local repository is a local folder that is used to store all your project’s dependencies (plugin jars and other files which are downloaded by Maven). In simple, when you build a Maven project, all dependency files will be stored in your Maven local repository.
By default, Maven local repository is default to .m2 folder :
  1. Unix/Mac OS X – ~/.m2
  2. Windows – C:\Documents and Settings\{your-username}\.m2

1. Update Maven Local Repository

Normally, I will change the default local repository folder from default .m2 to another more meaningful name, for example, maven-repo.
Find {M2_HOME}\conf\setting.xml, update localRepository to something else.
{M2_HOME}\conf\setting.xml

<settings>
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
 
<localRepository>D:/maven_repo</localRepository>

2. Saved it

Done, your new Maven local repository is now changed to D:/maven_repo.

2. Saved it

Done, your new Maven local repository is now changed to D:/maven_repo.