input textbox into array - c#

I want to create a textbox for my string input, and then separate it into an array if the input has ".". For example:
The answer lies in machine translation. The best machine translation technology cannot always provide translations tailored to a site or users like a human. Simply copy and paste a code snippet anywhere.
In that case, that input will consist of 3 arrays.
Please take a look at the following code from Microsoft. I want to change the hard code from the input using the textbox. Then pass each array to be translated.
class TranslateArraySample
{
public static async Task Run(string authToken)
{
var from = "en";
var to = "es";
** var translateArraySourceTexts = new []
{
"The answer lies in machine translation.",
"the best machine translation technology cannot always provide translations tailored to a site or users like a human ",
"Simply copy and paste a code snippet anywhere "
};
var uri = "https://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
var body = "<TranslateArrayRequest>" +
"<AppId />" +
"<From>{0}</From>" +
"<Options>" +
" <Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">{1}</ContentType>" +
"<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"</Options>" +
"<Texts>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{2}</string>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{3}</string>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{4}</string>" +
"</Texts>" +
"<To>{5}</To>" +
"</TranslateArrayRequest>";
string requestBody = string.Format(body, from, "text/plain", translateArraySourceTexts[0], translateArraySourceTexts[1], translateArraySourceTexts[2], to);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(uri);
request.Content = new StringContent(requestBody, Encoding.UTF8, "text/xml");
request.Headers.Add("Authorization", authToken);
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
switch (response.StatusCode)
{
case HttpStatusCode.OK:
Console.WriteLine("Request status is OK. Result of translate array method is:");
var doc = XDocument.Parse(responseBody);
var ns = XNamespace.Get("http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2");
var sourceTextCounter = 0;
foreach (XElement xe in doc.Descendants(ns + "TranslateArrayResponse"))
{
foreach (var node in xe.Elements(ns + "TranslatedText"))
{
** Console.WriteLine("\n\nSource text: {0}\nTranslated Text: {1}", translateArraySourceTexts[sourceTextCounter], node.Value);
}
sourceTextCounter++;
}
break;
default:
Console.WriteLine("Request status code is: {0}.", response.StatusCode);
Console.WriteLine("Request error message: {0}.", responseBody);
break;
}
}
}
}

use (StringObject).Split("<separator>")
sample code:
var translateArraySourceTexts = new[]
{
"The answer lies in machine translation.",
"the best machine translation technology cannot always provide translations tailored to a site or users like a human ",
"Simply copy and paste a code snippet anywhere "
};
var array = string.Join(",",translateArraySourceTexts).Split('.');

Here is some example code. Replace string s, with your .Text from your textbox.
string s = #"Changing your development practice to introduce an automated testing strategy can revolutionise your deployments. If you approach the software release date with a sense of dread, this technique is for you.
Implementing a test-driven development strategy using tSQLt leads to robust, modular code that becomes a pleasure to work with. As more tests are created, trust builds that releases will provide beneficial new functionality with no negative side-effects.";
var translateArraySourceTexts = s.Split( Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries ).ToArray();

You need String.Split(charArray, stringSplitoptions) to get only three strings in your resulting array.
in your example
string translatableString = "The answer lies in machine translation. The best
machine translation technology cannot always provide translations tailored to
a site or users like a human. Simply copy and paste a code snippet anywhere.";
string[] arr = translatableString.Split(new char[] { '.' },
StringSplitOptions.RemoveEmptyEntries);
you would get a array of 4 strings with
translatableString.Split('.') because one will be empty. This is why I provided the overloaded method.

Related

MWS Financial Services client library returning a null exception

