Winappdriver unit test c# automation getting an "Object reference not set to an instance of an object" error in Test2Password method with "possession" - winappdriver

Here when I try to run these unit tests
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Windows;
using System;
using System.Diagnostics;
namespace test
{
[TestClass]
public class AutomationTest
{
public static WindowsDriver<WindowsElement> possession;
[TestMethod]
public void Test1Login()
{
AppiumOptions ao = new AppiumOptions();
ao.AddAdditionalCapability("app", "Root");
WindowsDriver<WindowsElement> windowssession =
new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), ao);
AppiumOptions windowOptions = null;
var listOfAllWindows =
windowssession.FindElementsByXPath(#"//Window");
Debug.WriteLine($"Elements found: {listOfAllWindows.Count}");
foreach (var window in listOfAllWindows)
{
if (window.Displayed && window.Text.Contains("Aronium - POS"))
{
var windowHandle = window.GetAttribute("NativeWindowHandle");
Console.WriteLine($"Window Handle: {windowHandle}");
var handleInt = (int.Parse(windowHandle)).ToString("x");
windowOptions = new AppiumOptions();
windowOptions.AddAdditionalCapability("appTopLevelWindow", handleInt);
break;
}
}
WindowsDriver<WindowsElement> possession = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"),
windowOptions);
possession.FindElementByAccessibilityId("passwordBox").SendKeys("Future#123");
}
[TestMethod]
public void Test2Password()
{
possession.FindElementByClassName("Button").Click();
}
[ClassCleanup]
public static void Test5Cleanup()
{
if (possession != null)
{
possession.Quit();
}
}
}
}
I am getting an error "Object reference not set to an instance of an object" with the 2nd method (Test2Password)
Is there a way for me to declare the possession globally
Or can I declare the possession as a variable
I am new to C# and Winappdriver

Related

ShouldDelayBannerRenderingListenerImplementor Error after Xamarin AdMob SDK 118.1.1 update

