Why this google translate code isnt working? - c#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TranslateText("hi", "German");
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static string TranslateText(string input, string languagePair)
{
return TranslateText(input, languagePair, System.Text.Encoding.UTF7);
}
/// <summary>
/// Translate Text using Google Translate
/// </summary>
/// <param name="input">The string you want translated</param>
/// <param name="languagePair">2 letter Language Pair, delimited by "|".
/// e.g. "en|da" language pair means to translate from English to Danish</param>
/// <param name="encoding">The encoding.</param>
/// <returns>Translated to String</returns>
public static string TranslateText(string input, string languagePair, Encoding encoding)
{
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
string result = String.Empty;
using (WebClient webClient = new WebClient())
{
webClient.Encoding = encoding;
result = webClient.DownloadString(url);
}
Match m = Regex.Match(result, "(?<=<div id=result_box dir=\"ltr\">)(.*?)(?=</div>)");
if (m.Success)
result = m.Value;
MessageBox.Show(result);
return result;
}
}
}
I added in the constructor the line:
TranslateText("hi", "German");
And in the bottom i added:
MessageBox.Show(result);
I wanted for the test to translate the word "hi" to German
But the result im getting and in the messagebox is a very long text wich is containing all the google website.
I tried to go manualy to the web site in the string url address and its working im getting to the google translate website.
I dont understand why it dosent work.
I want later to put instead "hi" some text from a text file.
I tried ot use breakpoint and found that this part the Success is all the time return false dont know why:
if (m.Success)
result = m.Value;

I think you are not getting the translated text or value in your html result from your code and also from Google.
Reason:
If you execute this through the browser, it is not translating to the language you expect, example:
http://www.google.com/translate_t?hl=en&ie=UTF8&text=hi&langpair=de
I used langpair=de or langpair=German and doesn't work, it shows me always "hi" as my initial text and not "hallo" (text in german).
Well, just to answer your question to get the text, do the following:
Add this method to your class:
public static string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "";
}
}
Change the following in your "TranslateText" method:
//Match m = Regex.Match(result, "(?<=<div id=result_box dir=\"ltr\">)(.*?)(?=</div>)");
string text = getBetween(result, "<span id=result_box class=\"short_text\">", "</span>");
//if (m.Success)
// result = m.Value;
return text;
Now execute your code like this:
// this will return empty ("") if no text found.
// or any problem happens (like lose your internet connection)
string translatedText = TranslateText("hi", "German");
Console.Write(translatedText);
At this point, if you get the translated text from google, it will be retrieved in your app.
Recommendations:
Use a console application and no windows forms, it will be faster.
Warning:
"Google is not a free translating tool. What you do is terms violation".
Hope this helps :-)

Would be easier, and more robust to parse the html using something other than a regex. You can then search the parsed HTML tree for the result and extract it from there.
See What is the best way to parse html in C#?

Related

String interpolation not working in C# class

I'm using String interpolation in the code behind, and now I need to take part of it to a class.
when I do it, I get error "CS1056: Unexpected character '$'"
even a very simple code gives the error right on running (not on build):
string MailSubject = $"this is your score: {userScore}";
this part of code is part of the FaceClass.CS file
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
namespace ns.App_Code
{
public class FakeClass
{
public static void Check_Next_In_Line(int score)
{
int temp = Fake2Class.GetData();
if (temp == 0)
{
string MailSubject = "";
string MailBody = "";
MailBody = $"Your score: {score}";
/*
mail send function
*/
}
}
}
}
I'm using .NET Framework 4.8
String Interpolation works for me in a aspx code behind but not in a method within a class. If I want to refactor a part of code becuase it is needed more than once - it won't work
Hi an alternative solution to what you are looking for may be would be to use string format. Something like below
int userscore;
string MailSubject = string.Format("this is your score: {0}", userscore);

Extract certain parts from XML string

