Assert method in Webmethod asp.net - asp.net

I've a web method that has been called up using page methods. Assert function is not working in it although condition fails.
I want to test at what condition my code fails and debug it as in Assert menthod.
How should i debug that web menthod. Please suggest.
JavaScript Code
function sendingRqstForDealerCard(Argument) {
PageMethods.DealerTurn(OnSuccess);
function OnSuccess(response) {
Sys.Debug.assert(response!="", "respone is blanck in DealerTurn Function");
}
javascript assert is working but i have to check code in code behind.
Code Behind
[WebMethod]
public static string DealerTurn()
{
string previousRowHandTotal = BLHand.GetHandTotalField(hand, Convert.ToUInt16(dealerSpotID));
System.Diagnostics.Debug.Assert(previousRowHandTotal != string.Empty,"previousRowHandTotal is empty in dealerTurn function.");
}
Is there other way to debug WebMethod?

You will need to provide the code for a fuller answer, however keep in mind that if you are using Debug.Assert and not running in Debug mode, then the Assert is not even compiled into the code. That could be the reason your assert is not triggering.
Here is a MSDN article on how to run in debug mode. Typically, if you are running from visual studio, then this should prompt you to change the settings, though

Related

Blazor Web code after await doesn't execute until the second time

In Blazor Web, I have a method called from a button that does an HttpClient call to an API and then populates a field (Result) on the form. When I call it the first time, nothing happens. When I call it the second time, the field gets populated. Chrome confirms that the API call is made successfully both times. It looks like the code after the await doesn't execute until the 2nd call. What am I doing wrong?
private async void DoAPICall()
{
VerificationReturnType ReturnData = await Http.GetFromJsonAsync<VerificationReturnType>(APIMethod);
Result = String.Format("TrustedCookie: {0}\r\nVerificationCookie: {1}\r\nError: {2}\r\n", ReturnData.TrustedCookie, ReturnData.VerificatonCookie, ReturnData.Error);
}
Fixed by changing the return type of the DoAPICall from void to Task. Even though the DoAPICall is functionally the event handler for the web form button onclick event and async event handlers usually have to have the void return type, in this (Blazor Web) context, the method must have the Task return type.
Also, (which was my first solution), don't try to call the GetFromJsonAsync method synchronously by appending .Result, like you might when writing a backend C# application. It will compile OK but blow up running in the browser.
Really hope this helps someone else with beginner mistakes - Blazor Web has such potential!

How to Debug Selenium WebDriver Actions?

I am using Selenium WebDriver and run into an issue.
In the UI, elements are seen by the WebDriver but couldn't perform any actions such as click, type, select etc. Elements are found by the selenium and returned as instance of webelement. I can get, getText(),isEnabled() etc, but wont perform any actions. There is no exceptions. It just hangs.
I don't understand this behavior. If it is seen by the WebDriver, it should click. I have tried using actions. That too shows the same behavior.
How to debug this issue? Any ideas?
Little reminder: WebDriver can find for elements on page which are "hidden" by CSS.
These items are found, but are not click-able (or any other action).
Try to call method isDisplayed();
Only way to debug the code is to write wrapper around WebDriverEventListener and listen to the logs. Other wise, it is not possible.
If you are using Nunit, and the C# client drivers, you can attach Visual Studio to your nunit-agent.exe process by going to Tools > Attach to Process > choose "nunit-agent.exe" > Attach.
You can do the same when using JUnit, and the Java client drivers, by attaching to the nunit-agent.exe process in Eclipse.
===========
To answer your other questions...
1.) You may need to turn native events on for your driver in order to see JavaScript events.
2.) I also found some software bugs with WebDriver for Getting/Setting values. Try these for grabbing the InnerHtml (aka getText) that you were explaining in your question. This is .NET 4.0 code.. so you may need to modify it appropriately. These are in my Element class, hence the prefix of "Element" on the nested element calls.
public static int GetInnerHtmlByXPathTypeInt(IWebDriver driver, string xpath)
{
return int.Parse(Element.GetInnerHtmlByXpath(driver, xpath));
}
public static double GetInnerHtmlWithoutDollarSignByXPath(IWebDriver driver, string xpath)
{
return double.Parse(Element.GetInnerHtmlByXpath(driver, xpath).Replace("$", string.Empty));
}
public static string GetValueByXPath(IWebDriver driver, string xpath)
{
return driver.FindElement(By.XPath(xpath)).GetAttribute("value");
}
public static string GetInnerHtmlByXpath(IWebDriver driver, string xpath)
{
return driver.FindElement(By.XPath(xpath)).Text;
}

Error during serialization or deserialization using the JSON JavaScriptSerializer

I use the Microsoft ASP.Net AJAX framework for an autocompletion thingy on a text field (AutoCompleteExtender).
I'm getting an error :
Error during serialization or deserialization using the JSON
JavaScriptSerializer. The length of the string exceeds the value set
on the maxJsonLength property.
Several weird things about this error :
the error is thrown even when every single webservice in my solution return nothing (I altered them to return empty arrays) ;
in the web.config, jsonSerialization maxJsonLength is set to the maximum value of 2147483644, and the webservices in this page are supposed to return a few results ;
it says the source of the error is in a javascript function, but the function is never run, so the webservice is never actually called :
when I delete every AutoCompleteExtender and every call to any webservice from the page, it starts to throw me errors on "end if" inside the aspx. When I remove every "If" in the aspx, it crashes without telling me why. Fun !
<script type="text/javascript">
var tbEntrIdFonctionItemSelected = function(sender, e) {
$get('<%=Me.FormViewContact.FindControl("hdn_AgenceIdFonctionSearch").ClientID%>').value = e.get_value(); // source of the error
}
</script>
What do you think could be the cause of the problem ?
Thanks
OK, so after a bit of tracking, I noticed that a Telerik Combobox was the source of the error. And apparently, it was retreiving (using JSON, hence the error) the very small amount of 140.000 items. No big deal, right ? Hum.