After a long wait for Admob SDK Update on Xamarin to implement Adaptive Banners and new Native Ads ,after upgrade to new Nuget package Sdk 118.1.1preview ,Visual Studio open a .Java File and mention the following error :
error: ShouldDelayBannerRenderingListenerImplementor is not abstract and does not override abstract method zzb(Runnable) in ShouldDelayBannerRenderingListener.
To take advantage of the new xamarin admob sdk (118.1.1 preview) , and overcome the JAVA error :
error: ShouldDelayBannerRenderingListenerImplementor is not abstract and does not override abstract method zzb(Runnable) in ShouldDelayBannerRenderingListener.
just put the following code on the java file poped-up and build solution :
#Override
public boolean zzb(Runnable runnable) {
return false;
}
or let this c# code (FileWatcher)keep running :
static void Main(string[] args)
{
var Javacode = File.ReadAllText(#"MyJavaFile.java");
while (true)
{
try
{
var JavaFilePah = #"C:\Project\Android\apps\AppName\obj\Debug\100\android\src\mono\com\google\android\gms\ads\formats\ShouldDelayBannerRenderingListenerImplementor.java";
DateTime LastFileChang = File.GetLastWriteTime(JavaFilePah);
if (LastFileChang != LastFileChangesave)
{
if (File.Exists(JavaFilePah) && File.ReadAllText(JavaFilePah).Contains("zzb") == false)
{
File.WriteAllText(JavaFilePah, Javacode);
Console.WriteLine("ok");
}
LastFileChangesave = LastFileChang;
}
Thread.Sleep(10);
}
catch (Exception e)
{
}
}
}
change JavaFilePah with path of ur android app.
MyJavaFile content is :
package mono.com.google.android.gms.ads.formats;
public class ShouldDelayBannerRenderingListenerImplementor
extends java.lang.Object
implements
mono.android.IGCUserPeer,
com.google.android.gms.ads.formats.ShouldDelayBannerRenderingListener
{
/** #hide */
public static final String __md_methods;
static {
__md_methods =
"";
mono.android.Runtime.register ("Android.Gms.Ads.Formats.IShouldDelayBannerRenderingListenerImplementor, Xamarin.GooglePlayServices.Ads.Lite", ShouldDelayBannerRenderingListenerImplementor.class, __md_methods);
}
public ShouldDelayBannerRenderingListenerImplementor ()
{
super ();
if (getClass () == ShouldDelayBannerRenderingListenerImplementor.class)
mono.android.TypeManager.Activate ("Android.Gms.Ads.Formats.IShouldDelayBannerRenderingListenerImplementor, Xamarin.GooglePlayServices.Ads.Lite", "", this, new java.lang.Object[] { });
}
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
#Override
public boolean zzb(Runnable runnable) {
return false;
}
}

Windows universal app isolated storage - How to save and retrieve data?

I have this isolated storage helper and I need to use it to save and retrieve data from my universal app.
I don't know where to begin from. Should I maybe make an app and incorporate the helper class into it?
Here is my class:
using System.IO;
//using System.IO.IsolatedStorage;
using System.Runtime.Serialization.Json;
using System.Text;
public static class IsolatedStorageHelper
{
public static T GetObject<T>(string key)
{
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
if (localSettings.Values.ContainsKey(key))
{
string serializedObject = localSettings.Values[key].ToString();
return Deserialize<T>(serializedObject);
}
return default(T);
}
public static void SaveObject<T>(string key, T objectToSave)
{
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
string serializedObject = Serialize(objectToSave);
localSettings.Values[key] = serializedObject;
}
public static void DeleteObject(string key)
{
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values.Remove(key);
}
private static string Serialize(object objectToSerialize)
{
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
serializer.WriteObject(ms, objectToSerialize);
ms.Position = 0;
using (StreamReader reader = new StreamReader(ms))
{
return reader.ReadToEnd();
}
}
}
private static T Deserialize<T>(string jsonString)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
use static SaveObject method and supply the 'person' entity and a key. Retrieve it later using GetObject.
But I think in this scenario you should use database sqlite and sqlite net package to save the entity.

how to send the data every 5 minutes in WebAPI

I have a project WebAPI, I want to provide data every 5 minutes or so to the client:
using System;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace MyWebApi.Controllers
{
public class EventController : ApiController
{
public string Get()
{
var id = Guid.NewGuid();
string result = JsonConvert.SerializeObject(id, new IsoDateTimeConverter());
return result;
}
}
}
Why don't you use C# timer. You can create a static object and set time interval is 5 mins.
Here is an example I got from http://www.dotnetperls.com/timer
public static class TimerExample
{
static Timer _timer;
static List<DateTime> _l;
public static List<DateTime> DateList
{
get
{
if (_l == null)
{
Start(); // Start the timer
}
return _l;
}
}
static void Start()
{
_l = new List<DateTime>();
_timer = new Timer(300000); // Set up the timer for 5 mins
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
}
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
// Add event here
}
}

c# - selenium Nunit testing - how to do validation check for signup form

