Visual Studio 2017 not displaying my test in the Test Explorer - c#

I wrote the following script on my computer at work, where the script ran perfectly. However, I can't get it to run on my computer at home. I have the exact version of Visual Studio installed.
I click build, it successfully builds, however, it doesn't lead to the test being added to the test explorer.
My code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
using OpenQA.Selenium.Support.UI;
namespace TrainLineTest
{
public class Program
{
public static IWebDriver driver = new ChromeDriver();
public static void Main(string[] args)
{ }
public static void SetUp()
{
driver.Manage().Window.Maximize();
driver.Url = "https://www.thetrainline.com";
}
[Test]
public static void EnterDetails()
{
SetUp();
var OriginStation = driver.FindElement(By.Id("originStation"));
OriginStation.SendKeys("London Euston");
var DestinationStation = driver.FindElement(By.Id("destinationStation"));
DestinationStation.SendKeys("Manchester Picadilly");
var TravelMethod = driver.FindElement(By.Id("journey-type-return"));
TravelMethod.Click();
var OutDate = driver.FindElement(By.Id("outDate"));
OutDate.Clear();
OutDate.SendKeys("26-Aug-17");
OutDate.SendKeys(Keys.Tab);
Thread.Sleep(700);
new SelectElement(driver.FindElement(By.Id("outDepartOrArrive"))).SelectByValue("B");
Thread.Sleep(700);
new SelectElement(driver.FindElement(By.Id("outHour"))).SelectByValue("9");
new SelectElement(driver.FindElement(By.Id("outMinute"))).SelectByValue("30");
Thread.Sleep(700);
var ReturnDate = driver.FindElement(By.Id("returnDate"));
ReturnDate.Clear();
ReturnDate.SendKeys("15-Sep-17");
ReturnDate.SendKeys(Keys.Tab);
Thread.Sleep(500);
new SelectElement(driver.FindElement(By.Id("returnDepartOrArrive"))).SelectByValue("B");
Thread.Sleep(500);
new SelectElement(driver.FindElement(By.Id("returnHour"))).SelectByValue("14");
new SelectElement(driver.FindElement(By.Id("returnMinute"))).SelectByValue("30");
Thread.Sleep(500);
var Passengers = driver.FindElement(By.ClassName("passenger-summary-people"));
Passengers.Click();
Thread.Sleep(500);
new SelectElement(driver.FindElement(By.Name("AdultsTravelling"))).SelectByValue("2");
Thread.Sleep(500);
new SelectElement(driver.FindElement(By.Name("ChildrenTravelling"))).SelectByValue("1");
Thread.Sleep(500);
var JourneyComplete = driver.FindElement(By.CssSelector("#extendedSearchForm > div:nth-child(6) > div:nth-child(1) > div > div > button"));
JourneyComplete.Click();
Thread.Sleep(5000);
var ExtendedSearch = driver.FindElement(By.Id("submitButton"));
ExtendedSearch.Click();
Thread.Sleep(5000);
}
[TearDown]
public void CloseApp()
{
driver.Close();
}
}
}

If you are using NUnit3, you'll need to get NUnit3TestAdapter from the NuGet package manager. Once you have this package you'll be able to build your solution and have them show in Visual Studio's Test Explorer

Related

Chromedriver thread persists even after app crash. how to prevent it?

