Assert statement in Selenium using C# - c#

I am trying to make LoginFailTest, the idea is to give a successful result if the Login Fails and if it Logs in, it should give a Test Failed result.
The HTML code behind the page is:
<div id="waw1" class="grid" style="margin-top: 30px; padding-top: 20px;">
<div id="waw2" class="notice error">
<i class="icon-ok icon-large"/>
Please make sure the Organization ID, User ID, and Password you entered are correct.
<a href="#close" class="icon-remove"/>
</div>
The C# code is:
[TestClass]
public class LoginFailTest : ibankTest
{
[TestMethod]
public void User_Login_Fail()
{
Assert.IsTrue(LoginFail.Title, "Logged In");
}
}
My LoginFail class code is:
public class LoginFail
{
public static bool Title
{
get
{
var title = Driver.Instance.FindElements(By.XPath("//*[#id='waw2']"));
if (title != null)
return true;
return false;
}
}
The problem that I am facing is even if it Logs in, it is giving a successful test result, it should give me a Test Fails result here.
Can someone please help?
Thanks in advance

Actually you are handling the condition on the basis of element existence which is wrong because the element with the id always existing on the page, you need to check existence of text instead as below :
var title = Driver.Instance.FindElements(By.XPath("//*[contains(text(), 'Please make sure the Organization ID, User ID, and Password you entered are correct.')]"));
if (title.Count > 0)
return true;
return false;
Note : - FindElements always returns list of IWebElements if found otherwise returns empty list, It does not return null so you need to check its count to verify list is empty or not instead.

What actually happening here is you are using:-
Assert.IsTrue(LoginFail.Title, "Logged In")
and your LoginFail.Title is expecting a boolean value either true or false, but in this case whether there would be a successful or failure for login, it will always have a title for the page. So the value LoginFail.Title is always returning true.
What you can actually do is get the title and make an exact comparison with the title that you are expecting.
Hope it helps!

Related

Method is only returning null. Searchs class list if user input equals what the user has inputed return the input else return null isn't working

as said in the title I have a class list on everytime that the program lauches it reads a txt file and the info the txt file gets changed into objects of that class (this works without a issue), but when I want to verify that what a user has input is equaled to something in this class list it doesn't seem to return the proper value but instead only every returns null. I can't seem to figure out why, I suppose I could maybe change the class list to a string list and verify via that way but kinda seems not the proper thing to do. I will provide code below. Some ideas would be helpful!
clientaccount is meant to be the input,
clientaccounts is the class list. If it doesn't contain it return null.
public Client? GetAccountAccountsE(ClientEmail cliEmail)
{
foreach (Client clientaccount in clientaccounts)
{
if (clientaccount.Equals(cliEmail)) { return clientaccount; Console.WriteLine("returning account"); }
}
Console.WriteLine("nulling");
return null;
}
You are comparing Client to ClientEmail, which are, unless you override the Equals()-method, not equal.
If ClientEmail email is a property of Client, try:
if (clientaccount.email.Equals(cliEmail)) {
Console.WriteLine("returning account");
return clientaccount;
}

Two simultaneous AJAX requests to same action causing error

I have the following action:
public async Task<ActionResult> Cart(bool refresh = false, bool mobile = false)
{
var user = await Auth.GetUserAsync();
//rest of the code
}
Which is being called twice by 2 AJAX calls at the same time (one to render mobile partial, other normal page).
$(document).ready(function () {
$("basket").html('<i class="fa fa-spinner fa-spin"></i>');
$('basket').load(PartialURL + "/Cart");
$('MobileBasket').load(PartialURL + "/Cart?mobile=true");
});
The real problem occurs in Auth.GetUserAsync() function.
Code:
public static async Task<User> GetUserAsync()
{
if (HttpContext.Current == null || HttpContext.Current.Request == null
|| HttpContext.Current.User == null || HttpContext.Current.Request.IsAuthenticated == false)
return null;
//if session does not exist, but user is logged in, fill session information
if (HttpContext.Current.Session[sessionKey] == null && HttpContext.Current.Request.IsAuthenticated)
using (var dal = new DAL.DAL())
{
//load user from DB
var user = await dal.SingleOrDefaultAsync<User>(m => m.Email == HttpContext.Current.User.Identity.Name);
HttpContext.Current.Session[sessionKey] = user;
}
return HttpContext.Current.Session[sessionKey] as User;
}
In one of those calls, the function returns user normally, but the other call produces following error (screenshot from fiddler). Notice how the first call was successful.
Code for SingleOrDefaultAsync is following:
public Task<T> SingleOrDefaultAsync<T>(Expression<Func<T, bool>> predicate) where T : class
{
return _context.Set<T>().SingleOrDefaultAsync(predicate);
}
I have checked while debugging, and email is present in both of the requests, _context is not null, and the user with requested email exists, but one of those always returns an error. Error is returned randomly. Sometimes in first, sometimes in second AJAX call.
Can someone please tell me what is causing this error? Any help is greatly appreciated.
I would assume, because of the other checks you have in place, that HttpContext.Current.User.Identity.Name (or even HttpContext.Current.User.Identity) is null, and that that's what's causing the error.
This might be so if the first request has caused the authentication process to start, but that process is not yet complete - so that the null checks you have succeed, but the subsequent member access fails. In other words, you have a timing issue / race condition. That's just a guess, though.
Update: following my suggestion to store the name in a variable and use the variable in the lambda, everything worked. But why?
My theory is that the expression passed to your SingleOrDefaultAsync method included the expression HttpContext.User.Identity.Name, rather than the value of that expression.
This expression was then evaluated in your DAL, where HttpContext.Current was (presumably) null (assuming your DAL is not in your web project). QED?

Spam filtering: where do I start

I have created a new asp.net site (web forms, c#) and looking to make it secure against spam coming through textboxes and being added to the database. Does anyone have any good links on how to implement this?
Thanks
I use ReCaptcha for this.
You can download it from nuget or install with
Install-Package recaptcha
command through package management console
public class NoCache : ActionFilterAttribute
{
public class CaptchaValidatorAttribute : ActionFilterAttribute
{
private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";
private const string CAPTCHA_MODEL_KEY = "Captcha";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY];
var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY];
var captchaValidtor = new Recaptcha.RecaptchaValidator
{
PrivateKey = "key",
RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
Challenge = captchaChallengeValue,
Response = captchaResponseValue
};
var recaptchaResponse = captchaValidtor.Validate();
if (!recaptchaResponse.IsValid)
{
filterContext.Controller
.ViewData.ModelState
.AddModelError(
CAPTCHA_MODEL_KEY,
"Entered text is invalid");
}
base.OnActionExecuting(filterContext);
}
}
public static class CaptchaExtensions
{
public static string GenerateCaptcha(this HtmlHelper helper)
{
var captchaControl = new Recaptcha.RecaptchaControl
{
ID = "recaptcha",
Theme = "white",
PublicKey = "key",
PrivateKey = "key"
};
var htmlWriter = new HtmlTextWriter(new StringWriter());
captchaControl.RenderControl(htmlWriter);
return htmlWriter.InnerWriter.ToString();
}
}
Than you can use
#using (Html.BeginForm("activate_user", , FormMethod.Post))
{
#Html.HiddenFor(x => x.Email)
<div class="captcha">
#Html.Raw(#Html.GenerateCaptcha())
<div style="text-align:center; margin-left:-25px;">
#Html.ValidationMessage("Captcha")
</div>
</div>
<input type="submit" class="signUpButton active activation" value="Activate" />
}
And in controller:
[ActionName("activate_user")]
[CaptchaValidator]
[HttpPost]
public ActionResult ActivateUser(string email)
{
if (ModelState.IsValid && !string.IsNullOrEmpty(email))
{
FormsAuthentication.SetAuthCookie(email, false);
Repository.ActivateUser(email);
}
return View();
}
If you do not have spam, I wouldn't worry about it.
That being said, if you do have it, you want to know what kind of spam you are getting. Validating the input against the model should prevent most of it assuming you have restrictions on the valid input. If just about anything validates, or you have to accept everything for some reason, you can start with a honey pot, which is a simple, non intrusive method.
To implement a honey pot, you basically add a field, hide it with CSS and and validate that field is null on the server side. Most spam bots fill out all fields and this will identify when something automated has submitted the form.
If you find this ineffective in preventing all spam on your site, you need to see what kind of spam is getting through and find something that prevents that. As a last resort, you can move to intrusive actions such as recaptcha. The real issue with CAPTCHA's (as Eric Lippert's succinctly states it) is that they assume guilt, that the user is trying to do something bad, and that has a negative effect on your users.
I suggest that you take the Growmap Anti-Spam plugin for WordPress and convert its Javascript and PHP implementation to something you can use in your project. It's not as annoying as CAPTCHA to end users and it's been quite effective in stopping automated spam on my WordPress blogs. It shouldn't be a big deal to do the ASP.NET/C# conversion. I started on one but the project I was doing it for got canceled so I didn't complete it.
Of course, it won't help with manual spamming where somebody pays $5 for someone sitting in a third world Internet cafe to enter nonsense onto dozens of sites. This is also a problem for many other anti-spam systems, including CAPTCHA. This activity is primarily done to get links for SEO purposes so screening out links for moderation or preventing them from being entered can curtail this activity.

