What i'm trying to do is use the Selenium WebDriver to control Chrome instead of using Javascript, so basically combine Selenium & cefsharp so I can use .sendKeys().
I have docked the browser in a panel here panelBrowserMain.Controls.Add(browser); and read the official docs here: https://bitbucket.org/chromiumembedded/cef/wiki/UsingChromeDriver.md this example loads a seperate client cefClient.exe where as I just want to interact using my embedded browser located here panelBrowserMain.Controls.Add(browser);.
When I do a testing at LinkLabel1_LinkClicked to show the page source i'm getting System.NullReferenceException: Object reference not set to an instance of an object. errors, so the _driver is not being assigned (even though I do in the code)
I have Google'd quite a bit and their is hardly any information or solutions that I can see, is my code even correct, any help or tips would be appreciated.
using CefSharp;
using CefSharp.WinForms;
using OpenQA.Selenium.Chrome;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;
namespace projectname
{
public partial class FormBrowser : Form
{
public ChromiumWebBrowser browser;
private ChromeDriver _driver;
private void FormBrowser_Load(object sender, EventArgs e)
{
try
{
// Fix for the formClosing event not firing.
FormClosing += new FormClosingEventHandler(FormBrowser_FormClosed);
Text = string.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
}
catch (Exception ex)
{
ClassHelpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
}
}
private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
ClassHelpers.ReturnMessage(_driver.PageSource);
//_driver.FindElement(By.Name("user[profile_attributes][first_name]")).SendKeys("UserName");
}
catch (Exception ex)
{
ClassHelpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
}
}
public FormBrowser(string[] sites, string mode, FormMain formMain, ClassProject project)
{
InitializeComponent();
InitializeBrowser(sites, project);
}
public void InitializeBrowser(string[] sites, ClassProject project)
{
try
{
if (!Cef.IsInitialized)
{
// CEF.
CefSettings settings = new CefSettings()
{
LogFile = "cef/cefsharp.log",
CachePath = Path.GetFullPath("cef/cache/"),
UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
};
settings.BrowserSubprocessPath = Path.GetFullPath("cef/cefsharp/CefSharp.BrowserSubprocess.exe");
settings.LocalesDirPath = Path.GetFullPath("cef/cefsharp/locales");
settings.ResourcesDirPath = Path.GetFullPath("cef/cefsharp/");
settings.RemoteDebuggingPort = 8088;
settings.UserDataPath = Path.GetFullPath("cef/cefsharp/cefuserdata");
if (project.Proxy != "ip:port")
{
settings.CefCommandLineArgs.Add("proxy-server", project.Proxy);
}
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
// CEF.
sitesCount = sites.Count();
// Load in the first URL that was checked, which is index 0.
browser = new ChromiumWebBrowser(sites[counter])
{
MenuHandler = new MyCustomMenuHandler()
};
browser.AddressChanged += OnBrowserAddressChanged;
panelBrowserMain.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browserMain.Text = sites[counter];
// Selenium WebDriver.
ChromeOptions options = new ChromeOptions
{
DebuggerAddress = "localhost:8088"
};
options.AddArguments("--no-sandbox");
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
_driver = new ChromeDriver(service, options, TimeSpan.FromSeconds(180));
// Selenium WebDriver.
}
else
{
// IMPORTANT: Cef is already initialized, do not do it again.
browser = new ChromiumWebBrowser(sites[counter])
{
MenuHandler = new MyCustomMenuHandler()
};
browser.AddressChanged += OnBrowserAddressChanged;
panelBrowserMain.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browserMain.Text = sites[counter];
// Add the code here once we get it working above.
}
}
catch (Exception ex)
{
ClassHelpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
}
}
}
}
Related
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");
I am doing web scraping by using selenium dll's.But i face the problem when scrape the list of records. If I use the debugger it extract all the records, but if disable debugger and run the application it sometime display less records or sometime display no record.I want to know is there is any way to know that yet the page is fully loaded or not.
driver.FindElementsByClassName("search-result-gridview-item").ToList()
vary the record count.
driver.FindElementsByClassName("search-result-gridview-item").ToList().ForEach(x =>
{
objUPCProcess = new UPCProcessingModel();
try
{
objUPCProcess.Description = x.FindElement(By.ClassName("prod-ProductTitle")).Text;
objUPCProcess.Price = x.FindElement(By.ClassName("Price")).Text;
listOfProductDetails.Add(objUPCProcess);
if (i == 0)
{
log.Item = objUPCProcess.Description;
i++;
}
}
catch (OpenQA.Selenium.NoSuchElementException ex)
{
try
{
objUPCProcess.Description = x.FindElement(By.ClassName("prod-ProductTitle")).Text;
objUPCProcess.Price = ex.Message;
listOfProductDetails.Add(objUPCProcess);
}
catch
{
try
{
objUPCProcess.Price = x.FindElement(By.ClassName("Price")).Text;
objUPCProcess.Description = ex.Message;
listOfProductDetails.Add(objUPCProcess);
}
catch
{
objUPCProcess.Description = ex.Message;
objUPCProcess.Price = ex.Message;
log.Message = ex.Message;
listOfProductDetails.Add(objUPCProcess);
log.Status = "Error";
}
}
}
});
}
Looking at this case, I'm pretty sure this is caused by a synchronization issue (webdriver and page work at a different speed) with AJAX requests that actually populate the records. That's why
if disable debugger and run the application it sometime display less records or sometime display no record
I also don't see any explicit waits in your code. But you can implement a helper Utils method that will check
that yet the page is fully loaded or not
I've used the IScriptExecutor like so:
public void WaitSecondsForNewPageToLoad(int maxWaitTimeInSeconds)
{
string state = string.Empty;
bool jQueryActive = true;
try
{
WebDriverWait wait = new WebDriverWait(TestCaseContext.Driver,
TimeSpan.FromSeconds(maxWaitTimeInSeconds));
//Checks every 500 ms whether predicate returns true if returns exit otherwise keep trying till it returns true
wait.Until(d =>
{
try
{
state =
((IJavaScriptExecutor) TestCaseContext.Driver).ExecuteScript(
#"return document.readyState").ToString();
jQueryActive =
(bool)((IJavaScriptExecutor) TestCaseContext.Driver).ExecuteScript(
#"return jQuery.active == 0");
WindowsWhenSteps.WhenIFocusTheCurrentBrowserWindow();
}
catch (InvalidOperationException)
{
//Ignore
}
return (state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) ||
state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase)) &&
jQueryActive;
});
}
catch (TimeoutException)
{
//sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
Assert.IsTrue(false);
}
catch (NullReferenceException)
{
//sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
Assert.IsTrue(false);
}
catch (WebDriverException)
{
if (TestCaseContext.Driver.WindowHandles.Count == 1)
{
TestCaseContext.Driver.SwitchTo().Window(TestCaseContext.Driver.WindowHandles[0]);
}
state =
((IJavaScriptExecutor) TestCaseContext.Driver).ExecuteScript(
#"return document.readyState").ToString();
if (
!(state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) ||
state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase)))
Assert.IsTrue(false);
}
}
NOTE: You can lose some of the exception handling if it seems like an overhead, but I'm aiming at full answer in favor of the future readers too.
use the following code to check whether selenium is trigerred
/* * Created by SharpDevelop.
* User: sravanth
* Date: 2/2/2018
* Time: 1:33 AM *
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using System.Diagnostics;
using Microsoft.VisualBasic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
//using System.Collections;
using System.Collections.Generic;
namespace sele
{
class Program
{
public static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
//Console.Write("Press any key to continue . . . ");
//Console.ReadKey(true);
//System.setProperty("webdriver.ie.driver", "C:\\Users/sravanth/Downloads/IEDriverServer_x64_3.8.0/IEdriver.exe");
// C:\Users\sravanth\Downloads\IEDriverServer_x64_3.8.0
IWebDriver driver;
// = new InternetExplorerDriver(#"C:\\Users/sravanth/Downloads/IEDriverServer_x64_3.8.0");
var service = InternetExplorerDriverService.CreateDefaultService(#"C:\\Users/sravanth/Downloads/IEDriverServer_x64_3.8.0");
//var service = InternetExplorerDriverService.CreateDefaultService(#"C:\\Users/sravanth/Downloads/chromedriver_win32");
// properties on the service can be used to e.g. hide the command prompt
var options = new InternetExplorerOptions { IgnoreZoomLevel = true, InitialBrowserUrl = "file:///C:/Users/sravanth/Desktop/a.html", IntroduceInstabilityByIgnoringProtectedModeSettings = true };
driver = new InternetExplorerDriver(service, options);
//driver = new ChromeDriver(#"C:\\Users/sravanth/Downloads/chromedriver_win32");
//driver.Navigate().GoToUrl("https://www.w3schools.com/js/tryit.asp?filename=tryjs_prompt");
driver.Url="file:///C:/Users/sravanth/Desktop/a.html";
//driver.Navigate().GoToUrl("file:///C:/Users/sravanth/Desktop/a.html");
driver.Navigate();
//IList links = driver.FindElements(By.TagName("button"));
// Console.WriteLine(links.Count);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
//IWebElement btn = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("btn")));
IWebElement btn=driver.FindElement(By.Id("btn"));
btn.Click();
// System.Threading.Thread.Sleep(5000);
Process[] processes = Process.GetProcessesByName("iexplore");
Console.WriteLine(processes.Length);
int i=0;
IntPtr windowHandle;
foreach (Process p in processes)
{
i=i+1;
Console.WriteLine(i);
windowHandle = p.MainWindowHandle;
Console.Write("iexplore");
Console.WriteLine(windowHandle.ToString());
// do something with windowHandle
if(i.Equals(1))
{
//Console.WriteLine("Reached If Loop");
SetForegroundWindow(windowHandle);
}
}
//System.Windows.Forms.SendKeys.SendWait("%{F4}");
Console.WriteLine(processes.Length);
Process.Start("notepad.exe");
var prc = Process.GetProcessesByName("notepad");
if (prc.Length > 0)
{
SetForegroundWindow(prc[0].MainWindowHandle);
}
//System.Windows.Forms.SendKeys.SendWait("%{F4}");
}
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
}
}
I'm creating a cross platform mobile application for a local food truck for my senior project. I specifically want to use Parse for it's User class because there will be multiple roles. I'm having trouble with implementing Facebook authentication with Parse. For some reason, I keep getting an error that I can't access JsonValue. Can anyone give me some guidance?
Here is a link to my git repository, if that would help. https://github.com/mkmcgreal/FoodTruck.git
using System;
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Parse;
using System.Json;
using System.Threading.Tasks;
using Xamarin.Auth;
namespace FoodTruck.Droid
{
[Activity (Label = "Food Truck", MainLauncher = true, Icon = "#mipmap/icon")]
public class MainActivity : Activity
{
//int count = 1;
public void LoginToFacebook (bool allowCancel)
{
var auth = new OAuth2Authenticator (
clientId: "**************",
scope: "",
authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));
auth.AllowCancel = allowCancel;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += LoginComplete;
// UIViewController vc = auth.GetUI ();
// PresentViewController (vc, true, null);
}
public async void LoginComplete( object sender, AuthenticatorCompletedEventArgs e )
{
// We presented the UI, so it's up to us to dismiss it.
//DismissViewController (true, null);
if (!e.IsAuthenticated) {
Console.WriteLine ("Not Authorised");
return;
}
var accessToken = e.Account.Properties["access_token"].ToString();
var expiresIn = Convert.ToDouble(e.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds( expiresIn );
// Now that we're logged in, make a OAuth2 request to get the user's id.
var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, e.Account);
request.GetResponseAsync().ContinueWith (t => {
var builder = new AlertDialog.Builder (this);
if (t.IsFaulted)
{
builder.SetTitle ("Error");
builder.SetMessage (t.Exception.Flatten().InnerException.ToString());
}
else if (t.IsCanceled)
{
builder.SetTitle ("Task Canceled");
]
else {
var obj = JsonValue.Parse (t.Result.GetResponseText());
var id = obj["id"].ToString().Replace("\"","");
var user = ParseFacebookUtils.LogInAsync(id, accessToken,expiryDate);
builder.SetTitle ("Logged in");
builder.SetMessage ("Name: " + obj["name"]);
}
}
}
protected override void OnCreate (Bundle bundle)
{
Xamarin.Insights.Initialize (global::FoodTruck.Droid.XamarinInsights.ApiKey, this);
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
StartActivity (auth.GetUI (this));
// var facebook = FindViewById<Button> (Resource.Id.FacebookButton);
// facebook.Click += delegate { LoginToFacebook(true);};
//
// var facebookNoCancel = FindViewById<Button> (Resource.Id.FacebookButtonNoCancel);
// facebookNoCancel.Click += delegate { LoginToFacebook(false);};
//};
}
}
}
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.
There is this doc. available. So I used
YouTubeRequestSettings settings = new YouTubeRequestSettings("Appname","devkey", textBox1.Text, textBox2.Text);
request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = "Test";
newVideo.Tags.Add(new MediaCategory("Animals", YouTubeNameTable.CategorySchema));
newVideo.Description = "Testing Testing Testing";
newVideo.YouTubeEntry.Private = false;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource("C:\\BabyBoyScenesBackground_PAL.wmv", "video/x-ms-wmv");
try
{
request.Upload(newVideo);
}
catch (Exception ccc)
{
MessageBox.Show(ccc.ToString());
}
Just to get 401 unauthorized. What do I need to change. If you ask, all sources I found are either outdated or people were not dealing with that issue.
For "Appname","devkey" I used the appropriate values aswell as for pw and username.
I'm afraid in this case, as expected with a 401 unauthorized error, you must be giving incorrect details. I went to the trouble to try your code and it worked as expected, and uploaded the video. Your devkey, pw or username must be incorrect, or there must be a problem outside of the code posted above, since it worked fine for me.
However, you should really use a background worker for this task, perhaps like this:
namespace YouTube
{
using System;
using System.ComponentModel;
using System.Windows;
using Google.GData.Client;
using Google.GData.Extensions.MediaRss;
using Google.GData.YouTube;
using Google.YouTube;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private static BackgroundWorker uploader;
private static YouTubeRequestSettings settings;
static void UploaderDoWork(object sender, DoWorkEventArgs e)
{
var request = new YouTubeRequest(settings);
var newVideo = new Video { Title = "Test" };
newVideo.Tags.Add(new MediaCategory("Animals", YouTubeNameTable.CategorySchema));
newVideo.Description = "Testing Testing Testing";
newVideo.YouTubeEntry.Private = true;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource("C:\\Wildlife.wmv", "video/x-ms-wmv");
try
{
request.Upload(newVideo);
}
catch (Exception exception)
{
MessageBox.Show("Upload failed: " + exception.Message);
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
settings = new YouTubeRequestSettings(
"app",
"devkey",
"email",
"password");
uploader = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
uploader.DoWork += UploaderDoWork;
uploader.RunWorkerCompleted += delegate { MessageBox.Show("Upload completed!"); };
uploader.RunWorkerAsync();
MessageBox.Show("Initiated upload...");
}
}
}
Hope you sort it out!