I have driver.close() and driver.quit() in my code but sometimes app gets crashed and those drivers, chrome.exe and conhosts are still open...
I do not have any idea how to prevent it
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MetroFramework.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Diagnostics;
using OpenQA.Selenium.Support.UI;
namespace WindowsFormsApplication4
{
public partial class Form1 : MetroForm
{
private IWebDriver driver;
private ChromeOptions option;
private List<string[]> list = new List<string[]>();
public Form1()
{
option = new ChromeOptions();
option.AddArgument("--headless --user-agent=Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
InitializeComponent();
LoadEngines();
}
private void LoadEngines() {
List<string[]> lista = File.ReadLines(#"C:\Redirect\sites.txt")
.Select(line => line.Split(','))
.ToList();
for (int i = 0; i < lista.Count; i++)
{
engines.Text += lista[i][0]+ "\r\n";
}
list = lista;
}
private void metroButton1_Click(object sender, EventArgs e)
{
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
service.SuppressInitialDiagnosticInformation = true;
if (inL.Text != String.Empty) {
List<string> inUrls = new List<string>(
inL.Text.Split(new string[] { "\r\n" },
StringSplitOptions.RemoveEmptyEntries));
Debug.WriteLine(inUrls[0]);
}
else
{
status.Text = "Enter Urls";
return;
}
try
{
driver = new ChromeDriver(service, option);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
for (int i = 0; i < list.Count; i++)
{
try
{
driver.Navigate().GoToUrl(list[i][0]);
driver.FindElement(By.XPath(list[i][1])).SendKeys("http://google.com");
driver.FindElement(By.XPath(list[i][2])).Click();
outL.Text += driver.FindElement(By.XPath(list[i][3])).GetAttribute(list[i][4]) + "\r\n";
}
catch (NoSuchElementException err)
{
Logs.Text += $"No such element: {err} could be found.";
continue;
}
}
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile("C://Image.png",
ScreenshotImageFormat.Png);
}
catch
{
throw;
}
finally
{
driver.Close();
driver.Quit();
driver.Dispose();
}
}
}
}
Edited: So I have added code, maybe it will help to fix my test.
I need to automatically close chromedriver.exe and chrome.exe after every run.
Is remote server a good solutions?
Ideally the chromedriver.exe thread should get purged after driver.quit() call. In case , if it doesn't you can invoke system level commands to do the job. You can create a batch file with the following code :
#echo off
rem just killing stray local chromedriver.exe instances.
taskkill /im chromedriver.exe /f
In your C# code, call this bat at the end of test suite :
System.Diagnostics.Process.Start("c:\\batchfilename.bat");

how to convert video in multiple bitrate using asp.net

I want to play one video in different bitrates. Like i uploaded one video in 1080P resolution i want play that video in 720P, 480P, 360P, 240P, 144P etc.
I want this solution in asp.net using C#.
Like youtube provide the facility to watch video in different resolutions.
Please help me regarding this.
I tried the following code but not working:
using Softpae.Media;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
Job2Convert myJob = new Job2Convert();
MediaServer ms = new MediaServer();
myJob.pszSrcFile = "E:\\EhabVideoLibrary\\videos\\sinbad.mkv";
myJob.pszDstFile = "E:\\EhabVideoLibrary\\videos\\sinbad.mp4";
myJob.pszDstFormat = "mp4";
myJob.pszAudioCodec = "aac";
myJob.nAudioChannels = 2;
myJob.nAudioBitrate = -1;
myJob.nAudioRate = -1;
myJob.pszVideoCodec = "h264";
myJob.nVideoBitrate = -1;
myJob.nVideoFrameRate = -1;
myJob.nVideoFrameWidth = -1;
myJob.nVideoFrameHeight = -1;
bool ret = ms.ConvertFile(myJob);
}
}
}
You can use FFplay of the FFmpeg project. (ffmpeg.org) With FFmpeg it's possible to encode and transcode almost every codec in the resolution you want. In this thread is the use of a command line application using C# described.
I've never tried it, but there are also libraries provided for .NET using FFmpeg like this:
ffmpegdotnet.codeplex.com
intuitive.sk/fflib
Success with it!
Here is an example code using ffmpeg (I tested it under Win7 VM):
using System;
namespace ConsoleApplication_FFmpegDemo
{
class Program
{
static void Main(string[] args)
{
string inputVideo = #"C:\Users\Public\Videos\Sample Videos\Wildlife.wmv";
string outputVideo = #"C:\Users\Public\Videos\Sample Videos\Wildlife.mp4";
string ffmpegArg = string.Format("-i \"{0}\" -vf scale=320:240 \"{1}\"", inputVideo, outputVideo);
string ffmpegPath = #"C:\Portable\ffmpeg-win32-static\bin\ffmpeg.exe";
FFmpegTask ffmpegTask = new FFmpegTask(ffmpegPath, ffmpegArg);
ffmpegTask.Start();
Console.ReadLine();
}
}
}
And the FFmpegTask.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
namespace ConsoleApplication_FFmpegDemo
{
public class FFmpegTask
{
public Process process = new Process();
public FFmpegTask(string ffmpegPath, string arguments)
{
process.StartInfo.FileName = ffmpegPath;
process.StartInfo.Arguments = arguments;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.UseShellExecute = false;
}
public bool Start()
{
return process.Start();
}
}
}

C# WP8 Copy File SD Card, Access denied

I try copy file from D:\Data\ to D:\WPSystem\APPS{GUID}\Install\ and i have error Access denied, who can help me and/or rebuild source ?
Pocket file manager can add new files without any errors
Anyone ever mentioned "However to copy files to apps folder try to use StorageFolder and StorageFile classes"
But I do not know how to apply it
Source : Click
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp1.Resources;
using System.IO;
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
var directory = new DirectoryInfo("D:\\WPSystem\\") { Attributes = System.IO.FileAttributes.Normal };
directory.Attributes = System.IO.FileAttributes.Normal;
foreach (var info in directory.GetFileSystemInfos("*"))
{
info.Attributes = System.IO.FileAttributes.Archive;
}
var dir = directory.GetDirectories("apps").FirstOrDefault();
if (dir != null)
{
dir.MoveTo("D:\\WPSystem\\appsx");
var dir2 = new DirectoryInfo(#"D:\WPSystem\appsx\{GUID}\Install\");
var file = dir2.GetFiles("AppManifest.xaml").FirstOrDefault();
if (file != null)
{
file.Delete();
}
Directory.Move("D:\\WPSystem\\appsx", "D:\\WPSystem\\apps");
var data = new DirectoryInfo("D:\\Data\\");
var appmanifest = data.GetFiles("AppManifest.xaml").FirstOrDefault();
if (appmanifest != null)
{
appmanifest.CopyTo(
"D:\\WPSystem\\apps\\{GUID}\\Install\\File.bin");
}
}
MessageBox.Show("Success !");
//Application.Current.Terminate();
}
catch(Exception ex)
{
MessageBox.Show("Error"+ Environment.NewLine + ex.Message);
}
}
}
}
if you're getting an Access Denied exception problem is not in the code. Either the user running the application does not have privileges to run this, or the file/destination folder is locked for some reason.