I made a very simple console application which will hit MWS service and return XML document containing list of financial events. As it starts, an exception hits at line 14 'client.ListFinancialEvents(request)' and it just show null and no other information as to why its not working.
string accessKey = "AccessKey";
string secretKey = "SecretKey";
string appName = "AppName";
string appVersion = "1.0";
string serviceURL = "http://mws.amazonservices.com/Finances/2015-05-01/";
try
{
MWSFinancesServiceConfig config = new MWSFinancesServiceConfig();
config.ServiceURL = serviceURL;
MWSFinancesServiceClient client = new MWSFinancesServiceClient(accessKey, secretKey, appName, appVersion, config);
ListFinancialEventsRequest request = new ListFinancialEventsRequest();
request.SellerId = "SellerID";
request.AmazonOrderId = "111-111111111-111111111";
ListFinancialEventsResponse response = client.ListFinancialEvents(request);
Console.WriteLine("Response:");
ResponseHeaderMetadata rhmd = response.ResponseHeaderMetadata;
Console.WriteLine("RequestId: " + rhmd.RequestId);
Console.WriteLine("Timestamp: " + rhmd.Timestamp);
string responseXml = response.ToXML();
Console.WriteLine(response.ResponseHeaderMetadata);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.ReadLine();
The DLLs used as reference were downloaded from here. I have already tried MWS Scratchpad and values are working fine. What could be the possible issues due to which this exception occurred and how to solve this issue?
I am posting an answer to my own question in case someone faces similar issue in the future.
I was making a very stupid mistake and it took me a week to figure it out. In service URL, instead of "http://..." it should be "https://..." and it starts working perfectly. It return complete XML as response in 'responseXml' variable.

how to Add a formula in excel cell using Microsoft graph API?

I am trying to add a content to a cell in Excel using Microsoft Graph's Excel API. I am able to add content using PATCH method but when I try to add a formula, it does not behave like a formula. If I pass something like 'formulas': '=sum(2+2)', it does not behave as it should.
Result i am getting is in snip:
Is this doable?
here is my code:
//Set up workbook and worksheet endpoints
var workbookEndpoint = "https://graph.microsoft.com/v1.0/me/drive/items/" +
fileId + "/workbook";
var worksheetsEndpoint = workbookEndpoint + "/worksheets";
var patchMethod = new HttpMethod("PATCH");
var summaryTableRowJson = "{" +
"'formulas': '=sum(2+2)'" +
"}";
var colNamePatchBody = new StringContent(summaryTableRowJson);
colNamePatchBody.Headers.Clear();
colNamePatchBody.Headers.Add("Content-Type", "application/json");
var colNameRequestMessage = new HttpRequestMessage(patchMethod, worksheetsEndpoint +
"('" + worksheetName + "')/range(address='Sheet1!B2')")
{
Content = colNamePatchBody
};
var colNameResponseMessage = await client.SendAsync(colNameRequestMessage);
You need to pass this in via the formulas rather than the values property:
{
"formulas" : "=sum(2+2)"
}
You should also consider using the Microsoft Graph Client Library for .NET instead of rolling your own raw HTTP calls. It will save you a ton of headaches over time. It also results in much cleaner code:
await graphClient.Me
.Drive
.Items["id"]
.Workbook
.Worksheets["Sheet1"]
.Range("C12")
.Request()
.PatchAsync(new WorkbookRange()
{
Formulas = JArray.Parse(#"[['=2.2']]")
});

C# get string from txt, then copy into new txt

I have a tiny problem with my idea ;)
I want to read som emails from gmail (using Mailkit) and save them into multiple files.
Ok you may think "wtf is going on",... I want to extract the orders via mail and save them as single files for sort off log/protocoll. I think I can handle it better
Properties.Settings.Default.status = "Status: Online";
using (var client = new ImapClient())
{
client.Connect(Properties.Settings.Default.Server, Properties.Settings.Default.Port, true);
client.Authenticate(Properties.Settings.Default.Email, Properties.Settings.Default.Passwort);
client.Inbox.Open(FolderAccess.ReadWrite);
for (int i = 0; i < client.Inbox.Count; i++)
{
var message = client.Inbox.GetMessage(i);
var html = message.HtmlBody;
var text = message.TextBody;
var header = message.Subject + " " + message.From + " " + message.Date + " " + message.MessageId;
File.AppendAllLines(Properties.Settings.Default.pathmail + #"\" + "MailMain.txt", new[] { message.HtmlBody });
string line = File.ReadLines(Properties.Settings.Default.pathmail + #"\" + "MailMain.txt").Skip(i).Take(1).First();
dataGridView1.Rows.Add(message.Subject, message.From, message.Date, message.MessageId);
The MailMain.txt contains every email in gmail line after line, so it canĀ“t be difficult to filter them nicely.
Problem 1:
I need to get (e.g) the first line of the txt file, then create new txt with specific name (Properties.Settings.Default.pathmail). Line after line
For example: copy Line#1 from MailMain.txt to Thisisyourfirstline.txt
copy Line#2 from MailMain.txt to Thisisyoursecondline.txt.
Problem 2:
The body of the email contains a bit of HTML ( < /b>). I need to filter that all. Any suggestions ?
greeetings
I would use the StreamReader and StreamWriter to get and write things line by line. And String.Replace to strip the html tags.

How to extract first segment out of URI using Uri class

I am using Uri class for application development and needs the first segment of user-entered uri that either it contains http:// or http:// or ftp:// etc.
If not so,i have to hardcode to add to it.
I have already searched for it using googling and stackoverflowing but they didn't showed the precise requirement for me.
string path,downloadURL;
path = this.savePath.Text;
downloadURL = this.downloadURL.Text;
// i have done this but it didn't check if already existing .
downloadURL = "http://" + downloadURL;
Uri tmp = new Uri(downloadURL);
//extracts the last element
string EndPathFileName = tmp.Segments.Last();
// something like this but it returns only '/'.
//string StartPathFileName = tmp.Segments.First();
//Console.WriteLine(StartPathFileName);
Any suggestions?
Well there are a few options depending on what behavior you want...
You could just check if it contains :// which might be enough for what you want:
if(!downloadURL.Contains("://"))
downloadURL = "http://" + downloadURL;
Note that this would allow things such as "rubbish://www.example.com"
If you wanted to be a bit more cautious, you could check if the string starts with one of your predetermined values. For example:
if(!downloadURL.StartsWith("http://") && !downloadURL.StartsWith("https://") && !downloadURL.StartsWith("ftp://"))
downloadURL = "http://" + downloadURL;
Though this would mean that "rubbish://www.example.com" would become "http://rubbish://www.example.com".
You could go for a mix of both options, but keep in mind it can become very difficult to cope with all kinds of user input.
One final suggestion, which is even more robust, might be as follows:
string[] approvedSchemes = new string[] { "http", "https", "ftp" };
string userScheme = "";
if(downloadURL.Contains("://"))
{
// Get the first scheme defined, we will use this if it is in the approved list.
userScheme = downloadURL.Substring(0, downloadURL.IndexOf("://"));
// To cater for multiple :// remove all of them
downloadURL = downloadURL.Substring(downloadURL.LastIndexOf("://") + 3);
}
// Check if the user defined scheme is in the approved list, if not then set to http.
if(Array.IndexOf(approvedSchemes, userScheme.ToLowerInvariant()) > -1)
downloadURL = userScheme + "://" + downloadURL;
else
downloadURL = "http://" + downloadURL;
Here is a working example
You need to use Uri.Scheme Property
Uri baseUri = new Uri("http://www.contoso.com/");
Console.WriteLine(baseUri.Scheme); //http
Uri anotherUri = new Uri("https://www.contoso.com/");
Console.WriteLine(anotherUri.Scheme); //https

String that came from Request.Url.ToString() misteriously changes to another string when manipulating/comparing the first characters

I'm aware that there are easier ways to do this and believe me, I've tried them. I'm of course open to any suggestions =). You don't need to read the whole code, just the part that says where the problem lies. Also, I'm debbugging perl style so you guys can see. Oh and did I mention that on my development environment everything works as intended?
Here's the code:
string GetPortalAlias()
{
String myURL2 = Request.Url.ToString();
URLLabel.Text = "Original Request.Url.ToString() returned: \"" + myURL2 + "\"";
string myURL = string.Copy(myURL2);
URLLabel.Text = "Copying it to myURL, it's now: \"" + myURL + "\"";
myURL = myURL.ToLower().Trim();
URLLabel.Text += "<br>Trimming and ToLower myURL.<br>The new url is \"" + myURL + "\"" + "<br>";
myURL = myURL.Replace(":80", "");
URLLabel.Text += "Replacing the \":80\".<br> The new url is\"" + myURL + "\"<br>";
//***HERE LIES THE PROBLEM***
myURL = myURL.Replace("http://", "");
URLLabel.Text += "Replacing the \"http://\".<br> The new url is\"" + myURL + "\"<br>";
//***PROBLEM ENDS***
myURL = myURL.Remove(myURL.IndexOf("/"));
URLLabel.Text += "Removing everything after the \"/\"." + "<br> The new url is \"" + myURL + "\"<br>";
URLLabel.Text += "<br>GetPortalAlias Returning \"" + myURL + "\"";
return myURL;
}
Believe it or not, the output produced in the webpage is this:
Copying it to myURL, it's now: "http://sar.smg.com.ar/Default.aspx?TabID=912"
Trimming and ToLower myURL.
The new url is "http://sar.smg.com.ar/default.aspx?tabid=912"
Replacing the ":80".
The new url is"http://sar.smg.com.ar/default.aspx?tabid=912"
Replacing the "http://".
The new url is"intranetqa/default.aspx?tabid=912"
Removing everything after the "/".
The new url is "intranetqa"
GetPortalAlias Returning "intranetqa"
So... for some reason whenever it reaches the replace section it mysteriously mutates to start with "intranetqa" instead of "sar.smg.com.ar". "intranetqa" is our default hostname. CHANGING OR TAKING AWAY ANY CHARACTER OF HTTP:// IN ANY WAY MUTATES THE STRING.
I do a string.copy because I'm aware that if two strings are equal the compiler stores them in the same place therefore I wanted to prevent errors. Taking those lines away and use Request.Url.ToString() tomyURL directly does nothing at all. They were just a test to see if that worked.
Here's a list of the things I've tried:
All combinations of string / String, none worked.
I've tried Request.Host.Url and it just gave me "intranetqa".
I've used Request.Url.AbsoluteUri and that's why I have the replace
:80 line.
USING THE .tochararray FUNCTION GIVES ME BACK THE INTRANETQA THING
myURL = myURL.Substring(6) gives back the intranetqa thing.
string.Contains("sar.smg.com.ar") gives back false.
I believe the trick lies around here:
Uri uriAddress1 = Request.Url; and "The parts are <br>" + "Part 1: " + uriAddress1.Segments[0] + "<br>Part 2: " + uriAddress1.Segments[1]; Gives Part1 : "/" and Part 2: "Default.aspx". Trying to access part 3 (index 2) gives an exception.
The request.url does not have the first part, but when I call the ToString() method, it does have like a "fake" first part
Between your browser and the server are a reverse proxy and an output re-writer. These may be the same component, or separate components.
The URL your server actually sees is always of the form http://intranetqa/default.aspx?tabid=912 (after the reverse proxy/URL re-writer has intercepted the request).
The output your server produces is actually like:
Copying it to myURL, it's now: "http://intranetqa/Default.aspx?TabID=912"
Trimming and ToLower myURL.
The new url is "http://intranetqa/default.aspx?tabid=912"
Replacing the ":80".
The new url is"http://intranetqa/default.aspx?tabid=912"
Replacing the "http://".
The new url is"intranetqa/default.aspx?tabid=912"
Removing everything after the "/".
The new url is "intranetqa"
GetPortalAlias Returning "intranetqa"
The output re-writer is inspecting the output from your server and doing a replace of http://intranetqa with http://sar.smg.com.ar. Once you strip the http:// off of the front of these strings, it's no longer a match and so replacement no longer occurs.
If you want to know what the original requesting URL/host are, hopefully the reverse proxy either is, or can be configured to, adding an extra header to the request with the original URL.
You can try something like this
Uri uriAddress1 = new Uri("http://www.contoso.com/title/index.htm");
Console.WriteLine("The parts are {0}, {1}, {2}", uriAddress1.Segments[0], uriAddress1.Segments[1], uriAddress1.Segments[2]);
Uri.Segments Property
This is better way to handle URIs and their segments.
Try to use this property instead:
String myURL2 = Request.Url.AbsoluteUri;
Here is an Extension method that I use to pull the SiteRootPath. You should be able to easily adjust it however you need it. You will need access to the HttpContext for what I currently have below, however, you don't sound like you need that.
using System;
using System.Web;
namespace FlixPicks.Web.Extensions
{
public static class HttpContextExtensions
{
public static string SiteRootPath(this HttpContext context)
{
if (context == null || context.Request == null) { return null; }
return context.Request.Url.SiteRootPath(context.Request.ApplicationPath);
}
public static string SiteRootPath(this HttpContextBase context)
{
return context.Request.Url.SiteRootPath(context.Request.ApplicationPath);
}
private static string SiteRootPath(this Uri url, string applicationPath)
{
if (url == null) { return null; }
// Formatting the fully qualified website url/name.
string appPath = string.Format(
"{0}://{1}{2}{3}",
url.Scheme,
url.Host,
url.Port == 80 ? string.Empty : ":" + url.Port,
applicationPath);
// Remove ending slash(es) if one or more exists to consistently return
// a path without an ending slash. Could have just as well choosen to always include an ending slash.
while (appPath.EndsWith("/") || appPath.EndsWith("\\"))
{
appPath = appPath.Substring(0, appPath.Length - 1);
}
return appPath;
}
}
}
Good luck,
Tom
Don't you want to achieve part of what is done here?
Something like
string host = Request.Url.IsDefaultPort ?
Request.Url.Host :
Request.Url.Authority;
If you want to persist with the old method change it like this
string GetPortalAlias()
{
var rawUrl = Request.Url.ToString();
var lowerTrimmedUrl = rawUrl.ToLower().Trim();
var withoutPortUrl = lowerTrimmedUrl.Replace(":80", "");
var withoutProtocolUrl = withoutPortUrl.Replace("http://", "");
var justHostUrl = withoutProtocolUrl.Remove(myURL.IndexOf("/"));
var evolution = new StringBuilder();
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(rawUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(lowerTrimmedUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(withoutPortUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(withoutProtocolUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(justHostUrl));
URLLabel.Text = evolution.ToString();
return justHostUrl;
}
So you can see whats going on.

Categories