So what I'm trying to do is print outputs to a textbox but what's happening is it's always using the last textbox2.text it finds because I assume that each time I print it out it overrides the last output. I'm looking for some sort of work around
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Web;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ProgrammingProject
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btn_getinfo_Click(object sender, RoutedEventArgs e)
{
string UserInput = "76561198056932916";
// string UserInput = textBox.Text;
ProfileSummary(UserInput);
}
public void ProfileSummary(string SteamID)
{
string SteamKey = "CensoredAPIKEY";
WebClient c = new WebClient();
var data = c.DownloadString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/" + "?key=" + SteamKey + "&steamids=" + SteamID);
//Console.WriteLine(data);
JObject o = JObject.Parse(data);
JArray players = (JArray)o["response"]["players"];
if (players.Count > 0)
{
int PrivacyLevel = (int)players[0]["communityvisibilitystate"];
string username = (string)players[0]["personaname"];
string ProUrl = (string)players[0]["profileurl"];
double LastLogOff = (double)players[0]["lastlogoff"];
int CurrentStatus = (int)players[0]["personastate"];
int GamePlaying = (int)players[0]["gameid"];
textBox2.Text = "your username is " + username + "\n";
textBox2.Text = "You last logged off on " + ConvertUnix(LastLogOff) + "\n";
if (PrivacyLevel == 3)
{
textBox2.Text = "This user's account is public";
}
else if (PrivacyLevel == 1)
{
textBox2.Text = "This user's account is private";
}
switch (CurrentStatus)
{
case 1:
textBox2.Text = "This user is offline";
break;
case 2:
textBox2.Text = "This User is online and playing";
break;
}
}
else
{
textBox2.Text = "You have entered the SteamID incorrectly";
}
Console.ReadLine(); // Don't remove you idiot
}
public static DateTime ConvertUnix(double unixTimeStamp)
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Local);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
return dtDateTime;
}
}
the output of this code will be the last textbox2.text so in this case it would be the switch statement. I know I haven't explained it the best but I just don't know why this is happening, Thanks
You should use textBox2.Text += "more text to be added to the text box" instead of textBox2.Text = "more text to be added to the text box"
The problem here is that by using textBox2.Text =, you're overwriting the value. Instead, if you want to add lines, use textBox2.Text += "myString";. This will append the string to the textbox instead of overwriting it.
you should use += operator after first equal.
textBox2.Text = "your username is " + username + "\n";
textBox2.Text += "You last logged off on " + ConvertUnix(LastLogOff) + "\n";
if (PrivacyLevel == 3)
{
textBox2.Text += "This user's account is public";
}
else if (PrivacyLevel == 1)
{
textBox2.Text += "This user's account is private";
}
switch (CurrentStatus)
{
case 1:
textBox2.Text += "This user is offline";
break;
case 2:
textBox2.Text += "This User is online and playing";
break;
}
}
else
{
textBox2.Text += "You have entered the SteamID incorrectly";
}
the answer is as they describe above but I would like to suggest that you use a
richtextbox since you have more than one message and it would be better if you display them in Separate lines to do so
richtextbox1.text="\r\n"+some string;
the "\r\n" is to go to new line and then insert the text in that new line
.
Related
I want to retrieve the data from a .vcf file. It is in vcf format.
I need the regular expression formula for each item of data mentioned below. I tried but could not make it work.
BEGIN:VCARD
VERSION:2.1
FN;CHARSET=utf-8:s James F ' Ernande.
ADR;WORK;X-EDIT=0;X-POS=280,43,54,269,0,0,0,0;CHARSET=utf-8:;;P.O. Box No: 570, P. C-112, Ruwi Muscat, Sultanate Ofoman;;;;
X-IS-TAKE-ADR;CHARSET=utf-8:23.62866567746918;58.26649072858852;
N;X-EDIT=0;X-POS=33,89,29,178;CHARSET=utf-8:s;James F ' Ernande. ;;;
EMAIL;WORK;X-EDIT=0;X-POS=116,59,26,237;CHARSET=utf-8:james#om.bluerhine.com
EMAIL;WORK;X-EDIT=0;X-POS=142,61,26,234;CHARSET=utf-8:oman#onn.bluerhine.com
EXCHANGEDATE:2019-06-16
EXCHANGEDATE:2019-06-16
AUTHOR:IntSig-iOS-iPhone
ORG;WORK;X-EDIT=0;X-POS=0,0,0,0,59,29,33,295,0,0,0,0;CHARSET=utf-8:;Business Development Manaus)r;
TEL;WORK;X-EDIT=0;X-POS=88,107,23,142;CHARSET=utf-8:+96897641700
TEL;WORK;X-EDIT=0;X-POS=332,133,28,182;CHARSET=utf-8:+96822022247
TEL;WORK;X-EDIT=0;X-POS=328,36,27,92;CHARSET=utf-8:24796647
END:VCARD
Code:
Regex regex = new Regex(#"(?<strElement>(FN)) (:(?<strFN>[^\r\n]*))", options);// For retrieving the First Name
Regex regex = new Regex(#"((?<strElement>(EMAIL)) (;*(?<strAttr>(HOME|WORK)))* (;(?<strPref>(PREF)))* (;[^:]*)* (:(?<strValue>[^\n\r]*)))");//for retrieving Email
I am not getting the exact regular expression formula required.
Here is a simple parser :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
namespace ConsoleApplication124
{
class Program
{
static void Main(string[] args)
{
string input =
"BEGIN:VCARD\n" +
"VERSION:2.1\n" +
"FN;CHARSET=utf-8:s James F ' Ernande.\n" +
"ADR;WORK;X-EDIT=0;X-POS=280,43,54,269,0,0,0,0;CHARSET=utf-8:;;P.O. Box No: 570, P. C-112, Ruwi Muscat, Sultanate Ofoman;;;;\n" +
"X-IS-TAKE-ADR;CHARSET=utf-8:23.62866567746918;58.26649072858852;\n" +
"N;X-EDIT=0;X-POS=33,89,29,178;CHARSET=utf-8:s;James F ' Ernande. ;;;\n" +
"EMAIL;WORK;X-EDIT=0;X-POS=116,59,26,237;CHARSET=utf-8:james#om.bluerhine.com\n" +
"EMAIL;WORK;X-EDIT=0;X-POS=142,61,26,234;CHARSET=utf-8:oman#onn.bluerhine.com\n" +
"EXCHANGEDATE:2019-06-16\n" +
"EXCHANGEDATE:2019-06-16\n" +
"AUTHOR:IntSig-iOS-iPhone\n" +
"ORG;WORK;X-EDIT=0;X-POS=0,0,0,0,59,29,33,295,0,0,0,0;CHARSET=utf-8:;Business Development Manaus)r;\n" +
"TEL;WORK;X-EDIT=0;X-POS=88,107,23,142;CHARSET=utf-8:+96897641700\n" +
"TEL;WORK;X-EDIT=0;X-POS=332,133,28,182;CHARSET=utf-8:+96822022247\n" +
"TEL;WORK;X-EDIT=0;X-POS=328,36,27,92;CHARSET=utf-8:24796647\n" +
"END:VCARD";
ParseVCF parseVCF = new ParseVCF(input);
}
}
public class ParseVCF
{
public string version { get; set; }
public List<string> data = new List<string>();
enum State
{
FIND_BEGIN,
GET_VERSION,
PROCESS_DATA,
FOUND_END
}
public ParseVCF(string input)
{
StringReader reader = new StringReader(input);
string line = "";
State state = State.FIND_BEGIN;
while(((line = reader.ReadLine()) != null) && (state != State.FOUND_END))
{
line = line.Trim();
if (line.Length > 0)
{
switch (state)
{
case State.FIND_BEGIN :
if (line.StartsWith("BEGIN:"))
{
state = State.GET_VERSION;
}
break;
case State.GET_VERSION :
string[] split = line.Split(new char[] { ':' });
version = split[1];
state = State.PROCESS_DATA;
break;
case State.PROCESS_DATA :
if(line.StartsWith("END"))
{
state = State.FOUND_END;
}
else
{
data.Add(line);
}
break;
}
}
}
}
}
}
i have source irc client from some site. this is the some code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text.RegularExpressions;
namespace tes_irc
{
class Program
{
static string[] usuarios;
static void Main(string[] args)
{
NetworkStream conexion;
TcpClient irc;
StreamReader leer_datos;
StreamWriter mandar_datos;
string host = "irc.dal.net";
string nickname = "testing";
string canal = "#gsgsge";
string code = "";
leer_datos = new StreamReader(conexion);
mandar_datos = new StreamWriter(conexion);
mandar_datos.WriteLine("NICK " + nickname);
mandar_datos.Flush();
mandar_datos.WriteLine("USER " + nickname + " 1 1 1 1");
mandar_datos.Flush();
mandar_datos.WriteLine("JOIN " + canal);
mandar_datos.Flush();
while (true) // Mi bucle eterno
{
while ((code = leer_datos.ReadLine()) != null)
{
Console.WriteLine("Code : " + code);
Match regex = Regex.Match(code, "PING(.*)", RegexOptions.IgnoreCase);
if (regex.Success)
{
Console.WriteLine("hehe");
string te_doy_pong = "PONG " + regex.Groups[1].Value;
mandar_datos.WriteLine(te_doy_pong);
mandar_datos.Flush();
}
regex = Regex.Match(code, ":(.*) 353 (.*) = (.*) :(.*)", RegexOptions.IgnoreCase);
if (regex.Success)
{
string usuarios_lista = regex.Groups[4].Value;
usuarios = usuarios_lista.Split(' ');
foreach (string usuario in usuarios)
{
Console.Write("[+] User : " + usuario);
}
mandar_datos.WriteLine("PRIVMSG" + " " + canal + " " + "Hello World");
mandar_datos.Flush();
}
}
}
}
}
}
Connection is succes, but when i write for send message like "Hello world" just send "Hello". what's wrong with this code? maybe must encode string before? or?please help me. Thanks before :)
The final argument of your IRC command should be prefixed with a colon character (:). Otherwise parsing of the argument will end at the first whitespace.
mandar_datos.WriteLine("PRIVMSG" + " " + canal + " " + ":Hello World");
I'm writing a Stock Quote app in Silverlight and I can't figure out how to display only the information that I want from the xml, such as the price of the stock. It will display the tags and everything.
Here is my code:
private void getQuote_Click(object sender, RoutedEventArgs e)
{
bool check = NetworkInterface.GetIsNetworkAvailable();
if (check)
{
//available
GetQuote.StockQuoteSoapClient client = new StockQuoteSoapClient();
//call that method
client.GetQuoteAsync(symbolBox.Text);
//event handler response
client.GetQuoteCompleted +=client_GetQuoteCompleted;
}
else
{
return;
}
}
public void client_GetQuoteCompleted(object sender, GetQuoteCompletedEventArgs e)
{
result.Text = e.Result;
}
And here is the xml being returned by http://www.webservicex.net/stockquote.asmx?op=GetQuote
<string><StockQuotes><Stock><Symbol>msft</Symbol><Last>46.62</Last><Date>7/17/2015</Date><Time>4:00pm</Time><Change>-0.04</Change><Open>46.59</Open><High>46.78</High><Low>46.26</Low><Volume>29467107</Volume><MktCap>377.14B</MktCap><PreviousClose>46.66</PreviousClose><PercentageChange>-0.09%</PercentageChange><AnnRange>40.12 - 50.05</AnnRange><Earns>2.41</Earns><P-E>19.35</P-E><Name>Microsoft Corporation</Name></Stock></StockQuotes></string>
This is for a mobile app; it has to provide new, up-to-date information from the web service every time it is used, and I only need a few different pieces of the information. Also, the information shouldn't be specifically Microsoft, but any real company whose stock symbol is entered by the user.
Try 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 =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<string>" +
"<StockQuotes>" +
"<Stock>" +
"<Symbol>msft</Symbol>" +
"<Last>46.62</Last>" +
"<Date>7/17/2015</Date>" +
"<Time>4:00pm</Time>" +
"<Change>-0.04</Change>" +
"<Open>46.59</Open>" +
"<High>46.78</High>" +
"<Low>46.26</Low>" +
"<Volume>29467107</Volume>" +
"<MktCap>377.14B</MktCap>" +
"<PreviousClose>46.66</PreviousClose>" +
"<PercentageChange>-0.09%</PercentageChange>" +
"<AnnRange>40.12 - 50.05</AnnRange>" +
"<Earns>2.41</Earns>" +
"<P-E>19.35</P-E>" +
"<Name>Microsoft Corporation</Name>" +
"</Stock>" +
"</StockQuotes>" +
"</string>";
XDocument doc = XDocument.Parse(input);
var stocks = doc.Descendants("Stock").Select(x => new {
symbol = x.Element("Symbol").Value,
last = double.Parse(x.Element("Last").Value),
date = DateTime.Parse(x.Element("Date").Value),
time = DateTime.Parse(x.Element("Time").Value),
change = double.Parse(x.Element("Change").Value),
open = double.Parse(x.Element("Open").Value),
high = double.Parse(x.Element("High").Value),
low = double.Parse(x.Element("Low").Value),
volume = long.Parse(x.Element("Volume").Value),
mktcap = double.Parse(x.Element("MktCap").Value.Replace("B", "")),
previousClose = double.Parse(x.Element("PreviousClose").Value),
percentChange = double.Parse(x.Element("PercentageChange").Value.Replace("%", "")),
annRange = x.Element("AnnRange").Value,
earns = double.Parse(x.Element("Earns").Value),
p_e = double.Parse(x.Element("P-E").Value),
name = x.Element("Name").Value,
}).ToList();
}
}
}
I am using a PHP script to generate xml files. I want to write the data in the XML file to a Textblock in my Windows Phone 8 App.
When I debug, I get an error which is not caught my the catch. A print screen of the error: http://i811.photobucket.com/albums/zz38/JelleK1996/errorxml1_zps20df0a45.png
What is wrong?
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;
namespace xml1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
try
{
HttpWebRequest request = WebRequest.Create("http://cocktailpws.net23.net/requests/get_cocktail.php?id=10") as HttpWebRequest;
request.BeginGetResponse(r =>
{
var reponse = request.EndGetResponse(r);
//XDocument xmlDoc = XDocument.Load(reponse.GetResponseStream());
XmlReader reader = XmlReader.Create(reponse.GetResponseStream());
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // Het knooppunt is een element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //De tekst in elk element weergeven.
tb1.Text = tb1.Text + reader.Value + "\r\n";
Console.WriteLine(reader.Value);
break;
case XmlNodeType.EndElement: //Het einde van het element weergeven.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
}, null);
}
catch (Exception myExc)
{
Console.WriteLine(myExc.Message);
}
}
}
}
Firstly you have not got try catch block inside lambda function. Thats why you cant handle error
Secondly how to solve:
change :
tb1.Text = tb1.Text + reader.Value + "\r\n";
to
Dispatcher.BeginInvoke(() => {
tb1.Text = tb1.Text + reader.Value + "\r\n";
});
Thirdly,
I Believe you need rewrite your xml loop, Cause your code is inefficent way. It will call text change if there are many texts.So build string then after loop call text change
StringBuilder res = new StringBuilder();
...
//inside xml loop:
res.AppendLine(reader.Value);
...
//after loop:
Dispatcher.BeginInvoke(() => {
tb1.Text = res.ToString();
});
And check this to see what was error. or search invalid thread call
invalid thread call
I believe you must access tb1 from the UI thread, so I would suggest trying to use a statement similar to this:
case XmlNodeType.Text: //De tekst in elk element weergeven.
{
tb1.Dispatcher.BeginInvoke(() =>
{
tb1.Text = tb1.Text + reader.Value + "\r\n";
});
Console.WriteLine(reader.Value);
}
break;
I have a file on which I want to replace the dates but I don't know what dates are on it and I want to do generic code for me to use the same executable for other files.
I put all content of the file in a string and I want to replace all dates with format dd/mm/yyyy (ex: 19/12/2011) with the actual date (20/12/2011).
How can I do that?
Code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ReplaceDates
{
class Program
{
static int Main(string[] args)
{
string FileIn = retreiveArgument(args, "i");
int AddDays = Int32.Parse(retreiveArgument(args, "d"));
string date = (System.DateTime.Now).AddDays(AddDays).ToString("dd/MM/yyyy");
string content = "", date2replace = "";
if (File.Exists(FileIn))
{
File.Copy(FileIn, FileIn + ".bkp", true);
try
{
content = File.ReadAllText(FileIn);
// here is what I need to do
}
catch (Exception)
{
Console.WriteLine("Error replacing dates in " + FileIn + ".");
return 0;
}
try
{
File.WriteAllText(FileIn, content);
Console.WriteLine("Dates replaced in " + FileIn + ".");
return 0;
}
catch (Exception)
{
Console.WriteLine("Couldn't write the file " + FileIn);
return 2;
}
}
else
{
Console.WriteLine("File " + FileIn + " does not exist.");
return 1;
}
}
private static string retreiveArgument(string[] argument, string argumentName)
{
for (int i = 0; i < argument.Length; i++)
{
if (argument[i].ToLower().Equals("-h") || argument[i].ToLower().Equals("help") || argument[i].ToLower().Equals("-help") || argument[i].Equals("?") || argument[i].Equals("-?"))
{
Console.WriteLine("Usage : ");
Console.WriteLine("ReplaceDates.exe -i [Input File] -d [Addition]");
Console.WriteLine("[Input File] -> Complete path to the file.");
Console.WriteLine("[Addition] -> Adds the specified value in days to the actual date.");
Console.WriteLine();
Console.WriteLine("This executable replaces the data from the input file.");
}
else
{
if (argument[i].Equals("-" + argumentName))
{
return argument[i + 1].Trim();
}
}
}
return "";
}
}
}
Here's a solution using a MatchEvaluator. Tweak the regular expression if desired;
string UpdateDates(string input)
{
return Regex.Replace(input, #"\d{2}/\d{2}/\d{4}", m => DateTime.Now.ToString("dd/MM/yyyy"));
}
you can use a regex for that http://www.regular-expressions.info/dates.html
Use another file that contains the layout of the original file but in the dates that you need to replace put another string, something like "DD/MM/YYYY".
Now, you simply need to open the layout file, read all content, replace the "DD/MM/YYYY" for the date you want and voilá :)