I have a windows form in C# that does a httpclient get request. And this is the response in XML format
> <Result><Success>true</Success><Token>MYTOKENHERE</Token><TokenExpirationDate null="1"
> /><UserName>********</UserName><PersonCode>442078</PersonCode><LoginStatusMessage>LoginOk</LoginStatusMessage></Result>
I want to set the text of a text box to what is inbetween the <Token></Token> Tags
What is the best approach to do this
Thanks
This is my current Form1.cs code
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 System.Net.Http;
using System.Xml.Serialization;
namespace EBS_Token_Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
HttpClient Client = new HttpClient();
Client.BaseAddress = new Uri("PRIVATE_URL");
string Username = username.Text;
string Password = password.Text;
string CredentialsString = $"{Username}:{Password}";
byte[] CredentialsStringByes = System.Text.Encoding.UTF8.GetBytes(CredentialsString);
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("basic", Convert.ToBase64String(CredentialsStringByes));
try
{
var Response = Client.GetAsync("Rest/Authentication").Result;
if (!Response.IsSuccessStatusCode)
{
// Something went wrong, is error.
// Put a breakpoint on the line below and we can figure out why.
string x = "";
}
string ServerResponse = Response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
return;
}
}
If i set the value of the textbox to ServerResponse it has the full xml document. I need to extract just the .
Usually I'd use XmlSerializer for something like this, but if you really just need this one value, you may want to try XElement:
var root = XElement.Parse(yourResponseString);
var value = root.Element("Token")?.Value;
XElement is great for traversing, reading and manipulating XML.
XPath works for this, although some might consider overkill. The XPath expression /Result/Token/Text() does exactly what it looks like it will.
using System.Xml;
using System.Xml.XPath;
string Incoming_XML = #"<Result><Success>true</Success><Token>MYTOKENHERE</Token><TokenExpirationDate null=""1"" /><UserName>********</UserName><PersonCode>442078</PersonCode><LoginStatusMessage>LoginOk</LoginStatusMessage></Result>";
XPathDocument xPathDoc = null;
using (StringReader sr = new StringReader(Incoming_XML))
{
xPathDoc = new XPathDocument(sr);
XPathNavigator xPathNav = xPathDoc.CreateNavigator();
string Result = xPathNav.SelectSingleNode("/Result/Token/text()").Value;
Console.WriteLine($"Token is: {Result}");
}
below sample code may not the best but it is simple to understand and will do the work.
// Define a regular expression pattern
string Regex_syntax = #"<Token>[\s\S]*?</Token>";
Regex rx = new Regex(Regex_syntax,RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Define a RAW data string to process , in your case will be http response result
string inputtext = #"<Result><Success>true</Success><Token>MYTOKENHERE</Token><TokenExpirationDate";
// Find matches.
MatchCollection matches = rx.Matches(inputtext);
// clease the uneeded string
string cleanseString = matches[0].ToString().Replace(#"<Token>", "");
cleanseString = cleanseString.Replace(#"</Token>", "");
// This will print value in between the token tag
Console.WriteLine("require output = " + cleanseString);

Can I use WebUtility.HtmlDecode to decode XML?

I have an XML-encoded attribute value. This is actually from a processing instruction. So the original data looks something like this:
<root><?pi key="value" data="<foo attr="bar">Hello world</foo>" ?></root>
I can parse it like this:
using System;
using System.Linq;
using System.Xml.Linq;
public class Program
{
private const string RawData = #"<root><?pi key=""value"" data=""<foo attr="bar">Hello world</foo>"" ?></root>";
public static void Main()
{
XDocument doc = GetXDocumentFromProcessingInstruction();
IEnumerable<XElement> fooElements = doc.Descendants("foo");
// ...
}
private static XProcessingInstruction LoadProcessingInstruction()
{
XDocument doc = XDocument.Parse(rawData);
return doc
.DescendantNodes()
.OfType<XProcessingInstruction>()
.First();
}
private static XDocument GetXDocumentFromProcessingInstruction()
{
XProcessingInstruction processingInstruction = LoadProcessingInstruction();
// QUESTION:
// Can there ever be a situation where HtmlDecode wouldn't decode the XML correctly?
string decodedXml = WebUtility.HtmlDecode(processingInstruction.Data);
// This works well, but it contains the attributes of the processing
// instruction as text.
string dummyXml = $"<dummy>{xml}</dummy>";
return XDocument.Parse(dummyXml);
}
This works absolutely fine, as far as I can tell.
But I am wondering if there might be some edge cases where it may fail, because of differences in how data would be encoded in XML vs. HTML.
Anybody have some more insight?
Edit:
Sorry, I made some incorrect assumptions about XProcessingInstruction.Data, but the code above was still working fine, so my question stands.
I have nonetheless rewritten my code and wrapped everything in an XElement, which (of course) removed the issue altogether:
private static XDocument GetXDocumentFromProcessingInstruction2()
{
XProcessingInstruction processingInstruction = LoadProcessingInstruction();
string encodedXml = string.Format("<dummy {0} />", processingInstruction.Data);
XElement element = XElement.Parse(encodedXml);
string parsedXml = element.Attribute("data").Value;
return XDocument.Parse(parsedXml);
}
So this does exactly what I need. But since WebUtility.HtmlDecode worked sufficiently well, I would still like to know if there could have been a situation where the first approach could have failed.
Removing the question marks and adding a forward slash at end of your input I got this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "<pi data=\"<foo attr="bar">Hello world</foo>\" />";
XElement pi = XElement.Parse(input);
string data = (string)pi.Attribute("data");
XElement foo = XElement.Parse(data);
string attr = (string)foo.Attribute("attr");
string innertext = (string)foo;
}
}
}

windows phone 8.1 html taqs rss app

I want to ask is there any way to remove the html taq from Rss Reader on windows phone 8.1 I'm working on app that show the topics on any site using Rss on the smartphone " windows phone" but I have this problem can I remove the html taqs
this pic will show u what I mean ??
What control is this? Have you consider using a Web Browser control? Or, if you really need to display it in a TextBox (assuming it's a TextBox), you can convert your HTML into a XAML FlowDocument, using this tutorial.
I follow the same tutorial for create my rss reader.
So, for remove the html code you need create a class to trimmer the description:
Create a class named RssTextTrimmer.cs with the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Text.RegularExpressions;
using Windows.UI.Xaml.Data;
using System.Net;
namespace VEJA_Notícias
{
public class RssTextTrimmer : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null) return null;
int maxLength = 200;
int strLength = 0;
string fixedString = "";
// Remove HTML tags.
fixedString = Regex.Replace(value.ToString(), "<[^>]+>", string.Empty);
// Remove newline characters.
fixedString = fixedString.Replace("\r", "").Replace("\n", "");
// Remove encoded HTML characters.
fixedString = WebUtility.HtmlDecode(fixedString);
strLength = fixedString.ToString().Length;
// Some feed management tools include an image tag in the Description field of an RSS feed,
// so even if the Description field (and thus, the Summary property) is not populated, it could still contain HTML.
// Due to this, after we strip tags from the string, we should return null if there is nothing left in the resulting string.
if (strLength == 0)
{
return null;
}
// Truncate the text if it is too long.
else if (strLength >= maxLength)
{
fixedString = fixedString.Substring(0, maxLength);
// Unless we take the next step, the string truncation could occur in the middle of a word.
// Using LastIndexOf we can find the last space character in the string and truncate there.
fixedString = fixedString.Substring(0, fixedString.LastIndexOf(" "));
}
fixedString += "...";
return fixedString;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
And in your MainPage.xaml you need add the code:
<Page.Resources>
<local:RssTextTrimmer x:Key="RssTextTrimmer" />
</Page.Resources>
To access the method of RssTextTrimmer class in the xaml textblock you need to do so:
<TextBlock x:Name="textTitulo" Text="{Binding title, Converter={StaticResource RssTextTrimmer}}"/>

C# write multi lines to cs file

I googled and found the solution at MSDN.
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
How to extend the lines to complex content which including some natural C# code lines.
eg. I want to write the information below to my test.cs file.
Why?
I am parsing a XML schema with C# Console Application. And i want to generate the Console Result to a .cs file during the compiler time.
using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
{
public class CCODEData
{
public int iCodeId;
public string sCode;
public CODEDType cType;
public int iOccures;
}
[Description("CodeType for XML schema.")]
public enum CODEDType
{
cString = 1,
cInt = 2,
cBoolean = 3,
}
thank you.
If your source code is hardcoded as in your sample, you could use a C# literal string:
string lines =
#"using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
..."
Anyway in such cases it is a better idea (more readable and maintainable) to have the whole text contents into a text file as an embedded resource in your assembly, then read it using GetManifestResourceStream.
(I'm assuming you're trying to build up the result programmatically - if you genuinely have hard-coded data, you could use Konamiman's approach; I agree that using an embedded resource file would be better than a huge verbatim string literal.)
In your case I would suggest not trying to build up the whole file into a single string. Instead, use WriteLine repeatedly:
using (TextWriter writer = File.CreateText("foo.cs"))
{
foreach (string usingDirective in usingDirectives)
{
writer.WriteLine("using {0};", usingDirective);
}
writer.WriteLine();
writer.WriteLine("namespace {0}", targetNamespace);
// etc
}
You may wish to write a helper type to allow simple indentation etc.
If these suggestions don't help, please give more details of your situation.
I know an answer has already been accepted but why not use an XSLT applied to the XML instead? this would mean that you could easily generate c#, vb.net, .net without having to recompile the app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FileHandling
{
class Class1
{
static void Main()
{
Console.WriteLine("Enter data");
ConsoleKeyInfo k;
//Console.WriteLine(k.KeyChar + ", " + k.Key + ", " + k.Modifiers );
string str="";
char ch;
while (true)
{
k = Console.ReadKey();
if ((k.Modifiers == ConsoleModifiers.Control) && (k.KeyChar == 23))
{
Console.WriteLine("\b");
break;
}
if (k.Key == ConsoleKey.Enter)
{
Console.WriteLine("");
str += "\n";
}
ch = Convert.ToChar(k.KeyChar);
str += ch.ToString();
}
Console.WriteLine(str);
Console.Read();
}
}
}

Categories

Resources