How to change text to speech language in Xamarin.Android C# - c#

I wanted to make a text to speech application for a project and I used this as a reference: https://github.com/xamarin/monodroid-samples/tree/main/PlatformFeatures/TextToSpeech
However, whenever i open the app it always opens up the google tts service and I cannot change the language, and the spinner does not show any languages only "Default" is there a way to make this program not open up google tts service each time and making the language options available on the spinner? thanks so much!
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Support.V7.App;
using Android.Speech.Tts;
using Java.Util;
using Android.Graphics;
namespace DND_Connect
{
[Activity(Label = "Deaf")]
public class DeafPage : Activity, TextToSpeech.IOnInitListener
{
TextToSpeech textToSpeech;
Context context;
private readonly int MyCheckCode = 101, NeedLang = 103;
Java.Util.Locale lang;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.deaf);
var btnSayIt = FindViewById<Button>(Resource.Id.buttonSpeak);
var editWhatToSay = FindViewById<EditText>(Resource.Id.edtSpch);
var spinLanguages = FindViewById<Spinner>(Resource.Id.spnLng);
var txtSpeedVal = FindViewById<TextView>(Resource.Id.txtSpeed);
var txtPitchVal = FindViewById<TextView>(Resource.Id.txtPitch);
var seekSpeed = FindViewById<SeekBar>(Resource.Id.skSpeed);
var seekPitch = FindViewById<SeekBar>(Resource.Id.skPitch);
var txtView = FindViewById<TextView>(Resource.Id.deaftitle);
var txtView1 = FindViewById<TextView>(Resource.Id.deafdesc);
Typeface tf = Typeface.CreateFromAsset(Assets, "Roboto-Condensed.ttf");
txtView.SetTypeface(tf, Android.Graphics.TypefaceStyle.Normal);
txtView1.SetTypeface(tf, Android.Graphics.TypefaceStyle.Normal);
seekSpeed.Progress = seekPitch.Progress = 127;
txtSpeedVal.Text = txtPitchVal.Text = "0.5";
context = btnSayIt.Context;
textToSpeech = new TextToSpeech(this, this, "com.google.android.tts");
var langAvailable = new List<string> { "Default" };
var localesAvailable = Java.Util.Locale.GetAvailableLocales().ToList();
foreach (var locale in localesAvailable)
{
LanguageAvailableResult res = textToSpeech.IsLanguageAvailable(locale);
switch (res)
{
case LanguageAvailableResult.Available:
langAvailable.Add(locale.DisplayLanguage);
break;
case LanguageAvailableResult.CountryAvailable:
langAvailable.Add(locale.DisplayLanguage);
break;
case LanguageAvailableResult.CountryVarAvailable:
langAvailable.Add(locale.DisplayLanguage);
break;
}
}
langAvailable = langAvailable.OrderBy(t => t).Distinct().ToList();
var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, langAvailable);
spinLanguages.Adapter = adapter;
lang = Java.Util.Locale.Default;
textToSpeech.SetLanguage(lang);
textToSpeech.SetPitch(.5f);
textToSpeech.SetSpeechRate(.5f);
btnSayIt.Click += delegate
{
if (!string.IsNullOrEmpty(editWhatToSay.Text))
textToSpeech.Speak(editWhatToSay.Text, QueueMode.Flush, null);
};
seekPitch.StopTrackingTouch += (object sender, SeekBar.StopTrackingTouchEventArgs e) =>
{
var seek = sender as SeekBar;
var progress = seek.Progress / 255f;
textToSpeech.SetPitch(progress);
txtPitchVal.Text = progress.ToString("F2");
};
seekSpeed.StopTrackingTouch += (object sender, SeekBar.StopTrackingTouchEventArgs e) =>
{
var seek = sender as SeekBar;
var progress = seek.Progress / 255f;
textToSpeech.SetSpeechRate(progress);
txtSpeedVal.Text = progress.ToString("F2");
};
spinLanguages.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
{
lang = Java.Util.Locale.GetAvailableLocales().FirstOrDefault(t => t.DisplayLanguage == langAvailable[(int)e.Id]);
var checkTTSIntent = new Intent();
checkTTSIntent.SetAction(TextToSpeech.Engine.ActionCheckTtsData);
StartActivityForResult(checkTTSIntent, NeedLang);
};
}
void TextToSpeech.IOnInitListener.OnInit(OperationResult status)
{
if (status == OperationResult.Error)
textToSpeech.SetLanguage(Java.Util.Locale.Default);
if (status == OperationResult.Success)
textToSpeech.SetLanguage(lang);
}
protected override void OnActivityResult(int req, Result res, Intent data)
{
if (req == NeedLang)
{
var installTTS = new Intent();
installTTS.SetAction(TextToSpeech.Engine.ActionInstallTtsData);
StartActivity(installTTS);
}
}
}
}

