<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PHP vs .Net &#187; AJAX</title>
	<atom:link href="http://www.phpvs.net/category/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.phpvs.net</link>
	<description>ASP.Net and PHP go head to head</description>
	<lastBuildDate>Sat, 24 Dec 2011 18:20:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Manually validate an ASP.Net MVC form on the client side with MicrosoftMvcValidation.js and jQuery</title>
		<link>http://www.phpvs.net/2010/04/26/manually-validate-an-asp-net-mvc-form-on-the-client-side-with-microsoftmvcvalidation-js-and-jquery/</link>
		<comments>http://www.phpvs.net/2010/04/26/manually-validate-an-asp-net-mvc-form-on-the-client-side-with-microsoftmvcvalidation-js-and-jquery/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 06:16:51 +0000</pubDate>
		<dc:creator>morgan</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[ASP.Net MVC]]></category>
		<category><![CDATA[asp.net asp.net-mvc jquery validation]]></category>

		<guid isPermaLink="false">http://www.phpvs.net/?p=196</guid>
		<description><![CDATA[A recent problem cropped up in my Asp.Net MVC application. Its using the standard setup of DataAnnotations + MicrosoftMvcValidation.js + jQuery 1.4.2, and I needed to check the validation state of a form before performing some client-side actions. No problem, right? Obviously not. This second part of this post gets in depth as to what&#039;s [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-213" title="check-x" src="http://www.phpvs.net/wp-content/uploads/2010/04/check-x.png" alt="Validation" width="171" height="165" />A recent problem cropped up in my Asp.Net MVC application.  Its using the standard setup of DataAnnotations + MicrosoftMvcValidation.js + jQuery 1.4.2, and I needed to check the validation state of a form before performing some client-side actions. No problem, right?</p>
<p>Obviously not.</p>
<p>This second part of this post gets in depth as to what&#039;s going on with the MicrosoftMvcValidation script, but to save you some time, I&#039;ll post the solution first.</p>
<p><span style="text-decoration: underline;"><strong>To manually validate your form with MicrosoftMvcValidation.js:</strong></span></p>
<p><del datetime="2010-07-01T05:45:10+00:00">In MicrosoftMvcValidation.js, change line 20 from:</p>
<p style="padding-left: 30px;"><code> return Sys.Mvc._ValidationUtil.$0($2.validate('submit'));})); return $2;</code></p>
<p>to</p>
<p style="padding-left: 30px;"><code> return Sys.Mvc._ValidationUtil.$0($2.validate('submit'));})); <strong>$0.MvcValidationFormContext = $2;</strong> return $2;</code></p>
<p>Alternately, if you&#039;re using the debug version of the script, you can achieve the same effect by adding the following to line 196 (the end of the _parseJsonOptions function):</p>
<p style="padding-left: 30px;"><code>formElement.MvcValidationFormContext = formContext;</code></p>
<p></del></p>
<p><strong>UPDATE: </strong> As Morten Christiansen points out in the comments, there is a much cleaner way of accessing the FormContext object, without having to introduce a custom tracking property and modifying the script.  Instead of a custom property, we can just use<br />
<code>$('form')[0]['__MVC_FormValidation']</code>.  Thanks to Morten for pointing this out!</p>
<p>Now we can use the following jQuery/javascript code to manually validate our form:</p>
<pre>
var $form = ("#MyForm");                            // Select our form with jQuery
<del datetime="2010-07-01T05:45:10+00:00">var context = $form[0].MvcValidationFormContext;    // Access the new property we created</del>
var errors;
if ($form[0]['__MVC_FormValidation']) {
    errors = $form[0]['__MVC_FormValidation'].validate("submit");        // Validate the form
}
if (!$form[0]['__MVC_FormValidation'] || errors.length == 0) {
    // No errors, do your stuff
}
</pre>
<hr />
Now for the explanation.</p>
<p>I assumed (incorrectly) that there must be a client-side API to <code>MicrosoftMvcValidation.js</code>, the javascript responsible for dynamic client side form validation that ships with the ASP.Net MVC framework.  Unfortunately, in all my digging, I could not unearth one -- and it seems like a huge oversight.  The amount of effort to expose an <code>isValid</code> property or a <code>validate()</code> function on the client would be pretty minimal!</p>
<p>Why would you need to do this?  Doesn&#039;t the validation occur automatically?   Well, yes it does -- when you submit the form, or click around in it.  However, there are lots of cases where you might want to manually trigger the error messages or perform a client-side action based on whether or not the form is valid, without running the submit handler.   In my case, I wanted to make sure the form was valid <em>before </em>trying to submit it, as our ajax pipeline puts up the &#034;spinner&#034; graphic when a submit event is triggered, which meant it was flashing briefly and looked dumb.</p>
<p>The most common response I ran across when searching for how to manually validate was -- <a href="http://stackoverflow.com/questions/2060554/asp-net-mvc-check-form-input-is-valid-on-submit">give up and use the jQuery validate plugin</a>.  This would be my preferred solution to be honest, but I ran into at least two blockers with jQuery validate:</p>
<ol>
<li> it doesn&#039;t seem to work with modal dialogs generated from jQuery UI,</li>
<li> it doesn&#039;t seem to work with forms that are loaded into the document via an ajax call.</li>
</ol>
<p>So that was out.  Since I already had most of what I needed working with the Microsoft scripts, I went back to them and started exploring the code to see if I could discover any sort of public API.  This is what I came up with.</p>
<p>The key thing that I found was that <code>MicrosoftMvcValidation</code> creates a javascript object called a <code>FormContext</code>, which has a <code>validate(eventName)</code> method.  This <em>seemed </em>promising, so I tried following the code to see how I could get at this validate method. Well -- I couldn&#039;t.  Not without some modifications.  Here&#039;s how it works.</p>
<p>When you include <code>MicrosoftMvcValidation</code>, the main piece of script that executes is this:</p>
<pre>Sys.Mvc.FormContext._Application_Load = function Sys_Mvc_FormContext$_Application_Load() {
    var allFormOptions = window.mvcClientValidationMetadata;
    if (allFormOptions) {
        while (allFormOptions.length &gt; 0) {
            var thisFormOptions = allFormOptions.pop();
            Sys.Mvc.FormContext._parseJsonOptions(thisFormOptions);
        }
    }
}
</pre>
<p>Adding <code>&lt;% Html.EnableClientValidation(); %&gt;</code> to your views causes a bunch of JSON data to be output to the page, and appended to the <code>window.mvcClientValidationMetatdata</code> javascript object.  When the page is ready, the above function runs and calls <code>FormContext._parseJsonOptions()</code> on all the rules and data that were output to that object.</p>
<p><code>_parseJsonOptions </code>is what creates the <code>FormContext </code>object that we&#039;re interested in.  In fact, the return value of <code>_parseJsonOptions </code><em>is the FormContext</em>&#8230; but sadly, Application_Load ignores the return value, and it&#039;s just thrown to the bitbucket, never to be seen again (at least by us).</p>
<p>Judging from the underscores on the function names, it&#039;s pretty clear that these are meant to be internal operations, so we can (perhaps) excuse them for not storing and exposing the <code>FormContext </code>for us. From the framework&#039;s point of view, it doesn&#039;t need to be stored anywhere, because it still has it -- <code> _parseJsonOptions</code> internally adds new event handlers for the form, and these handler delegates close over the <code>FormContext </code>object.  The closures means that internally, the form handlers still have a saved reference to what they need, so the application load function doesn&#039;t need to do anything with the return value.  The <code>FormContext </code>never surfaces -- so if we want to validate the form ourselves, we need to <del datetime="2010-07-01T05:47:53+00:00">expose</del> dig for it.</p>
<p><del datetime="2010-07-01T05:47:53+00:00">All that my code at the top of the post is doing is modifying the <code>_parseJsonOptions</code> function (minified to be named <code>$12</code>), to start adding a new property to the form element in the DOM, which will store the created <code>FormContext</code> object. I named this property <code>MvcValidationFormContext</code>, but you could call it anything you&#039;d like.  You can subsequently access this new property to get the <code>FormContext </code>and call <code>validate("submit")</code> on it, which fires the validation as though we were trying to submit the form, and returns a collection of errors we can check.</del></p>
<p>As Morten pointed out, the reference is, of course, still there.  You can access the closed over FormContext by grabbing the DOM element and digging in it&#039;s properties array.  The updated code reflects this.</p>
<hr />I&#039;d love to see an upgrade to <code>MicrosoftMvcValidation.js</code> to include a client API in the future.  Even more, I&#039;d love to see <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery Validate</a> get some attention to fix the blockers that I ran into, so I can dump the MicrosoftAjax scripts out of my project altogether.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpvs.net/2010/04/26/manually-validate-an-asp-net-mvc-form-on-the-client-side-with-microsoftmvcvalidation-js-and-jquery/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>10 Tips for Building Selenium Integration Tests</title>
		<link>http://www.phpvs.net/2008/02/25/10-tips-for-building-selenium-integration-tests/</link>
		<comments>http://www.phpvs.net/2008/02/25/10-tips-for-building-selenium-integration-tests/#comments</comments>
		<pubDate>Mon, 25 Feb 2008 18:56:56 +0000</pubDate>
		<dc:creator>morgan</dc:creator>
				<category><![CDATA[Acceptance Testing]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Integration Testing]]></category>
		<category><![CDATA[Selenium]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://www.phpvs.net/2008/02/25/10-tips-for-building-selenium-integration-tests/</guid>
		<description><![CDATA[A list of ten tips, best practices and code snippets to make writing integration and acceptance tests with Selenium much easier, especially for AJAX applications.]]></description>
			<content:encoded><![CDATA[<p>I've been developing an API for our testers to use when writing GUI integration tests and acceptance tests for our main AJAXified web product.  Having chosen <a href="http://selenium-rc.openqa.org/">Selenium Remote Control </a>as our test engine, and writing many tests by hand and with the <a href="http://selenium-ide.openqa.org/">Selenium IDE Firefox Plugin</a>, I've delved deeply into Selenium this past several weeks.  (I've also managed to not only isolate it from our testers, but make our tests portable to any machine that you'd like to use, with no installs or executable paths, but I'll save that magic for another post <img src='http://www.phpvs.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> )</p>
<p>
So from the last few weeks, I thought I'd share some tips I've learned to make writing Selenium tests easier on yourself.
</p>
<ol>
<li> Make a GUI Component map</li>
<p>
              The first thing you should consider is mapping all your GUI elements to strongly typed objects, or at least a dictionary of named XPath strings.  It is much easier on everyone if they can read your code and see something like<br />
<code>Selenium.Click(UIElements["LoginButton"])</code><br />
rather then something like<br />
<code>Selenium.Click("//div[@id='LoginContainer']/table[1]/tbody[1]<br/>/tr[3]/td[2]/a[1]/img[1]")</code>
        </p>
<p>Hand in hand with this tip, I'll remind you to use Best Practices and get your developers to put in an ID for any web page element that will be interacted with <img src='http://www.phpvs.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />   Also, you can check out the <a href="http://wiki.openqa.org/display/SEL/GUI_Map">Selenium extension called GUI_Map</a> if you're looking to extend the Selenium core for your environment.</p>
<li> Fix the timer code!</li>
<p>
The code that the Selenium IDE generates for a timer loop is terrible! It loops from 0 to your timeout number, checking the condition and then sleeping for one second.  This assumes that the loop itself has a negligible execution time, which is untrue in many cases. I've run into situations where for whatever reason, the timer loop runs <strong>very </strong> slowly depending on the XPath you're checking against.  This means your 60 second timeout actually takes wayyyy longer, which is very annoying.  Use this code instead to more reliably measure elapsed time:
</p>
<div class="igBar"><span id="lcsharp-1"><a href="#" onclick="javascript:showPlainTxt('csharp-1'); return false;">&gt;&gt; show as plain text</a></span></div>
<div class="syntax_hilite"><span class="langName">C#:</span>
<div id="csharp-1">
<div>
<ol>
<li>
<div>DateTime start = DateTime.<span style="color: #0000FF;">Now</span>;</div>
</li>
<li>
<div>TimeSpan ts = DateTime.<span style="color: #0000FF;">Now</span>.<span style="color: #0000FF;">Subtract</span><span style="color: #000000;">&#40;</span>start<span style="color: #000000;">&#41;</span>;</div>
</li>
<li>
<div><span style="color: #FF0000;">bool</span> bFound = <span style="color: #0600FF;">false</span>;</div>
</li>
<li>
<div><span style="color: #0600FF;">do</span></div>
</li>
<li>
<div><span style="color: #000000;">&#123;</span></div>
</li>
<li>
<div>&nbsp; &nbsp; <span style="color: #0600FF;">try</span></div>
</li>
<li>
<div>&nbsp; &nbsp; <span style="color: #000000;">&#123;</span></div>
</li>
<li>
<div>&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_selenium.<span style="color: #0000FF;">IsElementPresent</span><span style="color: #000000;">&#40;</span>elementName<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span></div>
</li>
<li>
<div>&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000;">&#123;</span></div>
</li>
<li>
<div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bFound = <span style="color: #0600FF;">true</span>;</div>
</li>
<li>
<div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF;">break</span>;</div>
</li>
<li>
<div>&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000;">&#125;</span></div>
</li>
<li>
<div>&nbsp; &nbsp; <span style="color: #000000;">&#125;</span></div>
</li>
<li>
<div>&nbsp; &nbsp; <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception<span style="color: #000000;">&#41;</span></div>
</li>
<li>
<div>&nbsp; &nbsp; <span style="color: #000000;">&#123;</span> <span style="color: #000000;">&#125;</span></div>
</li>
<li>
<div>&nbsp; &nbsp; Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;color:#800000;">1000</span><span style="color: #000000;">&#41;</span>;</div>
</li>
<li>
<div>&nbsp; &nbsp; ts = DateTime.<span style="color: #0000FF;">Now</span>.<span style="color: #0000FF;">Subtract</span><span style="color: #000000;">&#40;</span>start<span style="color: #000000;">&#41;</span>;</div>
</li>
<li>
<div><span style="color: #000000;">&#125;</span></div>
</li>
<li>
<div><span style="color: #0600FF;">while</span> <span style="color: #000000;">&#40;</span>ts.<span style="color: #0000FF;">TotalMilliseconds</span> &lt;_waittime<span style="color: #000000;">&#41;</span> ;</div>
</li>
<li>
<div>&nbsp;</div>
</li>
<li>
<div><span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>!bFound<span style="color: #000000;">&#41;</span> Assert.<span style="color: #0000FF;">Fail</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">"timeout"</span><span style="color: #000000;">&#41;</span>; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<li>MouseDown() + MouseUp() is better than Click()</li>
<p>
I've found that in many situations a call to <code>Click()</code> won't work, even if the Selenium IDE generated the code.  This is especially true for block elements like table cells that you've styled to be clickable.  Just give up and use a call to <code>MouseDown("element")</code> followed by <code>MouseUp("element")</code>.  This works great in almost every situation.</p>
<li> Simulate Click-Drag with MouseDownAt + MouseUpAt</li>
<p>
I also searched long and hard for a Click-drag method for Selenium until realizing that this can also simply be done with <code>MouseDownAt("elementName", "x1,y1")</code> followed by a <code>MouseUpAt("elementName", "x2,y2")</code>.  Handy if you're testing on-screen drawing or selection tools using click-drags.</p>
<li>Use the Command Pattern</li>
<p>
One of the things the testers appreciate most is that my API handles all the overhead in their tests.  Typically you'll want to split your integration tests into multiple parts, so any given test run would be composed of several tests, each of which runs a sequence of selenium commands.  In order to reset our test environment for each test, I made heavy use of the Command pattern to implement file undo stacks, reversible web-steps, etc.  That way, testers can go deeply into a sequence of commands and simply call the reverse of each command in the stack to back them out to where they started from.  Very useful when testing anything that modifies configurations, test data, etc.</p>
<li>Modal Dialogs are a show-stopper</li>
<p>
There's no getting around this one.  Browser dialogs such as the file download dialog are not testable in Selenium.  There is work being done to allow this in the future, but currently you're out of luck.</p>
<li>Access Javascript Variables in your page with getCurrentWindow()</li>
<p>
If you're using <code>WaitForCondition()</code>, you can use the following snippet to access the DOM for the page that Selenium is running:<br />
<code>selenium.WaitForCondition(<br />"this.browserbot.getCurrentWindow().imgloaded == 1", "15000"<br/>);</code><br />
This is handy for executing existing javascript functions as well as checking variable values.
</p>
<li>Selenium IDE is not your friend: Re-use code to reduce fragility</li>
<p>
A fundamental drawback to using a GUI direct-testing tool is the reliance on locators for GUI elements.  If your locators change, your tests break, even though functionally the app might still be in perfect working order.  As well as using Best Practices to make your tests as robust as possible, you need to centralize your locators (see Tip #1) and build a library of utility functions to re-use.  Having 15 wait-for loops in a test or having the same navigation routines in multiple tests is hideous, not maintainable, and very fragile.
</p>
<li>Use <a href="https://addons.mozilla.org/en-US/firefox/addon/1843">Firebug </a>+ Selenium IDE for XPath finding</li>
<p>
While the Selenium IDE will choose the shortest XPath it can find when it generates your test code, often it isn't what you want.  If you don't want to edit the default behaviours of the IDE tool (which requires some javascript tinkering), I find it helpful to just use the <a href="https://addons.mozilla.org/en-US/firefox/addon/1843">Firebug extension for Firefox</a> and hit F12 to bring up Firebug when the Selenium IDE won't generate a good locator for you.  Use firebug to view the element and determine the XPath you need, replace it in the Selenium IDE, and continue along your merry way.</p>
<li> Use the following code to test for all finished callbacks</li>
<p>
             If you're making use of a framework that is using the <a href="http://msdn2.microsoft.com/en-us/library/ms178208.aspx">ASP.Net 2.0 Callback architecture</a>, this little snippet can save you a bundle.  The key to AJAX testing with Selenium is making use of the various WaitFor...() methods.  For a normal AJAX request, you would just do a regular <code>WaitForCondition </code>or <code>WaitForElementPresent </code>- so what's different about some callbacks?  If you have a Callback chain - i.e., one callback has a result that sets off another callback -<em> you can't use WaitFors to tell when they're done</em>.  A <code>WaitForElementPresent </code>on something that is changed later on in the callback chain will not work, since the element is present and sitting there while the first callbacks are executing.  A <code>WaitForCondition </code>might work, depending on the specific situation, but generally it's not easy to inject a semaphore around some callback object without making the test very fragile, and having to write code for multiple situations in your app.  And of course using <code>Thread.Sleep()</code> slows down your test unnecessarily and isn't reliable.  What we really need is a reliable generic method to check that all Callbacks are complete before we start Asserting that everything worked out.  So use this:</p>
<p>
<code>WaitForCondition("var finished = 1; for (var i = 0; i < selenium.browserbot.getCurrentWindow().__pendingCallbacks.length; i++) { if (selenium.browserbot.getCurrentWindow().__pendingCallbacks[i] != null){ finished = 0; } }; finished == 1", "15000");</code>
</p>
<p>
This is a semaphore around the ASP.Net <code>__pendingCallbacks </code>array that waits for everything to finish up and returns true when all callbacks are complete.  It times out in 15 seconds (you can change the 15000 parameter to any timeout length you'd like).
</p>
</ol>
<p>There it is - 10 tips for happier test writing.  Hope it helps some people out.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.phpvs.net%2f2008%2f02%2f25%2f10-tips-for-building-selenium-integration-tests%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.phpvs.net%2f2008%2f02%2f25%2f10-tips-for-building-selenium-integration-tests%2f&#038;bgcolor=FF9933&#038;cbgcolor=D4E1FD" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpvs.net/2008/02/25/10-tips-for-building-selenium-integration-tests/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>