Hi I am trying to test this online signup form. I have created a test but I would like to do a validation check on each field,
e.g.
For Name field
driver.FindElement(By.Id("Name")).SendKeys("Clayton")
I would like to try different text/number/characters and see what goes through and what fails.
Is there any way i could do this?
please see the codes.
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTests
{
[TestFixture]
public class loop
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
private bool acceptNextAlert = true;
[SetUp]
public void SetupTest()
{
driver = new FirefoxDriver();
baseURL = "http://something.com/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
driver.Quit();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void TheSignupTest()
{
driver.Navigate().GoToUrl(baseURL + "/Account/Login?ReturnUrl=%2f");
driver.FindElement(By.Id("UserName")).Clear();
driver.FindElement(By.Id("UserName")).SendKeys("something");
driver.FindElement(By.Id("Password")).Clear();
driver.FindElement(By.Id("Password")).SendKeys("something");
driver.FindElement(By.CssSelector("input.btn.small")).Click();
driver.FindElement(By.Id("nav2")).Click();
driver.FindElement(By.Id("upload-file")).Click();
driver.FindElement(By.Id("Name")).Clear();
driver.FindElement(By.Id("Name")).SendKeys("00");
driver.FindElement(By.Id("ReferenceNumberPrefix")).Clear();
driver.FindElement(By.Id("ReferenceNumberPrefix")).SendKeys("00");
driver.FindElement(By.Name("submit")).Click();
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
private bool IsAlertPresent()
{
try
{
driver.SwitchTo().Alert();
return true;
}
catch (NoAlertPresentException)
{
return false;
}
}
private string CloseAlertAndGetItsText()
{
try
{
IAlert alert = driver.SwitchTo().Alert();
string alertText = alert.Text;
if (acceptNextAlert)
{
alert.Accept();
}
else
{
alert.Dismiss();
}
return alertText;
}
finally
{
acceptNextAlert = true;
}
}
}
}
I think a good start would be to transform your test into a parameterized test and use the TestCaseAttribute.
Your test could then look like this:
[Test]
[TestCase("Clayton", "abc", true)]
[TestCase("Clayton", "def", false)]
public void TheSignupTest(string username, string password, bool isAccepted)
{
driver.Navigate().GoToUrl(baseURL + "/Account/Login?ReturnUrl=%2f");
driver.FindElement(By.Id("UserName")).Clear();
driver.FindElement(By.Id("UserName")).SendKeys(username);
driver.FindElement(By.Id("Password")).Clear();
driver.FindElement(By.Id("Password")).SendKeys(password);
driver.FindElement(By.CssSelector("input.btn.small")).Click();
driver.FindElement(By.Id("nav2")).Click();
driver.FindElement(By.Id("upload-file")).Click();
driver.FindElement(By.Id("Name")).Clear();
driver.FindElement(By.Id("Name")).SendKeys("00");
driver.FindElement(By.Id("ReferenceNumberPrefix")).Clear();
driver.FindElement(By.Id("ReferenceNumberPrefix")).SendKeys("00");
driver.FindElement(By.Name("submit")).Click();
if (isAccepted)
{
Assert.That(driver.Url, Is.EqualTo(baseURL + "/PageWhereClientIsRedirectedToAfterSuccessfulLogin"));
}
else
{
Assert.That(driver.FindElement(By.Name("ErrorBox")).Text, Is.EqualTo("Login failed"));
}
}
The test cases are defined using the TestCaseAttribute:
[TestCase("Clayton", "abc", true)]
[TestCase("Clayton", "def", false)]
So you have two test cases in your test runner.

Trying to call code in my controller but getting Null Reference error

Don't want to over-complicate the issue, but I think I need to post all the code that's hooked into this error.
Using MvcMailer and introduced a separate Send mechanism (for use with Orchard CMS' own EMail).
The MvcMailer Code:
1) AskUsMailer.cs:
public class AskUsMailer : MailerBase, IAskUsMailer
{
public AskUsMailer()
: base()
{
//MasterName = "_Layout";
}
public virtual MvcMailMessage EMailAskUs(AskUsViewModel model)
{
var mailMessage = new MvcMailMessage { Subject = "Ask Us" };
ViewData.Model = model;
this.PopulateBody(mailMessage, viewName: "EMailAskUs");
return mailMessage;
}
}
2) IAskUsMailer.cs:
public interface IAskUsMailer : IDependency
{
MvcMailMessage EMailAskUs(AskUsViewModel model);
}
3) AskUsController.cs: (GETTING NULL REFERENCE ERROR BELOW)
[Themed]
public ActionResult Submitted()
{
//This is the new call (see new code below):
//Note: Debugging steps through eMailMessagingService,
//then shows the null reference error when continuing to
//SendAskUs
eMailMessagingService.SendAskUs(askUsData);
//Below is normal MvcMailer call:
//AskUsMailer.EMailAskUs(askUsData).Send();
return View(askUsData);
}
Note: askUsData is defined in a separate block in the controller:
private AskUsViewModel askUsData;
protected override void OnActionExecuting(ActionExecutingContext
filterContext)
{
var serialized = Request.Form["askUsData"];
if (serialized != null) //Form was posted containing serialized data
{
askUsData = (AskUsViewModel)new MvcSerializer().
Deserialize(serialized, SerializationMode.Signed);
TryUpdateModel(askUsData);
}
else
askUsData = (AskUsViewModel)TempData["askUsData"] ??
new AskUsViewModel();
TempData.Keep();
}
protected override void OnResultExecuted(ResultExecutedContext
filterContext)
{
if (filterContext.Result is RedirectToRouteResult)
TempData["askUsData"] = askUsData;
}
I did not know how to get my EMailMessagingService.cs (see below) call into the controller, so in a separate block in the controller I did this:
private IEMailMessagingService eMailMessagingService;
public AskUsController(IEMailMessagingService eMailMessagingService)
{
this.eMailMessagingService = eMailMessagingService;
}
I think this is part of my problem.
Now, the new code trying to hook into Orchard's EMail:
1) EMailMessagingServices.cs:
public class EMailMessagingService : IMessageManager
{
private IAskUsMailer askUsMailer;
private IOrchardServices orchardServices;
public EMailMessagingService(IAskUsMailer askUsMailer,
IOrchardServices orchardServices)
{
this.orchardServices = orchardServices;
this.askUsMailer = askUsMailer;
this.Logger = NullLogger.Instance;
}
public ILogger Logger { get; set; }
public void SendAskUs(AskUsViewModel model)
{
var messageAskUs = this.askUsMailer.EMailAskUs(model);
messageAskUs.To.Add("email#email.com");
//Don't need the following (setting up e-mails to send a copy anyway)
//messageAskUs.Bcc.Add(AdminEmail);
//messageAskUs.Subject = "blabla";
Send(messageAskUs);
}
....
}
The EMailMessagingService.cs also contains the Send method:
private void Send(MailMessage messageAskUs)
{
var smtpSettings = orchardServices.WorkContext.
CurrentSite.As<SmtpSettingsPart>();
// can't process emails if the Smtp settings have not yet been set
if (smtpSettings == null || !smtpSettings.IsValid())
{
Logger.Error("The SMTP Settings have not been set up.");
return;
}
using (var smtpClient = new SmtpClient(smtpSettings.Host,
smtpSettings.Port))
{
smtpClient.UseDefaultCredentials =
!smtpSettings.RequireCredentials;
if (!smtpClient.UseDefaultCredentials &&
!String.IsNullOrWhiteSpace(smtpSettings.UserName))
{
smtpClient.Credentials = new NetworkCredential
(smtpSettings.UserName, smtpSettings.Password);
}
if (messageAskUs.To.Count == 0)
{
Logger.Error("Recipient is missing an email address");
return;
}
smtpClient.EnableSsl = smtpSettings.EnableSsl;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
messageAskUs.From = new MailAddress(smtpSettings.Address);
messageAskUs.IsBodyHtml = messageAskUs.Body != null &&
messageAskUs.Body.Contains("<") &&
messageAskUs.Body.Contains(">");
try
{
smtpClient.Send(messageAskUs);
Logger.Debug("Message sent to {0} with subject: {1}",
messageAskUs.To[0].Address, messageAskUs.Subject);
}
catch (Exception e)
{
Logger.Error(e, "An unexpected error while sending
a message to {0} with subject: {1}",
messageAskUs.To[0].Address, messageAskUs.Subject);
}
}
}
Now, in EMailMessagingService.cs I was getting an error that things weren't being implemented, so I auto-generated the following (don't know if this is part of my error):
public void Send(Orchard.ContentManagement.Records.ContentItemRecord recipient, string type, string service, System.Collections.Generic.Dictionary<string, string> properties = null)
{
throw new NotImplementedException();
}
public void Send(System.Collections.Generic.IEnumerable<Orchard.ContentManagement.Records.ContentItemRecord> recipients, string type, string service, System.Collections.Generic.Dictionary<string, string> properties = null)
{
throw new NotImplementedException();
}
public void Send(System.Collections.Generic.IEnumerable<string> recipientAddresses, string type, string service, System.Collections.Generic.Dictionary<string, string> properties = null)
{
throw new NotImplementedException();
}
public bool HasChannels()
{
throw new NotImplementedException();
}
public System.Collections.Generic.IEnumerable<string> GetAvailableChannelServices()
{
throw new NotImplementedException();
}
2) IEMailMessagingServices.cs
public interface IEMailMessagingService
{
MailMessage SendAskUs(AskUsViewModel model);
}
MvcMailer works fine without this addition (outside of Orchard), but I am trying to get everything working within Orchard.
I just cannot figure out what I am doing wrong. Any thoughts?
Sorry for excessive code.
IEmailMessaginService does not implement IDependency, so it can't be found by Orchard as a dependency. That's why it's null.

Resources