Rendering different HTML depending on value of variable

I wish to use C# and Razor syntax to check if a cookie has been set. If it has been set, I want to show
<h2> Cookie set </h2>.
If it hasn't, I want to display
<h2>Cookie not set</h2>
So, to review a few things, I have this setting the cookie :
//set cookie
HttpCookie cookie = Request.Cookies.Get("stackOverflowCookie");
if(cookie == null) {
cookie = new HttpCookie("stackOverflowCookie");
cookie.Value = "Hi guys!";
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Using Razor, what is the best way, syntactically, to render what I wish? Whatever I try results in compilation errors :
#{
if(Request.Cookies["stackOverflowCookie"] == null){
//some other logic is here in my actual code, so an inline statement is not sufficient
<h2> Cookie set </h2>
#}
#{ else {
<h2> Cookie not set </h2>
#}
Obviously this is horrible looking, and it doesn't work. It does show the functionality I would like those. How is the best way to achieve this functionality?
If your if statement logic is longer than a single-liner allows, you can just set a variable in a code block:
#{
var isCookieSet = Request.Cookies["stackOverflowCookie"] == null && otherConditions;
}
And then your razor code could just look like this:
#if (isCookieSet) {
<h2>Cookie set</h2>
} else {
<h2>Cookie not set</h2>
}
Just remember to be careful of putting logic in the user-interface (ie, the View).
You may wish to consider editing the View-Model to include a value of the cookie, and display the different UI depending on this variable using a simply IF statement:
#if(model.CookieProperty != null) {
<h2>Cookie is set</h2>
} else {
<h2>Cookie is not set</h2>
}
And then having the controller reading the cookie, and setting the View-Model property:
model.CookieProperty = Request.Cookies["cookieName"];
The advantages of this are:
The controller may need to "enable functionality" or perform other logic depending on this value
Testing: It's difficult to test UI elements. Easy to test a View-Model.
You could try something like
#if(Request.Cookies["stackOverflowCookie"] == null) {
<h2> Cookie set </h2>
} else {
<h2> Cookie not set </h2>
}

