Accessing and displaying certain xml elements from a Service Reference - c#

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();
}
}
}
​

Related

Pulling the Display name of an attribute from entity Metadata

I am fairly new at trying to get data from CRM using C#, I am trying to get the display names of all of my attribute on CRM, When I try, I am getting a result of Microsoft.Xrm.Sdk.Label and it doesn't seem to straight forward to get the value of that label, could someone point me in the right direction?
using System;
using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace CRM_MetaData_Download
{
class Program
{
static void Main(string[] args)
{
try {
var connectionString = #"AuthType = Office365; Url = https://CRMINFORMATION";
CrmServiceClient conn = new CrmServiceClient(connectionString);
IOrganizationService service;
service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.All,
LogicalName = "account"
};
RetrieveEntityResponse retrieveAccountEntityResponse = (RetrieveEntityResponse)service.Execute(retrieveEntityRequest);
EntityMetadata AccountEntity = retrieveAccountEntityResponse.EntityMetadata;
Console.WriteLine("Account entity attributes:");
foreach (object attribute in AccountEntity.Attributes)
{
AttributeMetadata a = (AttributeMetadata)attribute;
Console.WriteLine(a.LogicalName + " " +
a.Description + " " +
a.DisplayName + " " +
a.EntityLogicalName + " " +
a.SchemaName + " " +
a.AttributeType + " "
);
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
Since Dynamics CRM supports multi-lingual capabilities, the display name label will be stored for each language. You can get it like below:
a.DisplayName.UserLocalizedLabel.Label

Printing multiple lines in a text box/block .net c#

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
.

Getting all the items from the listbox winform

Good day!
I am having troubles on getting all the items, selected or not, from the listbox. Whenever I click the send button, the only items that I could get is the ones I selected (This is the current results of my code below: http://imgur.com/jA94Bjm). What I want is to get all the items from the textbox not just from the selected ones and which is not repeating.
private void cmd_send_Click_1(object sender, EventArgs e)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
try
{
String pno = textBox4.Text.ToString();
String path = textBox5.Text.ToString();
String name = textBox6.Text.ToString();
String user = textBox7.Text.ToString();
output.Text += "\n Sent data : " + pno + " " + user + " " + name + " " + path;
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
NetworkStream ns = tcpclnt.GetStream();
String data = "";
data = "--++" + " " + textBox4.Text + " " + textBox5.Text + " " + textBox6.Text + " " + textBox7.Text;
if (ns.CanWrite)
{
byte[] bf = new ASCIIEncoding().GetBytes(data);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
}
}
If you want to access all your items from your listbox, you have to iterate all of the items and access the value of that item. Here's a sample how you can achieve this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
class Process
{
public int ProcessId { get; set; }
public string FilePath { get; set; }
public string FileName { get; set; }
public string User { get; set; }
}
static void Main(string[] args)
{
Process p1 = new Process();
p1.ProcessId = 1;
p1.FileName = "Tool.exe";
p1.FilePath = #"C:\Tool.exe";
p1.User = "User1";
Process p2 = new Process();
p2.ProcessId = 2;
p2.FileName = "Tool2.exe";
p2.FilePath = #"C:\Tool2.exe";
p2.User = "User2";
Process p3 = new Process();
p3.ProcessId = 3;
p3.FileName = "Tool3.exe";
p3.FilePath = #"C:\Tool3.exe";
p3.User = "User3";
ListBox listBox = new ListBox();
listBox.Items.Add(p1);
listBox.Items.Add(p2);
listBox.Items.Add(p3);
for (int i = 0; i < listBox.Items.Count; i++)
{
Process p = (Process)listBox.Items[i]; //Access the value of the item
Console.WriteLine("Process id: {0}", p.ProcessId);
Console.WriteLine("Process filename: {0}", p.FileName);
Console.WriteLine("Process file path: {0}", p.FilePath);
Console.WriteLine("Process user: {0}", p.User);
}
Console.ReadLine();
}
}
}
We have a sample class Process with different properties. Each Process is added on ListBox which is later accessed inside the loop.

mono-service keeps reserving memory untill raspberry pi is out of mem

So I have a background service written in C# which connects to a RFID-reader and reads out all the tags he sees. After that the service will place all tags in a database running on the Raspberry Pi as well. The problem is when I start the service that it keeps consuming more and more memory from the Pi. I've already ran it with mono-service --profile=default:alloc but this returns errors. Does anybody see anything in my code which could cause this memory usage?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Impinj.OctaneSdk;
using MySql.Data.MySqlClient;
using Raspberry.IO.GeneralPurpose;
using System.IO.Ports;
using System.Xml;
using System.Threading;
namespace RFIDdaemon
{
public partial class RFIDdaemon : ServiceBase
{
// Create an instance of the ImpinjReader class.
static ImpinjReader reader = new ImpinjReader();
static int opIdUser, opIdTid;
static MySQL _oMySql = new MySQL(Properties.Resources.DatabaseHostname, Properties.Resources.Database, Properties.Resources.Uid, Properties.Resources.Pwd);
// Create a Dictionary to store the tags we've read.
static OutputPinConfiguration led1 = ConnectorPin.P1Pin18.Output();
static GpioConnection connection = new GpioConnection(led1);
static XmlDocument Power = new XmlDocument();
private Thread _oThread;
private ManualResetEvent _oManualResetEvent = new ManualResetEvent(false);
static string userData, tidData, epcData;
public RFIDdaemon()
{
this.ServiceName = "RFIDdaemon";
this.AutoLog = false;
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (_oThread == null)
{
_oThread = new Thread(Reader);
}
if (!_oThread.IsAlive)
{
_oManualResetEvent.Reset(); //Reset reset event te continue thread
_oThread = new Thread(Reader); //New thread
_oThread.Name = "RFIDreader";
_oThread.IsBackground = true;
_oThread.Start();
}
}
protected override void OnStop()
{
// Stop reading.
reader.Stop();
GC.Collect();
// Disconnect from the reader.
reader.Disconnect();
connection.Close();
}
static void Reader()
{
try
{
// Connect to the reader.
// Change the ReaderHostname constant in SolutionConstants.cs
// to the IP address or hostname of your reader.
reader.Connect(Properties.Resources.ReaderIP);
// Assign the TagOpComplete event handler.
// This specifies which method to call
// when tag operations are complete.
reader.TagOpComplete += OnTagOpComplete;
// Get the default settings
// We'll use these as a starting point
// and then modify the settings we're
// interested in.
Settings settings = reader.QueryDefaultSettings();
double[] Results = ReadXml();
if(Results != null)
{
settings.Antennas.GetAntenna(1).TxPowerInDbm = Results[0];
settings.Antennas.GetAntenna(1).RxSensitivityInDbm = Results[1];
}
// Create a tag read operation for User memory.
TagReadOp readUser = new TagReadOp();
// Read from user memory
readUser.MemoryBank = MemoryBank.User;
// Read two (16-bit) words
readUser.WordCount = 2;
// Starting at word 0
readUser.WordPointer = 0;
// Create a tag read operation for TID memory.
TagReadOp readTid = new TagReadOp();
// Read from TID memory
readTid.MemoryBank = MemoryBank.Tid;
// Read two (16-bit) words
readTid.WordCount = 8;
// Starting at word 0
readTid.WordPointer = 0;
// Add these operations to the reader as Optimized Read ops.
// Optimized Read ops apply to all tags, unlike
// Tag Operation Sequences, which can be applied to specific tags.
// Speedway Revolution supports up to two Optimized Read operations.
settings.Report.OptimizedReadOps.Add(readUser);
settings.Report.OptimizedReadOps.Add(readTid);
// Store the operation IDs for later.
opIdUser = readUser.Id;
opIdTid = readTid.Id;
// Apply the newly modified settings.
reader.ApplySettings(settings);
// Start reading.
reader.Start();
}
catch (OctaneSdkException e)
{
// Handle Octane SDK errors.
Console.WriteLine("Octane SDK exception: {0}", e.Message);
//Console.ReadLine();
}
catch (Exception e)
{
// Handle other .NET errors.
Console.WriteLine("Exception : {0}", e.Message);
}
}
// This event handler will be called when tag
// operations have been executed by the reader.
static void OnTagOpComplete(ImpinjReader reader, TagOpReport report)
{
try
{
userData = tidData = epcData = "";
// Loop through all the completed tag operations
foreach (TagOpResult result in report)
{
// Was this completed operation a tag read operation?
if (result is TagReadOpResult)
{
// Cast it to the correct type.
TagReadOpResult readResult = result as TagReadOpResult;
// Save the EPC
epcData = readResult.Tag.Epc.ToHexString();
// Are these the results for User memory or TID?
if (readResult.OpId == opIdUser)
userData = readResult.Data.ToHexString();
if (readResult.OpId == opIdTid)
tidData = readResult.Data.ToHexString();
if (epcData != "")
{
InsertTag(epcData, tidData, userData, DateTime.Now);
}
readResult = null;
}
}
userData = tidData = epcData = null;
}
catch
{
}
}
static void InsertTag(string EPC, string TID, string User, DateTime TagreadTime)
{
try
{
DataTable Time = _oMySql.Select("SELECT Tijd FROM biketable WHERE EPC = '" + EPC + "';").Tables[0];
DateTime OldTime = Convert.ToDateTime(Time.Rows[0][0]);
TimeSpan diff = TagreadTime.Subtract(OldTime);
string formatForMySql = TagreadTime.ToString("yyyy-MM-dd HH:mm:ss");
if (diff.TotalSeconds > 20)
{
connection.Blink(led1, 100);
if (_oMySql.Select("SELECT Binnen From biketable WHERE EPC = '" + EPC + "';").Tables[0].Rows[0][0].ToString() == "True")
_oMySql.Update("UPDATE biketable SET Tijd = '" + formatForMySql + "', TID = '" + TID + "', UserMem ='" + User + "', Binnen = 'False' WHERE EPC = '" + EPC + "';");
else
_oMySql.Update("UPDATE biketable SET Tijd = '" + formatForMySql + "', TID = '" + TID + "', UserMem ='" + User + "', Binnen = 'True' WHERE EPC = '" + EPC + "';");
}
Time = null;
formatForMySql = null;
}
catch
{
}
}
static double[] ReadXml()
{
double[] Results = new double[2];
try
{
string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Power.Load(dir + #"\\Power.XML");
XmlNodeList TXpower = Power.GetElementsByTagName("TXpower");
XmlNodeList RXpower = Power.GetElementsByTagName("RXpower");
Results[0] = System.Convert.ToDouble(TXpower[0].InnerXml);
Results[1] = System.Convert.ToDouble(RXpower[0].InnerXml);
return Results;
}
catch (Exception e)
{
return null;
}
}
}
}
when I run tail -n 1000 /var/log/syslog I get the following messages: note the last messages where it kills the service
http://cl.ly/image/343p2i2y251L
How can I easily detect the memory leak?
Thanks in advance

MaasOne yahoo-finance-managed returning zero results for AlphabeticIDIndexResult

I am trying to use http://code.google.com/p/yahoo-finance-managed/ to retrieve a list of all stock ids
with the following code:
using MaasOne.Base;
using MaasOne.Finance.YahooFinance;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Elance___Yahoo_Finance_Symbols
{
class Program
{
static void Main(string[] args)
{
AlphabeticIDIndexDownload dl1 = new AlphabeticIDIndexDownload();
dl1.Settings.TopIndex = null;
Response<AlphabeticIDIndexResult> resp1 = dl1.Download();
Console.Write("Id|Isin|Name|Exchange|Type|Industry");
foreach (var alphabeticalIndex in resp1.Result.Items)
{
AlphabeticalTopIndex topIndex = (AlphabeticalTopIndex)alphabeticalIndex;
dl1.Settings.TopIndex = topIndex;
Response<AlphabeticIDIndexResult> resp2 = dl1.Download();
foreach (var index in resp2.Result.Items)
{
IDSearchDownload dl2 = new IDSearchDownload();
Response<IDSearchResult> resp3 = dl2.Download(index);
int i = 0;
foreach (var item in resp3.Result.Items)
{
Console.Write(item.ID + "|" + item.ISIN + "|" + item.Name + "|" + item.Exchange + "|" + item.Type + "|" + item.Industry);
}
}
}
}
}
}
but the
Response<AlphabeticIDIndexResult> resp1 = dl1.Download();
is always returning zero results...
Does anyone know what might be wrong please?
Thanks
I have an app using this API that's been working for about a year, and I see the same issue as of yesterday. :( Perhaps Yahoo changed their API, which would really suck.

Categories