[assembly: Xamarin.Forms.Dependency(typeof(TextToSpeechImplementation))]
namespace ShopFloor_Automation.Droid.Implementations
{
public class TextToSpeechImplementation : Java.Lang.Object, ITextToSpeech, TextToSpeech.IOnInitListener
{
TextToSpeech speaker;
string toSpeak;
public TextToSpeechImplementation() { }
public void OnInit([GeneratedEnum] OperationResult status)
{
if (status.Equals(OperationResult.Success))
{
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
public void Speak(string text)
{
var ctx = Forms.Context; // useful for many Android SDK features
toSpeak = text;
if (speaker == null)
{
speaker = new TextToSpeech(ctx, this);
}
else
{
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
}
}

Related

Dis connect websocket in c# after many minutes

I made a desktop program with c# an use
web socket ((use : https://www.nuget.org/packages/WebSocketSharp/1.0.3-rc11)) into
and server side script is PHP web socket ((use : http://socketo.me/))
but I encountered some errors.
1-When I call the Send method, the readyState switches to 'close' and I have to call Connect method before Send .
2-When The program stays idle for a while connection is close
Please help me 2 errors.
Thank you very much
my code c#:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
using Newtonsoft.Json;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using WebSocketSharp;
using System.Globalization;
namespace MyApp
{
public partial class Form1 : Form
{
public WebSocket ws = new WebSocket("ws://example.com:4563");
private static readonly HttpClient client = new HttpClient();
public int request_id;
public bool online;
public async Task<String> login(String id, String password)
{
var values = new Dictionary<string, string>
{
{ "id",id },
{ "password",password }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://example.com/Login", content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
public void websocket()
{
button1.Enabled = button4.Enabled = button5.Enabled = false;
ws.OnOpen += (sende, E) =>
{
//conncect app
};
ws.OnClose += (sende, E) =>
{
};
ws.OnMessage += (sende, E) =>
{
dynamic response = JsonConvert.DeserializeObject(E.Data);
switch ((String)response.type)
{
case "push_for_app":
{
label10.Text = (String)response.response;
turn_count = (String)response.response;
if ((String)response.response == "0")
{
button1.Enabled = button4.Enabled = button5.Enabled = false;
}
else if (online) button1.Enabled = true;
}
break;
case "request":
{
switch ((String)response.method)
{
case "logout":
{
if ((String)response.response == "true")
{
groupBox1.Visible = false;
groupBox4.Visible = false;
groupBox1.Visible = false;
groupBox4.Visible = false;
groupBox2.Visible = true;
}
}
break;
case "get_turn_count":
{
label10.Text = (String)response.response;
turn_count = (String)response.response;
if ((String)response.response == "0")
{
button1.Enabled = button4.Enabled = button5.Enabled = false;
}
else if (online) button1.Enabled = true;
}
break;
case "set_online":
{
if ((String)response.response == "is_online")
{
button2.Visible = true;
online = true;
{
var template = new
{
type = "request",
method = "get_turn_count"
};
String output = JsonConvert.SerializeObject(template);
ws.Connect();
ws.Send(output);
}
}
}
break;
case "set_offline":
{
if ((String)response.response == "is_offline")
{
button8.Visible = true;
button1.Enabled = false;
online = false;
}
}
break;
default: break;
}
}
break;
default: break;
}
};
var List = new List<KeyValuePair<String, String>> {
new KeyValuePair<String, String>("api-key", "jshTRHNSDB54n7y4e5nhty"),
new KeyValuePair<String, String>("secret-key", secret_key),
new KeyValuePair<String, String>("type", "app")
};
ws.CustomHeaders = List;
ws.Connect();
}
//login
private void button7_Click(object sender, EventArgs e)
{
Task<String> task = Task.Run(async () => await login(textBox1.Text, textBox3.Text));
task.Wait();
dynamic res = JsonConvert.DeserializeObject(task.Result);
if (res.state == "true")
{
secret_key = res.message;
set_secret(secret_key);
groupBox1.Visible = true;
groupBox4.Visible = true;
groupBox2.Visible = false;
button8.Visible = true;
//connect socket
websocket();
}
else { label11.Text = res.message; }
}
//start app
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(SystemInformation.VirtualScreen.Width - this.Width, SystemInformation.VirtualScreen.Height - this.Height);
this.BringToFront();
this.TopMost = true;
this.Focus();
}
//set offline
private void button2_Click(object sender, EventArgs e)
{
var template = new
{
type = "request_from_pharmacy",
method = "set_offline"
};
String output = JsonConvert.SerializeObject(template);
ws.Connect();
ws.Send(output);
button2.Visible = false;
button8.Visible = true;
}
//set online
private void button8_Click(object sender, EventArgs e)
{
var template = new
{
type = "request",
method = "set_online"
};
String output = JsonConvert.SerializeObject(template);
ws.Connect();
ws.Send(output);
button8.Visible = false;
button2.Visible = true;
}
}
}

Regarding strongly typed dataset in windows form application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GST.Masters
{
public partial class Customers : Heptanesia.Winforms.Ui.Forms.MainUC
{
public static string recCode
{ get; set; }
public string RC;
public bool insertFlag;
public Data.GSTDb.CustomersRow r;
public Data.GSTDb.CustomersGSTNosRow gr;
public Data.GSTDb.CustomersDataTable dt = new Data.GSTDb.CustomersDataTable();
public Customers()
{
InitializeComponent();
recCode = Guid.NewGuid().ToString();
this.Load += new EventHandler(this.Customers_Load);
this.Ts.SaveClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SaveClickedEventHandler(this.Ts_SaveClicked);
this.Ts.AddNewClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.AddNewClickedEventHandler(this.Ts_AddNewClicked);
this.Ts.SearchClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SearchClickedEventHandler(this.Ts_SearchClicked);
this.DgGST.CellValidated += (sender, e) =>
{
string name = this.DgGST.Columns[e.ColumnIndex].Name;
if (name == "DGCCountryCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.statesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCStateCode"].Value = null;
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
else if (name == "DGCStateCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.citiesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
};
}
private void Ts_AddNewClicked(object sender, EventArgs e)
{
this.gSTDb.Customers.Rows.Clear();
r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter CGT = new Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter();
CGT.FillByParentCode(gSTDb.CustomersGSTNos, r.RecCode);
}
private void Ts_SearchClicked(object sender, EventArgs e)
{
Heptanesia.Winforms.Ui.Forms.SearchForm sf = new Heptanesia.Winforms.Ui.Forms.SearchForm();
sf.DataSource = new Data.GSTDbTableAdapters.CustomersTableAdapter().GetData();
sf.DisplayColumns = new string[] { "Name" };
sf.DisplayHeaders = new string[] { "Customers Name" };
sf.DisplayWidths = new int[] { 200 };
if (sf.ShowDialog(this) == DialogResult.OK)
{
this.RC = sf.ReturnRow["RecCode"].ToString();
this.customersTableAdapter.FillByRecCode(this.gSTDb.Customers, RC);
}
}
private void Ts_SaveClicked(object sender, EventArgs e)
{
string message = "Error: ";
try
{
this.customersBindingSource.EndEdit();
//if (this.DgGST.CurrentRow.DataBoundItem != null)
this.fkCustomerGSTNosCustomersBindingSource.EndEdit();
if (this.gSTDb.Customers.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.customersBindingSource, this.gSTDb.Customers.GetErrors()[0]);
else if (this.gSTDb.CustomersGSTNos.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.fkCustomerGSTNosCustomersBindingSource, this.gSTDb.CustomersGSTNos.GetErrors()[0]);
else
{
this.gSTDb.Customers.BeforeSave();
this.gSTDb.CustomersGSTNos.BeforeSave();
Data.GSTDbTableAdapters.TableAdapterManager tm = new Data.GSTDbTableAdapters.TableAdapterManager();
tm.CustomersTableAdapter = this.customersTableAdapter;
tm.CustomersGSTNosTableAdapter = this.customersGSTNosTableAdapter;
tm.UpdateAll(this.gSTDb);
message = "Record(s) Saved Successfully";
}
}
catch (Exception ex)
{
message += ex.Message;
}
MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Customers_Load(object sender, EventArgs e)
{
this.FormIsLoading = true;
this.customersTableAdapter.Fill(this.gSTDb.Customers);
this.customersGSTNosTableAdapter.Fill(this.gSTDb.CustomersGSTNos);
this.countriesTableAdapter.Fill(this.gSTDb.Countries);
this.statesTableAdapter.Fill(this.gSTDb.States);
this.citiesTableAdapter.Fill(this.gSTDb.Cities);
this.gSTDb.Customers.Rows.Clear();
if (this.gSTDb.Customers.Rows.Count == 0)
{
Data.GSTDb.CustomersRow r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
}
this.FormIsLoading = false;
}
private void DgGST_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception is ArgumentException)
{
object value = DgGST.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (!((DataGridViewComboBoxColumn)DgGST.Columns[e.ColumnIndex]).Items.Contains(value))
{
((DataGridViewComboBoxCell)DgGST[e.ColumnIndex, e.RowIndex]).Value = DBNull.Value;
//((DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex]).Items.Add(value);
e.ThrowException = false;
}
}
else
{
MessageBox.Show(e.Exception.Message);
e.Cancel = true;
}
}
}
}
I am developing one simple invoice application in which I am having a simple Customer screen module.A Customer can have any number of GST records in the Datagridview.The Screen is based on Customer Masters(Textboxes) and Customers Master Details(Datagridview) relationship through foreign keys. And I am Using Strongly Typed Dataset in this project as a xsd file.This Screen has 3 buttons i.e.New,Save and Find toolstrip menu.
When I start adding records after clicking on New Buttonstrip and and save ,it saves it successfully and when I press New Ideally it should clear the rows.The main issue here is that it is not clearing the rows??
I am enclosing the cs file here.
What I have tried:
Everything as I can Do.
Clearing the Rows through Rows.Clear(); 2) I tried clearing
Binding Source and DataGridview after setting it null.
Nothing Worked.

Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"

Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"
After about 4 hours of searching I cannot figure out this error. I am using the Windows 10 IOT Core on a RPI 3. My program is pretty basic, however I can not convert the datatype within the code to resolve the error.
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Windows.Devices.WiFi;
using Windows.Networking.Connectivity;
using Windows.Security.Credentials;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WiFiConnect
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class WiFiConnect_Scenario : Page
{
MainPage rootPage;
private WiFiAdapter firstAdapter;
public ObservableCollection<WiFiNetworkDisplay> ResultCollection
{
get;
private set;
}
public WiFiConnect_Scenario()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
rootPage = MainPage.Current;
// RequestAccessAsync must have been called at least once by the app before using the API
// Calling it multiple times is fine but not necessary
// RequestAccessAsync must be called from the UI thread
var access = await WiFiAdapter.RequestAccessAsync();
if (access != WiFiAccessStatus.Allowed)
{
rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
}
else
{
DataContext = this;
var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDevice Selector());
if (result.Count >= 1)
{
firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
var button = new Button();
button.Content = string.Format("Scan Available Wifi Networks");
button.Click += Button_Click;
Buttons.Children.Add(button);
}
else
{
rootPage.NotifyUser("No WiFi Adapters detected on this machine.", NotifyType.ErrorMessage);
}
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await firstAdapter.ScanAsync();
ConnectionBar.Visibility = Visibility.Collapsed;
DisplayNetworkReport(firstAdapter.NetworkReport);
}
private void DisplayNetworkReport(WiFiNetworkReport report)
{
rootPage.NotifyUser(string.Format("Network Report Timestamp: {0}", report.Timestamp), NotifyType.StatusMessage);
ResultCollection.Clear();
foreach (var network in report.AvailableNetworks)
{
ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter));
}
}
private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null)
{
return;
}
// Show the connection bar
ConnectionBar.Visibility = Visibility.Visible;
// Only show the password box if needed
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
NetworkKeyInfo.Visibility = Visibility.Collapsed;
}
else
{
NetworkKeyInfo.Visibility = Visibility.Visible;
}
}
private async void ConnectButton_Click(object sender, RoutedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null || firstAdapter == null)
{
rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
return;
}
WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;
if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true)
{
reconnectionKind = WiFiReconnectionKind.Automatic;
}
WiFiConnectionResult result;
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
}
else
{
FileStream file = new FileStream("final-wordlist.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
sr.ReadLine();
var textLines = File.ReadAllLines("final-wordlist.txt");
foreach (var line in textLines)
{
string[] dataArray = line.Split(' ');
foreach (var item in dataArray)
{
PasswordCredential credential = line;
//string credential = line.ToString();
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
}
}
// Only the password potion of the credential need to be supplied
}
if (result.ConnectionStatus == WiFiConnectionStatus.Success)
{
rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);
// refresh the webpage
webViewGrid.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
refreshBrowserButton.Visibility = Visibility.Visible;
}
else
{
rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
}
// Since a connection attempt was made, update the connectivity level displayed for each
foreach (var network in ResultCollection)
{
network.UpdateConnectivityLevel();
}
}
private void Browser_Toggle_Click(object sender, RoutedEventArgs e)
{
if (webViewGrid.Visibility == Visibility.Visible)
{
webViewGrid.Visibility = Visibility.Collapsed;
refreshBrowserButton.Visibility = Visibility.Collapsed;
toggleBrowserButton.Content = "Show Browser Control";
}
else
{
webViewGrid.Visibility = Visibility.Visible;
refreshBrowserButton.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
}
}
private void Browser_Refresh(object sender, RoutedEventArgs e)
{
webView.Refresh();
}
}
}
This worked for me. The problem was it was it need more than one var to fill it.
var credential = new PasswordCredential("Module", "Username", "Password");
Try this:
PasswordCredential credential = null;
if (!string.IsNullOrEmpty(line))
{
credential = new PasswordCredential()
{
Password = line
};
}