Unit Test & Log4net

I have unit test testing an action in my controller, the action writes to log4net.
When I run my action it works well - writes to log4net .
However , When I run the unit test - the action doesn't write to log4net but doesn't throw any exception.
Does anyone have a solution?
// ARRANGE
var memoryAppender = new MemoryAppender();
BasicConfigurator.Configure(memoryAppender);
// ACT
_sut.DoWhatever();
// ASSERT - using xunit - change the expression to fit your purposes
Assert.True(memoryAppender.GetEvents().Any(le => le.Level == Level.Warn), "Expected warning messages in the logs");
You don't need to add in another layer of indirection by using a logging interface (if you don't want to). I have used the abstracted way for years, but now am moving towards just using the MemoryAppender as it is testing what is actually happening. Just be sure to .Clear() the appender after each test.
Log4net does not throw exceptions: http://logging.apache.org/log4net/release/faq.html
Writing to an log on disk or in a database in a unit test is counterproductive; the whole point is automation. You shouldn't have to check the logs every time you run tests.
If you truly need to verify that a call was made to log something, you should mock the ILog interface and assert that the appropriate method was called.
If you are using a mocking framework, this is trivial. If you aren't, you can create a TestLogger class that implements or partially implements ILog and exposes extra properties that show how many times a given method was called. Your assertions will check that the methods were called as expected.
Here is an example of a class to be tested:
public class MyComponent
{
private readonly ILog _log;
public MyComponent(ILog log)
{
_log = log;
}
public string DoSomething(int arg)
{
_log.InfoFormat("Argument was [{0}]", arg);
return arg.ToString();
}
}
and the test (using Rhino.Mocks to mock the ILog):
[TestClass]
public class MyComponentTests
{
[TestMethod]
public void DoSomethingTest()
{
var logger = MockRepository.GenerateStub<ILog>();
var component = new MyComponent(logger);
var result = component.DoSomething(8);
Assert.AreEqual("8", result);
logger.AssertWasCalled(l => l.InfoFormat(Arg<string>.Is.Anything, Arg<int>.Is.Equal(8)));
}
}
Try adding:
[assembly: log4net.Config.XmlConfigurator()]
To the AssemblyInfo.cs (or init log4net any other way).
Or try using AssemblyInitialize as suggested in this answer.
It is your log4net configuration. Right now it might be in your web.config or log4net.config file in the web/bin. You have to place it in a common location and make it discoverable by both web app and test. Or you have to put it into your unittest.project=>app.config file. But if you have many test projects, it would be duplicated in number of places. So the ideal would be to put it in a common place.
Here's another possible solution if none of the other solutions work for you...
Try writing your log file to the root of the c drive. By default, I set log4net to write to the current directory which is always the directory the unit test is running from right?... wrong! I'm running windows 8 with vs 2012 using MS Unit Test, and it writes the file to a local temp directory which gets deleted after the unit test completes. In my setup it writes the file to here:
C:\Users\[myself]\AppData\Local\Temp\TestResults
Bottom line, any unit tests I write for now on, are going to use a full absolute log file path and not a relative one.

Ajax function throwing WebServiceFailedException

I am using same asp.net page to edit and add data, only with some fields disabled and enabled accordingly. Now when I call webmethod from the add page, it's working fine, but when I call it from edit page, it is not. Though I am using the same javascript function to call the server side method. Please see the code:
.aspx:
function KeyCheck()
{
var KeyID = event.keyCode;
if(KeyID==46)
{
PageMethods.Delete_files(CurrentObj.id);
}
Now when I try to call this same method through edit, its generating following error :
Microsoft JScript runtime error:
Sys.Net.WebServiceFailedException: The
server method 'Delete_files' failed
with the following error:
If you look here they discuss a similar problem. Although the last answer wasn't selected I would still recommend doing what he says. After your first parameter you can pass two function callbacks; one for a successful Ajax call and one for a failure.
Your function should look more like this:
var onDeleteSuccess = function(result) {
//Successfully deleted files, maybe display confirmation to user.
};
var OnDeleteError = function(result) {
//Deleting files unsuccessful, display error to user.
};
PageMethods.Delete_files(CurrentObj.id, onDeleteSuccess, OnDeleteError);
Try adding the "missing" (although they should be optional) parameters to your PageMethod call and see if that solves it.
Edit:
I found a closed bug at connect.microsoft.com about this problem. Have you tried using the page only in IE7? If so, test it in other browsers and see if it works. If it does your only option may be to upgrade IE7 to a newer version or re-open the issue.
Edit after comments:
Try placing this code before your PageMethods.Delete_files function call:
PageMethods.set_path("PageYouAreTransferringto.aspx");
I think the handler you're calling is confused about which server-side page method to call since it appears (to the browser and JavaScript) that you're on a different page.

Resources