Message Box when item saved

Hi people I am new to this website was having trouble with my controller in C# MVC3 and when I gave up on looking for answers since i spent like 2 weeks on it I decided to join here.
The problem is I want a very simple confirmation message when I create a item in my application. I tried a If statement but I can't get the context correct. Can you kind people please help me thank you. My code:
//
// POST: /News/Create
[HttpPost]
public ActionResult Create(BooksItem booksitem)
{
try
{
using (var db = new BooksForever2())
{
db.NewsItems.Add(booksitem);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
The create works fine I can add books and it saves but I want when it saves a message appears so it shows the user its has been saved. I have tried: Viewbag.Message("Saved")
But this does not work. Any help will be truly appreciated
Thank You
Just add this in you controller
TempData["Message"] = "Saved";
then in your view:
#if(TempData["Message"] != null)
{
<p>#TempData["Message"].ToString()</b> #* or whatever element you need to show*#
}
at your view level you can do anything with the message (maybe flash it with jQuery):
jquery: Flash messages
UPDATE: I replaced ViewBag with TempData because I noticed you are doing a redirect, in which case the ViewBag won't persist but TemData would
Where do you want that confirmation message displayed? On the same edit form you are already on, or back on the index/list page?
Right now at the end of your method, you are redirecting to the Index action/page:
return RedirectToAction("Index");
The result of that is that the Index page will be loaded, and it will be completely unaware of where it came from other that something was saved.
Your two options, as I see it, are:
1) Stay on the current page, and display the message. You can add that message to the ViewBag like as has already been mentioned:
ViewBag.Message = "Saved"`
And then display it like this:
#if(ViewBag.Message != null)
{
<p>#ViewBag.Message</p>
}
and then make sure you remove the RedirectToAction and just return the default View, otherwise will still bounce you to the Index page.
2) Or, you can redirect the user back to the Index page, passing the message to be displayed, and then have the Index page look for that message. So when you call RedirectToAction, include a query string parameter:
ViewBag.Message
return RedirectToAction("Index", new { Message="Saved" });
Which will redirect you to ".../yourControllerName/Index?Message=Saved". Then you can add this to your Index action method:
if(!string.IsNullOrEmpty(QueryString["Message"]))
{
ViewBag.Message = QueryString["Message"];
}
And include that same view code in your index view:
#if(ViewBag.Message != null)
{
<p>#ViewBag.Message</p>
}

Categories