How can i upload to a youtube account specific account using UserCredential revoke ?

In my class that i'm using to upload to youtube a video files and it's working fine the uploading i want to make something that on the form designer i will have a button of a gmail account when i click this button it will make two things:
Will upload the video file to the account of this button.
For example the text on the button will be test#gmail.com
So when i click the button it will check and if there is already a user connected on the pc to gmail account and if it's not test#gmail.com then first make revoke then connect to the test#gmail.com and upload the video file.
But in case there no gmail account yet connected on the pc then the user will enter a gmail account it will connect to it and upload.
Will revoke.
The problem now is that i have one button that all it does is revoking.
And i need to change on the browser in this case chrome the gmail account or to log in to a gmail account then running my program over again then it will showm e this screen where i need to accept the authorization to this acocunt then it will upload to it the video file.
And i want to pass over the part of log in each time to another gmail via the chrome browser and pass over the need of making accept over again each time changing account.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Google.GData.Client;
using Google.GData.Extensions;
using System.Reflection;
using System.IO;
using System.Threading;
using System.Net;
using Google.Apis.YouTube;
using Google.Apis.Requests;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail;
using MailBee;
namespace test
{
public partial class testing : Form
{
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
YouTubeService service;
string apiKey = "myapikey";
string FileNameToUpload = "";
string[] stringProgressReport = new string[5];
long totalBytes = 0;
DateTime dt;
public static string fileuploadedsuccess = "";
public Youtube_Uploader(string filetoupload)
{
InitializeComponent();
FileNameToUpload = #"C:\Users\test\Videos\test.mp4";
service = AuthenticateOauth(apiKey);
var videoCatagories = service.VideoCategories.List("snippet");
videoCatagories.RegionCode = "IL";
var result = videoCatagories.Execute();
UserCredentials();
UserYoutubeService();
MakeRequest();
backgroundWorker1.RunWorkerAsync();
}
public static string uploadstatus = "";
Video objects = null;
private void videosInsertRequest_ResponseReceived(Video obj)
{
System.Timers.Timer aTimer;
aTimer = new System.Timers.Timer();
aTimer.Elapsed += aTimer_Elapsed;
aTimer.Interval = 10000;
aTimer.Enabled = false;
uploadstatus = obj.Status.UploadStatus;
if (uploadstatus == "uploaded")
{
fileuploadedsuccess = "file uploaded successfully";
}
if (uploadstatus == "Completed")
{
fileuploadedsuccess = "completed";
}
objects = obj;
}
double mbSent = 0;
int percentComplete = 0;
VideoProcessingDetailsProcessingProgress vp = new VideoProcessingDetailsProcessingProgress();
private void videosInsertRequest_ProgressChanged(IUploadProgress obj)
{
ulong? ul = vp.TimeLeftMs;
stringProgressReport[1] = obj.Status.ToString();
mbSent = ((double)obj.BytesSent) / (1 << 20);
stringProgressReport[2] = mbSent.ToString();
percentComplete = (int)Math.Round(((double)obj.BytesSent) / totalBytes * 100);
stringProgressReport[3] = percentComplete.ToString();
if (obj.BytesSent != 0)
{
var currentTime = DateTime.Now;
TimeSpan diff = currentTime - dt;
double diffSeconds = (DateTime.Now - dt).TotalSeconds;
double averageSpeed = obj.BytesSent / diffSeconds;
double MBunits = ConvertBytesToMegabytes((long)averageSpeed);
stringProgressReport[4] = string.Format("{0:f2} MB/s", MBunits);
}
}
public static YouTubeService AuthenticateOauth(string apiKey)
{
try
{
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
ApiKey = apiKey,
ApplicationName = "YouTube Uploader",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}
private void MakeRequest()
{
var searchListRequest = service.Search.List("snippet");
searchListRequest.Q = "daniel lipman gta"; // Replace with your search term.
searchListRequest.RegionCode = "IL";
searchListRequest.MaxResults = 50;
var searchListResponse = searchListRequest.Execute();
List<string> videos = new List<string>();
List<string> channels = new List<string>();
List<string> playlists = new List<string>();
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
case "youtube#channel":
channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
break;
case "youtube#playlist":
playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
break;
}
}
}
static Video video = new Video();
public void Revoke()
{
if (uc!=null)
{
uc.RevokeTokenAsync(CancellationToken.None);
}
}
UserCredential uc = null;
private void UploadVideo(string FileName, string VideoTitle, string VideoDescription)
{
try
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
video.Snippet = new VideoSnippet();
video.Snippet.Title = VideoTitle;
video.Snippet.Description = VideoDescription;
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public";
using (var fileStream = new FileStream(FileName, FileMode.Open))
{
const int KB = 0x400;
var minimumChunkSize = 256 * KB;
var videosInsertRequest = youtubeService.Videos.Insert(video,
"snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged +=
videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived +=
videosInsertRequest_ResponseReceived;
// The default chunk size is 10MB, here will use 1MB.
videosInsertRequest.ChunkSize = minimumChunkSize * 3;
dt = DateTime.Now;
videosInsertRequest.Upload();
}
}
catch (Exception errors)
{
string errorss = errors.ToString();
}
}
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
private void Youtube_Uploader_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
UploadVideo(FileNameToUpload, "test", "Testing");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Revoke();
}
UserCredential credential = null;
private void UserCredentials()
{
using (FileStream stream = new FileStream(#"C:\jason file\client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None,
new FileDataStore("YouTube.Auth.Store")).Result;
}
uc = credential;
}
private void UserYoutubeService()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
}
}
}
In this class i have this part:
private void button1_Click(object sender, EventArgs e)
{
Revoke();
}
And
public void Revoke()
{
if (uc!=null)
{
uc.RevokeTokenAsync(CancellationToken.None);
}
}
And the user credential
UserCredential credential = null;
private void UserCredentials()
{
using (FileStream stream = new FileStream(#"C:\jason file\client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None,
new FileDataStore("YouTube.Auth.Store")).Result;
}
uc = credential;
}
The problem is that this GoogleWebAuthorizationBroker show the screen that i need to accept each time i did revoke.
Also a problem is how to check using the GoogleWebAuthorizationBroker if there is any user logged in already on the pc to gmail and get the gmail address.
And then to decide if to revoke or not and also how to connect to a gmail account using the GoogleWebAuthorizationBroker.
I'm using the google api.