How to execute a scheduled task with “schtasks” without opening a new command line window using C# process?

I am trying to run a scheduled task from C# without opening a new command line window, using the following code without any success (it prompts a window every time I use it)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
Process p1 = new Process();
p1.StartInfo.FileName = #"C:\Windows\System32\schtasks.exe";
p1.StartInfo.Verb = "runas";
p1.StartInfo.Arguments = "/run /tn CCleaner";
p1.StartInfo.RedirectStandardOutput = true;
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p1.StartInfo.CreateNoWindow = true;
p1.Start();
p1.Close();
}
catch (Exception ex)
{
}
}
}
}
How could I solve this problem ?
Thank you so much for your attention
You can use a library that provides access to Task Scheduler API.
For example using http://taskscheduler.codeplex.com/
using (var ts = new TaskService())
{
Task task = ts.GetTask("My task");
task.Run();
}

Background Agent Not Performing.: Windows Phone 8

NEED A SOLUTION
Background agent is working only once. After There is no occurrence of a background agent. It works at the first time and it works perfectly as soon as the page opens. however, after that it takes forever and ever to do that again. sometimes page close and open doesn't work. that would probably because of not removing the agenet
My background Agent Code:
#define DEBUG_AGENT
using System;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Info;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Threading;
using Microsoft.Xna.Framework.Media;
using System.Windows.Input;
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.Net.Sockets;
using System.Text;
using System.Net;
namespace ScheduledTaskAgent1
{
public class ScheduledAgent : ScheduledTaskAgent
{
private static volatile bool _classInitialized;
//private DispatcherTimer s;
Socket _socket = null;
ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
double lat = 7.16126666666667;
static ScheduledAgent()
{
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += UnhandledException;
});
}
/// Code to execute on Unhandled Exceptions
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
protected override void OnInvoke(ScheduledTask task)
{
//TODO: Add code to perform your task in background
string toastTitle = "";
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
lat += 0.001;
string snmea = DD2NMEA(lat, 80.44506);
string dates = DateTime.UtcNow.ToString("ddMMyy");
string UTCTime = DateTime.UtcNow.ToString("hhmmss") + ".000";
string s1 = Checksum("$FRCMD,869444005499999,_SendMessage,,0809.67600,N,8050.70360,E,1.0,1.08,3.0,141013,055642.000,1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
string s = Send("$FRCMD,869444005499999,_SendMessage,," + snmea + ",1.0,1.08,3.0," + dates + "," + UTCTime + ",1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
startToastTask(task, toastTitle);
}
private void startToastTask(ScheduledTask task, string toastTitle)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif
// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}
}
}
My Page from app which calls the agent
PeriodicTask toastPeriodicTask;
const string toastTaskName = "ToastPeriodicAgent";
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
toastPeriodicTask = ScheduledActionService.Find(toastTaskName) as PeriodicTask;
StartPeriodicAgent(toastTaskName);
}
private void StartPeriodicAgent(string taskName)
{
toastPeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (toastPeriodicTask != null)
{
RemoveAgent(taskName);
}
toastPeriodicTask = new PeriodicTask(taskName);
toastPeriodicTask.Description = periodicTaskDesc;
try
{
ScheduledActionService.Add(toastPeriodicTask);
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(2));
#endif
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
{
MessageBox.Show("Background agents for this application have been disabled by the user.");
}
else if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
{
MessageBox.Show("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
}
else
{
MessageBox.Show("An InvalidOperationException occurred.");
}
}
catch (SchedulerServiceException)
{
}
}
Ensure that your project has DEBUG_AGENT defined. This is a setting within your project properties. To set this flag, follow these steps
Right click the project within VS and select Properties
Select the Build tab
Add DEBUG_AGENT to the "Conditional compilation symbols" field.
If that is set, I've found it's best to give at least 30 seconds in the LaunchForTest. Sometimes it doesn't quite schedule it when you tell it to.

Categories