Microsoft Translate API is not working properly - c#

I am trying to convert English text to Hindi text. For that I am using Microsoft Text translator API. But some of my text is not translating.
After googling I have found below code.
public string GetHindiText(string textToTranslate)
{
Carrier.ErrorCode = 0;
string TranslatedText = string.Empty;
try
{
Translator.LanguageServiceClient objTranslate = new Translator.LanguageServiceClient();
TranslatedText = objTranslate.Translate("***************", textToTranslate, "en", "hi");
}
catch (WebException ex)
{
Carrier.ErrorCode = 1;
return ex.Message;
}
return TranslatedText;
}
And I have added below service reference
http://api.microsofttranslator.com/V1/SOAP.svc
Most of the text is not translating. I need your suggestions to move forward.
Am I doing in correct way or anything I need to change. Any help is greatly helpful to me.
Thanks in advance.

Refer to the NuGet package NequeoNetTranslator, this contains text and speech translation APIs.
Sample of text translation this uses the new Cognitive version, first get your access token, through your translation [KEY]:
Nequeo.Net.Translator.Microsoft.Cognitive.Api apiat = new Nequeo.Net.Translator.Microsoft.Cognitive.Api(new Uri("https://api.cognitive.microsoft.com/sts/v1.0/"));
apiat.Credentials = new System.Net.NetworkCredential("[KEY]", "[KEY]");
string token = apiat.GetAccessToken();
Now call the translate method , this will translate en tode:
Nequeo.Net.Translator.Microsoft.Cognitive.Api api = new Nequeo.Net.Translator.Microsoft.Cognitive.Api(new Uri("https://api.microsofttranslator.com/v2/http.svc/"));
api.Credentials = new System.Net.NetworkCredential("[KEY]", "[KEY]");
byte[] data = api.Translate("hello", "de", "en", null, token);
Translation[] tran = api.Translate(data);
string tranText = System.Text.Encoding.Default.GetString(data);
If you are using speech to text then sample code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Nequeo.Net.Translator.Microsoft.Cognitive.SpeechApi apiat = null;
private void button1_Click(object sender, EventArgs e)
{
apiat = new Nequeo.Net.Translator.Microsoft.Cognitive.SpeechApi(new Uri("wss://dev.microsofttranslator.com/speech/"));
apiat.Credentials = new System.Net.NetworkCredential("[KEY]", "[KEY]");
string token = apiat.GetAccessToken(new Uri("https://api.cognitive.microsoft.com/sts/v1.0/"));
apiat.OnRecording += Apiat_OnRecording;
apiat.OnStopRecording += Apiat_OnStopRecording;
apiat.OnTranslationReceived += Apiat_OnTranslationReceived;
Nequeo.IO.Audio.Device device_in = Nequeo.IO.Audio.Devices.GetDeviceIn(0);
apiat.AudioDevice = device_in;
apiat.WriteStream = new System.IO.MemoryStream();
apiat.Translate("hr-HR", "en-US", token);
}
private void Apiat_OnTranslationReceived(object sender, EventArgs e)
{
System.IO.MemoryStream jj = (System.IO.MemoryStream)apiat.WriteStream;
string gg = Encoding.Default.GetString(jj.ToArray());
Nequeo.Net.Translator.Microsoft.Cognitive.SpeechTranslation dffddf = apiat.GetSpeechTranslation();
}
private void Apiat_OnStopRecording(object sender, EventArgs e)
{
bool kk = true;
}
private void Apiat_OnRecording(object sender, EventArgs e)
{
bool kk = true;
}
private void button2_Click(object sender, EventArgs e)
{
apiat.StopTranslate();
}
}

Related

C# Windows Forms Serial Communication with GMap app crash