How to login to google accounts using awesomium in C#.net?

I'm learning Awesomium and following is the code in which I'm trying to login to https://accounts.google.com. I'm successfully able to set the login and password field values in the page, but not able to submit the login form, neither does the click works. Can anyone help me how to login?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
namespace Awesom
{
class Program1
{
public static void Main(String[] args)
{
Console.WriteLine("Started....");
WebView wv = WebCore.CreateWebView(1024, 600);
wv.Source = new Uri("https://accounts.google.com");
wv.LoadingFrameComplete += (s, e) =>
{
if (!e.IsMainFrame)
return;
dynamic document = (JSObject) wv.ExecuteJavascriptWithResult("document");
using(document)
{
//Works
var tbox = document.getElementById("Email");
tbox.value = "XXXXXXXX#gmail.com";
//Works
var pbox = document.getElementById("Passwd");
pbox.value = "**********";
//Doesnt work
var lform = document.getElementById("gaia_loginform");
lform.submit();
//Doesnt work
var sbox = document.getElementById("signIn");
sbox.click();
}
BitmapSurface surface = (BitmapSurface)wv.Surface;
surface.SaveToPNG("result.png", true);
WebCore.Shutdown();
};
WebCore.Run();
}
}
}
Result image:
It IS working, you're just taking the screenshot too early. You need to account for the second frame navigation, if you use .click().
public static void Main(String[] args)
{
Console.WriteLine("Started....");
WebView wv = WebCore.CreateWebView(1024, 600);
wv.Source = new Uri("https://accounts.google.com/");
FrameEventHandler handler = null;
handler = (s, e) =>
{
if (e.IsMainFrame)
{
// we have finished loading main page,
// let's unhook ourselves
wv.LoadingFrameComplete -= handler;
LoginAndTakeScreenShot(wv);
}
};
wv.LoadingFrameComplete += handler;
WebCore.Run();
}
private static void LoginAndTakeScreenShot(WebView wv)
{
dynamic document = (JSObject)wv.ExecuteJavascriptWithResult("document");
using (document)
{
//Works
var tbox = document.getElementById("Email");
tbox.value = "XXXXXXXX#gmail.com";
//Works
var pbox = document.getElementById("Passwd");
pbox.value = "**********";
FrameEventHandler handler = null;
handler = (sender, args) =>
{
if (args.IsMainFrame)
{
wv.LoadingFrameComplete -= handler;
BitmapSurface surface = (BitmapSurface)wv.Surface;
surface.SaveToPNG("result.png", true);
WebCore.Shutdown();
}
};
wv.LoadingFrameComplete += handler;
var sbox = document.getElementById("signIn");
sbox.click();
}
}

Categories