I've written desktop application, that receives location via serial communication from NRF/GPS module, split that data in order to distinguish latitude, longitude and then i load these coordinates to map(i use GMap). But when i receive data, first 1 or 2 seconds it comes in a little confused form(like this 06840.370056;49.84006068). And i thought adding some Thread.Sleep will solve this problem, but instead application crashes after 5-10 seconds. How can i solve this problem, because i want my app run smoothly? Here is part of my code:
public partial class Form1 : Form
{
public string dataIn;
private List<PointLatLng> _points;
public Form1()
{
_points = new List<PointLatLng>();
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GMapProviders.GoogleMap.ApiKey = AppConfig.Key;
string[] ports = SerialPort.GetPortNames();
cBoxCom.Items.AddRange(ports);
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
gMap.MapProvider = GMapProviders.GoogleMap;
gMap.ShowCenter = false;
gMap.DragButton = MouseButtons.Left;
gMap.SetPositionByKeywords("Chennai, India");
}
private void btnConnect_Click(object sender, EventArgs e)
{
serialPort1.PortName = cBoxCom.Text;
serialPort1.BaudRate = Convert.ToInt32(cBoxBaudrate.Text);
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
serialPort1.Open();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
}
}
private void btnClearDataIn_Click(object sender, EventArgs e)
{
if (richBoxReciever.Text != "")
{
richBoxReciever.Text = " ";
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
dataIn = serialPort1.ReadExisting();
this.Invoke(new EventHandler(ShowData));
}
private void ShowData(object sender, EventArgs e)
{
Thread.Sleep(3000);
richBoxReciever.Text += dataIn;
Thread.Sleep(5000);
string[] locationData = dataIn.Split(new char[] { ';' });
List<string> tokens = new List<string>();
foreach (string s in locationData)
{
if (s.Length != 0)
{
tokens.Add(s);
}
}
txtLat.Text = tokens[0];
txtLon.Text = tokens[1];
}

how to copy "speech to text" text in a string variable for string matching purpose?

I'm a novice to C# i'm not sure if I'm writing on the right forum. I am building simple speech recognition program which takes voice command as input, performs speech to text translation and then searches a video matching to that text.
I am currently storing output in text box but I want to store it in string.
I am unable to write correct logical code for storing recognized text into string, if anyone could advise me How can I do this ? here is my code...
public partial class Form1 : Form
{
var ss = new SpeechSynthesizer();
var pb = new PromptBuilder();
var sre = new SpeechRecognitionEngine();
var clist = new Choices();
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
btnStop.Enabled = true;
clist.Add(new string[] { "go away", "able", "active", "actual", "afraid", "busy", "casual" });
Grammar gr = new Grammar(new GrammarBuilder(clist));
try
{
sre.RequestRecognizerUpdate();
sre.LoadGrammar(gr);
sre.SpeechRecognized+= sre_SpeechRecognized;
sre.SetInputToDefaultAudioDevice();
sre.RecognizeAsync(RecognizeMode.Multiple);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
private void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) =>
textContent.Text += e.Result.Text.ToString() + Environment.NewLine;
private void btnStop_Click(object sender, EventArgs e)
{
sre.RecognizeAsyncStop();
btnStart.Enabled = true;
btnStop.Enabled = false;
}
}

Call a method inside an event handler function

I'm trying to implement an application in C# which generates me a QR Code. I've managed to do this, but I don't know how to call CreateQRImage(string inputData) inside the genButton_Click(object sender, EventArgs e).
I inside the windows form I have a textbox and a button, and I think that the function CreateQRImage must be called with the name of the textbox
Here is the code:
private void genButton_Click(object sender, EventArgs e)
{
}
public void CreateQRImage(string inputData)
{
if (inputData.Trim() == String.Empty)
{
System.Windows.Forms.MessageBox.Show("Data must not be empty.");
}
BarcodeWriter qrcoder = new ZXing.BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.QrCode.QrCodeEncodingOptions
{
ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
Height = 250,
Width = 250
}
};
string tempFileName = System.IO.Path.GetTempPath() + inputData + ".png";
Image image;
String data = inputData;
var result = qrcoder.Write(inputData);
image = new Bitmap(result);
image.Save(tempFileName);
System.Diagnostics.Process.Start(tempFileName);
}
This should do the trick:
private void genButton_Click(object sender, EventArgs e)
{
// Assuming your text box name. Also assuming UI disables button until text is entered.
this.CreateQRImage(myTextBox.Text);
}

Need help getting listbox item text from secondary form to main form

I have been looking all over the Internet for this and have found similar, but none of it will work for me. Everything I have found assumes the listbox is on the main form and not the secondary form, or the code is for an older version of C# or Visual Studio (I am using VS2008).
I am creating a web browser that has a button on the main form (called frmMyBrowser) to open a dialog (frmBookmarks) with a listbox (lstBookmark) with bookmarked URLs. I need to be able to double click on an item (the bookmarked URL) and have the text pasted into the address bar (cmbAddress) of the main form.
Any help would be GREATLY appreciated.
I figured out that if I create the window at runtime, I can get it to work. In case anyone is interested, the code I used is below.
public void frmMyBrowser_ShowFavorites(object sender, EventArgs e)
{
frmFavorites.ShowIcon = false;
frmFavorites.ShowInTaskbar = false;
frmFavorites.MinimizeBox = false;
frmFavorites.MaximizeBox = false;
frmFavorites.ControlBox = false;
frmFavorites.Text = "Bookmarks";
frmFavorites.Width = 500;
frmFavorites.Height = 350;
frmFavorites.Controls.Add(lstFavorites);
frmFavorites.Controls.Add(btnRemoveFavorite);
frmFavorites.Controls.Add(btnAddFavorite);
frmFavorites.Controls.Add(btnCloseFavorites);
frmFavorites.Controls.Add(txtCurrentUrl);
lstFavorites.Width = 484;
lstFavorites.Height = 245;
btnRemoveFavorite.Location = new Point(8, 280);
btnAddFavorite.Location = new Point(8, 255);
btnCloseFavorites.Location = new Point(400, 255);
txtCurrentUrl.Location = new Point(110, 255);
txtCurrentUrl.Size = new Size(255, 20);
btnAddFavorite.Text = "Add";
btnRemoveFavorite.Text = "Remove";
btnCloseFavorites.Text = "Close";
txtCurrentUrl.Text = wbBrowser.Url.ToString();
btnAddFavorite.Click += new EventHandler(btnAddFavorite_Click);
btnRemoveFavorite.Click += new EventHandler(btnRemoveFavorite_Click);
frmFavorites.Load += new EventHandler(frmFavorites_Load);
btnCloseFavorites.Click += new EventHandler(btnCloseFavorites_Click);
lstFavorites.MouseDoubleClick += new MouseEventHandler(lstFavorites_MouseDoubleClick);
frmFavorites.Show();
}
public void btnCloseFavorites_Click(object sender, EventArgs e)
{
if (lstFavorites.Items.Count > 0)
{
using (StreamWriter writer = new System.IO.StreamWriter(#Application.StartupPath + "\\favorites.txt"))
{
for (int i = 0; i < lstFavorites.Items.Count; i++)
{
writer.WriteLine(lstFavorites.Items[i].ToString());
}
writer.Close();
}
}
frmFavorites.Hide();
}
public void btnAddFavorite_Click(object sender, EventArgs e)
{
string strFavoriteAddress = wbBrowser.Url.ToString();
if (!lstFavorites.Items.Contains(strFavoriteAddress))
{
lstFavorites.Items.Add(strFavoriteAddress);
MessageBox.Show("Favorite Added", "Message");
}
else if (lstFavorites.Items.Contains(strFavoriteAddress))
{
MessageBox.Show("This site already exists in your Favorites list!", "Error");
}
else
{
}
}
public void btnRemoveFavorite_Click(object sender, EventArgs e)
{
try
{
lstFavorites.Items.RemoveAt(lstFavorites.SelectedIndices[0]);
}
catch
{
MessageBox.Show("You need to select an item", "Error");
}
}
public void frmFavorites_Load(object sender, EventArgs e)
{
try
{
using (StreamReader reader = new System.IO.StreamReader(#Application.StartupPath + "\\favorites.txt"))
{
while (!reader.EndOfStream)
{
for (int i = 0; i < 4; i++)
{
string strListItem = reader.ReadLine();
if (!String.IsNullOrEmpty(strListItem))
{
lstFavorites.Items.Add(strListItem);
}
}
}
reader.Close();
}
}
catch
{
MessageBox.Show("An error has occured", "Error");
}
}
private void lstFavorites_MouseDoubleClick(object sender, MouseEventArgs e)
{
string strSelectedAddress = lstFavorites.Text.ToString();
cmbAddress.Text = strSelectedAddress;
wbBrowser.Navigate(strSelectedAddress);
frmFavorites.Hide();
}

objects in datagridview

Im adding objects to a datagridview ( only one kind) through a list
ej.
List<Material> mater = new List<Material>();
DataGridView dgvMAterial = new DataGridView();
dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
dgvMaterial.DataSource = mater;
But every time I click over the datagrid I get an indexoutofrangeexeption.
Can somone tell me why?
thanks
here is my whole code for the form
public partial class inicio : Form
{
private string ConnectionString = "Data Source=localhost\\sqlexpress;Initial Catalog=data.mdf;Integrated Security=SSPI;";
//private string ConnectionString = "Server=.\\SQLExpress;AttachDbFilename=|DataDirectory|\\data\\data_data.mdf.mdf; Database=data.mdf;Trusted_Connection=Yes;";
private ISessionFactory sessionFactory;
List<Material> mater = new List<Material>();
List<Salarios> salar = new List<Salarios>();
IBindingList mind = new BindingList<Salarios>();
Productos prod;
public inicio()
{
InitializeComponent();
sessionFactory = nhn.BusinessObjects.Initialize.CreateSessionFactory(ConnectionString);
dgvMaterial.DataSource = mater;
}
private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmMaterial material = new costeos.Catalogos.frmMaterial(ConnectionString);
material.ShowDialog(this);
material.Dispose();
}
private void salariosToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmSalarios salarios = new costeos.Catalogos.frmSalarios(ConnectionString);
salarios.ShowDialog(this);
salarios.Dispose();
}
private void agregarToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmAddRemuneraciones rem = new costeos.Catalogos.frmAddRemuneraciones(ConnectionString);
rem.ShowDialog(this);
rem.Dispose();
}
private void agregarToolStripMenuItem1_Click(object sender, EventArgs e)
{
Catalogos.frmAddAdmin adm = new costeos.Catalogos.frmAddAdmin(ConnectionString);
adm.ShowDialog(this);
adm.Dispose();
}
private void agregarToolStripMenuItem2_Click(object sender, EventArgs e)
{
Catalogos.frmAddInsumosInd insumos = new costeos.Catalogos.frmAddInsumosInd(ConnectionString);
insumos.ShowDialog(this);
insumos.Dispose();
}
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void inicio_Load(object sender, EventArgs e)
{
LlenaCampos();
}
private void LlenaCampos()
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var mat = session.CreateCriteria(typeof(Material))
.List<Material>();
var sal = session.CreateCriteria(typeof(Salarios))
.List<Salarios>();
transaction.Commit();
cmbMaterial.DataSource = mat;
cmbMaterial.DisplayMember = "Nombre";
cmbSalarios.DataSource = sal;
cmbSalarios.DisplayMember = "Nombre";
cmbMIndirecta.DataSource = sal;
cmbMIndirecta.DisplayMember = "Nombre";
}
}
}
private void btnAddMaterial_Click(object sender, EventArgs e)
{
materialBindingSource.DataSource = null;
//dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
//dgvMaterial.DataSource = mater;
dgvMaterial.DataSource = materialBindingSource;
materialBindingSource.DataSource = mater;
materialBindingSource.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{
dgvSalarios.DataSource = null;
salar.Add((Salarios)cmbSalarios.SelectedValue);
dgvSalarios.DataSource = salar;
}
private void button3_Click(object sender, EventArgs e)
{
dgvMIndirecta.DataSource = null;
mind.Add((Salarios)cmbMIndirecta.SelectedValue);
dgvMIndirecta.DataSource = mind;
}
private void button1_Click(object sender, EventArgs e)
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
if (prod == null)
{
prod = new Productos { CargasTurno = float.Parse(txtCargasTurno.Text), CavidadesMolde = int.Parse(txtCavidadesMolde.Text), Clave = txtClave.Text, Comentarios = txtComentarios.Text, MezclasTurno = float.Parse(txtMezclasTurno.Text), Moldes = int.Parse(txtMoldes.Text), Nombre = txtNombre.Text, Peso = float.Parse(txtPesoTotal.Text), TotalPza = int.Parse(txtPzasTotales.Text), Turnos = int.Parse(txtTurnos.Text) };
session.Save(prod);
transaction.Commit();
}
foreach (DataGridViewRow dr in dgvMaterial.Rows)
{
Material m = dr.DataBoundItem as Material;
m.Materiales
PMaterial mat = new PMaterial { Material = dr.DataBoundItem as Material, Cantidad = float.Parse(dr.Cells["Cantidad"].Value.ToString()), Fecha = DateTime.Now, Producto = prod };
session.Save(mat);
}
transaction.Commit();
session.Close();
}
}
}
}
}
That's probably not DGV problem, but with this combo box. Show us the code that fills combo box and sets its properties.
If you are casting to Material class you should probably use SelectedItem instead of SelectedValue. (unless you exactly know what you're doing)
I would guess that you have an event-handler that isn't happy. What exactly does the message say?
You might also be having problems if you are adding the same Material instance to the list multiple times; since IndexOf will only find the first occurrence. This line makes me very suspicious:
mater.Add((Material)cmbMaterial.SelectedValue);
since it could potentially (on consecutive clicks / etc) do exactly this.
Note: if you used BindingList<T> instead all you'd have to doo is Add(...) - no resetting required:
field:
BindingList<Material> mater = new BindingList<Material>();
init grid:
dgvMaterial.DataSource = mater;
add item:
mater.Add(newInstance);
If you assign data source to the DGV you should check element count - if zero then assign null. I don't know why this is the way it is, but I'm doing it in all my forms.
//I'm still analysing the rest of the code

Categories

Resources