[Code]C# - App.Config reader - Windows Mobile Software Development

I just want to share my code for reading app.config file. I wrote it earlier for my current project - JWMD Stuick.
I just want it simple and clean and my/an alternative of (I never used it though) OpenNETCF.Configuration.
here's the code
PHP:
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
using System.IO;
namespace ApplicationConfiguration
{
public class Configuration
{
XmlDocument xmldoc;
string _applicationname = string.Empty;
string _appconfigfile = string.Empty;
Dictionary<string, string> _appSettings = new Dictionary<string, string>();
public Dictionary<string, string> AppSettings
{
get { return _appSettings; }
}
public Configuration()
{
string startup = System.Reflection.Assembly.GetCallingAssembly().GetName().CodeBase;
FileInfo fi = new FileInfo(startup);
this._applicationname = System.IO.Path.GetFileNameWithoutExtension(startup);
this._appconfigfile = System.IO.Path.Combine(fi.DirectoryName.ToString(), _applicationname + ".exe.config");
Read();
}
void Read()
{
xmldoc = new XmlDocument();
xmldoc.Load(this._appconfigfile);
XmlNodeList nodeCol = xmldoc.SelectNodes("//add");
if (nodeCol != null)
{
foreach (XmlNode thisNode in nodeCol)
{
string key = thisNode.Attributes["key"].Value.ToString();
string value = thisNode.Attributes["value"].Value.ToString();
this._appSettings.Add(key, value);
System.Diagnostics.Debug.WriteLine(key + ", " + value);
}
}
}
}
}
to make this work, make sure app config file is named the way Windows Forms rename the app.config.
e.g. your application name is "mysuperapplication" then the app config file must be "mysuperapplication.exe.config"
below is a application test.

Related

Deploy XAP without Visual Studio

Is it possible to deploy my XAP file without using Visual Studio in either hacked or original emulator image?
With XNA tool WP.exe you can install .xap to Emulator or Device WITHOUT VisualStudio.
On my machine, XNAGSv4=C:\Program Files\Microsoft XNA\XNA Game Studio\v4.0\Tools
Command:
wp install [options] <xap> <app id> <icon> <xapcache>
Example:
%XNAGSv4%\Tools\wp.exe install HellpWP7.xap 71f6d153-0759-4d6e-9bcd-de9a49d8f232 ApplicationIcon.png XapCacheFile.xml
* app id: The GUID found in Propeties\AssemblyInfo.cs
* ApplicationIcon.png: Found in the output directory.
* XapCacheFile.xml: Found in the intermediate (obj) directory.
I have read that the approach using wp.exe from XNA only works for XNA apps. Here is another approach which makes use of CoreCon API: h**p://justinangel.net/WindowsPhone7EmulatorAutomation
XapDeploy
You should use XapDeploy tool from following folder:
c:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Tools\XAP Deployment\
or c:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Tools\XAP Deployment\
Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Xml.XPath;
using Microsoft.SmartDevice.Connectivity;
internal static class Utils
{
// Fields
private const string AppIconFileName = "ApplicationIcon.png";
private const string AppNode = "//App";
private const string DefaultAppIcon = "Microsoft.Phone.Tools.DefaultAppIcon.png";
private const string ProductIdNode = "ProductID";
private const string WMAppManifestFile = "WMAppManifest.xml";
// Methods
internal static string ExtractIconFile(string xapPath)
{
string str2;
try
{
using (FileStream stream = new FileStream(xapPath, FileMode.Open, FileAccess.Read))
{
Stream fileStream = new ZipArchive(stream).GetFileStream("ApplicationIcon.png");
if (fileStream == null)
{
fileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.Phone.Tools.DefaultAppIcon.png");
}
string tempFileName = Path.GetTempFileName();
using (FileStream stream3 = new FileStream(tempFileName, FileMode.Create))
{
fileStream.CopyTo(stream3);
}
str2 = tempFileName;
}
}
catch (Exception)
{
str2 = null;
}
return str2;
}
internal static DeviceInfo[] GetDevices()
{
List<DeviceInfo> list = new List<DeviceInfo>();
DatastoreManager manager = new DatastoreManager(0x409);
foreach (Platform platform in manager.GetPlatforms())
{
foreach (Device device in platform.GetDevices())
{
list.Add(new DeviceInfo(platform.Id.ToString(), device.Id.ToString(), device.Name));
}
}
return list.ToArray();
}
internal static Guid? GetXapGuid(string xapPath)
{
Guid? nullable;
try
{
using (FileStream stream = new FileStream(xapPath, FileMode.Open, FileAccess.Read))
{
ZipArchive archive = new ZipArchive(stream);
using (Stream stream2 = archive.GetFileStream("WMAppManifest.xml"))
{
XPathDocument document = new XPathDocument(stream2);
nullable = new Guid(document.CreateNavigator().SelectSingleNode("//App").GetAttribute("ProductID", string.Empty));
}
}
}
catch (Exception)
{
nullable = null;
}
return nullable;
}
internal static RemoteApplication InstallApplication(DeviceInfo deviceInfo, Guid appGuid, string applicationGenre, string iconFile, string xapFile)
{
DatastoreManager manager = new DatastoreManager(0x409);
Device device = manager.GetPlatform(new ObjectId(deviceInfo.PlatformId)).GetDevice(new ObjectId(deviceInfo.DeviceId));
device.Connect();
if (device.IsApplicationInstalled(appGuid))
{
RemoteApplication application = device.GetApplication(appGuid);
application.TerminateRunningInstances();
application.Uninstall();
}
RemoteApplication installApplication = device.InstallApplication(appGuid, appGuid, applicationGenre, iconFile, xapFile);
installApplication.Launch();
return installApplication;
}
internal class DeviceInfo
{
// Methods
internal DeviceInfo(string platformId, string deviceid, string deviceName)
{
this.PlatformId = platformId;
this.DeviceId = deviceid;
this.DeviceName = deviceName;
}
public override string ToString()
{
return this.DeviceName;
}
// Properties
internal string DeviceId
{
get;
set;
}
internal string DeviceName
{
get;
set;
}
internal string PlatformId { get; set; }
}
internal class ZipArchive
{
// Fields
private List<ZipArchiveFile> fileList = new List<ZipArchiveFile>();
private FileStream stream;
// Methods
internal ZipArchive(FileStream stream)
{
this.stream = stream;
for (ZipArchiveFile file = ZipArchiveFile.ReadHeader(stream); file != null; file = ZipArchiveFile.ReadHeader(stream))
{
this.fileList.Add(file);
}
}
internal Stream GetFileStream(string filename)
{
foreach (ZipArchiveFile file in this.fileList)
{
if (string.Compare(file.Name, filename, true) == 0)
{
return file.GetUncompressedStream(this.stream);
}
}
return null;
}
}
internal class DeployArguments
{
internal DeployArguments(DeviceInfo deviceInfo, System.Guid guid, string icon, string xap, OnCompleteAction onComplete)
{
this.DeviceInfo = deviceInfo;
this.Guid = guid;
this.Icon = icon;
this.Xap = xap;
this.OnComplete = onComplete;
}
internal DeviceInfo DeviceInfo
{
get;
set;
}
internal System.Guid Guid
{
get;
set;
}
internal string Icon
{
get;
set;
}
internal OnCompleteAction OnComplete
{
get;
set;
}
internal string Xap { get; set; }
internal delegate void OnCompleteAction(Exception ex);
}
internal class ZipArchiveFile
{
private ushort compressMethod;
private long dataPosition;
// Methods
private ZipArchiveFile()
{
}
internal Stream GetUncompressedStream(Stream zipStream)
{
zipStream.Seek(this.dataPosition, SeekOrigin.Begin);
switch (this.compressMethod)
{
case 0:
return zipStream;
case 8:
return new DeflateStream(zipStream, CompressionMode.Decompress);
}
return null;
}
internal static ZipArchiveFile ReadHeader(FileStream stream)
{
BinaryReader reader = new BinaryReader(stream);
if (reader.ReadUInt32() != 0x4034b50)
{
return null;
}
ZipArchiveFile file = new ZipArchiveFile();
reader.ReadUInt16();
reader.ReadUInt16();
file.compressMethod = reader.ReadUInt16();
reader.ReadUInt16();
reader.ReadUInt16();
reader.ReadUInt32();
uint num2 = reader.ReadUInt32();
reader.ReadUInt32();
ushort count = reader.ReadUInt16();
ushort num4 = reader.ReadUInt16();
file.Name = new string(reader.ReadChars(count));
reader.ReadBytes(num4);
file.dataPosition = reader.BaseStream.Position;
reader.BaseStream.Seek((long)num2, SeekOrigin.Current);
return file;
}
// Properties
internal string Name { get; set; }
}
}
And
Code:
Utils.InstallApplication(Utils.GetDevices()[0], Utils.GetXapGuid(FILENAME).Value, "NormalApp", Utils.ExtractIconFile(FILENAME).Icon, FILENAME);
Regs,
b0l0k
Nice, and only your second post.. Where did you get this?
That's reflected from XapDeploy
You will have to use XapDeploy tool. It requires Zune running on the same environment. You can also use WPConnect, a console tool, if you have Zune installed, see msdn.microsoft.com/en-us/library/gg180729(VS.92).aspx

[Q] [.net cf]Loopback

Hey guys
I'm developing a little webserver for WM with the .net cf. it's easy and works fine as long as I don't try to access it from the same device it's running on. Nothing works: localhost,127.0.0.1 or even if I'm connected to a wifi network and I use this IP. Has anyone the solution for this issue?
ta you
a yeah I use the TcpListener-Class and I implemted some simple HTTP.
chabun
Code
Hey guys
Noone has an idea??
Here is the code which I use to setup the HttpListener and answer connections.
Code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using StedySoft.SenseSDK;
using System.Threading;
using System.IO;
namespace WebServer
{
public partial class ServerForm : Form
{
IPEndPoint local;
TcpListener listener;
private volatile bool stop;
private volatile bool handled;
SensePanelItem state;
SensePanelTextboxItem response;
Thread serverThread;
public ServerForm(IPEndPoint local)
{
InitializeComponent();
this.local = local;
SetupList();
}
private void SetupList()
{
SensePanelDividerItem infos = new SensePanelDividerItem("infd", "Infos");
mainList.AddItem(infos);
mainList.AddItem(new SensePanelItem("Local-Endpoint") { PrimaryText = "Local-Endpoint", SecondaryText = local.ToString() });
mainList.AddItem(state = new SensePanelItem("Status") { PrimaryText = "Status", SecondaryText = "Wird gestartet..." });
mainList.AddItem(new SensePanelDividerItem("Response", "Response"));
mainList.AddItem(response = new SensePanelTextboxItem("body") { LabelText = "HTML-Body, welcher auf Requests gesendet wird.", Text = "<span style =\"color:red;font-size:30pt\">It works!!</span>" });
mainList.AddItem(new SensePanelDividerItem("Requests", "Requests"));
}
private void StartServer()
{
if (listener != null)
{
StopServer(true);
}
listener = new TcpListener(local.Port);
listener.Start();
serverThread = new Thread(listen);
serverThread.IsBackground = true;
stop = false;
serverThread.Start();
state.SecondaryText = "Gestartet...";
}
private void listen()
{
while (!stop)
{
while (listener.Pending())
{
handled = false;
Thread handlingThread = new Thread(handler);
handlingThread.Start();
while (!handled)
Thread.Sleep(50);
}
Thread.Sleep(200);
}
}
private void handler()
{
// Get the current connection
TcpClient client = (TcpClient)this.Invoke(new Func<TcpClient>(listener.AcceptTcpClient));
IPEndPoint remote = (IPEndPoint)client.Client.RemoteEndPoint;
handled = true;
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
ReadHttpRequest(reader);
StreamWriter writer = new StreamWriter(stream);
StringBuilder response = new StringBuilder(); ;
StartHTML(response);
response.AppendLine((string)this.Invoke(new Func<IPEndPoint, string>(GetResponse), remote));
EndHTML(response);
WriteHTTPResponse(writer, response.Length);
writer.WriteLine(response.ToString());
writer.Flush();
stream.Close();
client.Close();
}
private void WriteHTTPResponse(StreamWriter writer, int length)
{
writer.WriteLine("HTTP/1.1 200 OK");
writer.WriteLine("Date: " + DateTime.Now.ToString());
writer.WriteLine("Content-Length: "+ length.ToString());
writer.WriteLine("Connection: close");
writer.WriteLine("Content-Type: text/html; charset=utf-8");
writer.WriteLine();
}
private void ReadHttpRequest(StreamReader reader)
{
string buffer = null;
while (buffer != "")
buffer = reader.ReadLine();
}
int counter = 0;
private string GetResponse(IPEndPoint remote)
{
counter++;
mainList.AddItem(new SensePanelItem(counter.ToString()) { PrimaryText = remote.ToString(), SecondaryText = "Response:" + counter.ToString() });
return response.Text;
}
private void EndHTML(StringBuilder writer)
{
writer.AppendLine("</body>");
writer.AppendLine("</html>");
}
private void StartHTML(StringBuilder writer)
{
writer.AppendLine("<?xml version=\"1.0\"?>");
writer.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
writer.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"de\" lang=\"de\">");
writer.AppendLine("<head>");
writer.AppendLine("<title>SmartWebServer</title>");
writer.AppendLine("<meta name=\"author\" content=\"Alexander Kayed\">");
writer.AppendLine("</head>");
writer.AppendLine("<body>");
}
private void StopServer(bool restart)
{
stop = true;
serverThread.Join();
if (restart)
StartServer();
}
private void ServerForm_Load(object sender, EventArgs e)
{
StartServer();
}
private void ServerForm_Closed(object sender, EventArgs e)
{
StopServer(false);
}
private void menuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
The user can choose the IPEndPoint(constructor), which the server will be bound to, in a prevouis form:
Code:
foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
item = new SensePanelRadioItem(ip.ToString());
item.PrimaryText = ip.ToString();
item.SecondaryText = ip.AddressFamily.ToString();
item.Tag = ChoosedIp = ip;
item.OnStatusChanged += new SensePanelRadioItem.StatusEventHandler(item_OnStatusChanged);
IPList.AddItem(item);
}
So the user can choose between IPs I got from the DNS (e.g. 127.0.0.1, 192.168.0.1) and type a free (valid) port number (eg. 80, 8080, 8888)
Thanks for Your help!!
Still no answer...
I will post my experiences with this issue as long as I solved it - like small blog. Maybe some of you have the same problem...
I found another strange thing:
I'm able to connect to my Server from a TcpClient from another self-written App (own exectuable, different AppDomain):
Code:
void test()
{
Action<string> setText = new Action<string>(setTestText);
try
{
this.Invoke(setText, "Connect...");
TcpClient client = new TcpClient();
client.Connect(local);
this.Invoke(setText, "Connected...");
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream);
StreamReader reader = new StreamReader(stream);
writer.WriteLine();
writer.Flush();
this.Invoke(setText, "Read answer");
string buffer = reader.ReadToEnd();
this.Invoke(setText, "Test succeeded");
testing = false;
}
catch
{
this.Invoke(setText, "Test failed");
}
}
And I got a the right answer as well. It's strange, really strange that the browsers (IE,Opera etc.) can't loopback to it?

[Q] Developing app that requires root - freezes after asking for su

I am new to android development and am having an issue. I am working on an app that requires root and when I request it using this code:
Code:
Runtime.getRuntime().exec(new String[] {"su"});
I get the request, Allow it then the app locks up and doesn't go to the next item. I am trying to figure out the debugging environment in eclipse, but have not figured out a way to debug this. Is there something I need to do after acquiring root? The next line of code is a simple Toast, so I know it is locking up at the su command. Is there any documentation on writing root apps anybody can point me to? Or is there a simple answer? Thanks in advance.
EDIT: Just in case the whole code will help, here it is:
Code:
public class toggle extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
String[] results = executeShellCommand(new String[] {"su"});
Toast toast = Toast.makeText(this, results[0], Toast.LENGTH_SHORT);
toast.show();
finish();
}
public String[] executeShellCommand(String[] args) {
Process mLogcatProc = null;
BufferedReader reader = null;
BufferedReader errorReader = null;
String logResult = null;
String errorLogResult = null;
String separator = System.getProperty("line.separator");
try
{
mLogcatProc = Runtime.getRuntime().exec(args);
reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream()));
errorReader = new BufferedReader(new InputStreamReader(mLogcatProc.getErrorStream()));
String line;
final StringBuilder log = new StringBuilder();
while ((line = reader.readLine()) != null)
{
log.append(line);
log.append(separator);
}
logResult = log.toString();
String errorLine;
final StringBuilder errorLog = new StringBuilder();
while ((errorLine = errorReader.readLine()) != null)
{
errorLog.append(errorLine);
errorLog.append(separator);
}
errorLogResult = errorLog.toString();
if((logResult.length() == 0) || (errorLogResult.length() > 0))
{
if(errorLogResult.length() > 0)
{
return errorLogResult.split(separator);
}
else
{
return (new String[] {"null_result"});
}
}
else
{
return logResult.split(separator);
}
}
catch (Exception e)
{
return (new String[] {e.toString()});
}
finally
{
if (reader != null)
try
{
reader.close();
}
catch (IOException e)
{
}
}
}
}
I do this a bunch in my RogueTools app.
Take a peek here:
https://github.com/myn/RogueTools/blob/master/src/com/logicvoid/roguetools/OverClock.java
Let me know if you need a hand.
myn said:
I do this a bunch in my RogueTools app.
Take a peek here:
https://github.com/myn/RogueTools/blob/master/src/com/logicvoid/roguetools/OverClock.java
Let me know if you need a hand.
Click to expand...
Click to collapse
Thanks a ton, I should be able to get it from here....I'll let you know if not.
Myn always on top of things
Sent from my unrEVOked using xda app

MAPIdotnet and binary message body

Best all,
A while ago I tried to make a simple application which can export all my smses and mmses to my local database server. It runs quite smoothly but I can't manage to get the correct mms body data. It seems that about 5% of the exported body data(for example a sent picture in jpeg format) is different from the original jpeg picture/body data: the exported picture data can't be viewed, it is corrupt.
I suspect the method of exporting the data must be changed from string to binary, but I don't know exactly how to proceed.
I'm using C# 2008 in combination with the MAPIdotnet library, and my target device is a HTC HD Mini with Windows Mobile 6.5 professional.
The part of my code where it's going wrong:
Code:
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(s);
bw.Write(ba);
bw.Close();
fs.Close();
if (messages[msgID].Body != null)
{
FileStream fs2 = File.Create("\\Opslagkaart\\Debug\\body_" + Convert.ToString(msgID) + ".dat");
BinaryWriter bw2 = new BinaryWriter(fs2);
System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
byte[] file = enc.GetBytes(messages[msgID].Body);
//bw2.Write(messages[msgID].Body);
bw2.Write(file);
bw2.Close();
fs2.Close();
}
In combination with MAPIdotnet's code:
Code:
public string Body
{
get
{
IStreamChar s = (IStreamChar)this.msg.OpenProperty(cemapi.PropTags.PR_BODY, 0);
if (s == null)
return "";
IntPtr p = Marshal.AllocHGlobal(4);
char[] b = new char[3];
StringBuilder str = new StringBuilder();
int c, len = b.Length * 2;
do
{
s.Read(b, len, p);
c = Marshal.ReadInt32(p);
str.Append(new string(b, 0, c / 2));
}
while (c >= len);
Marshal.FreeHGlobal(p);
return str.ToString();
}
}
Can somebody give a hint of how to proceed?
Thanks,
I suddenly got some more inspiration and, with help from google, I've managed to correctly retrieve the binary jpeg attachments of two of my mmses.
The code part of my program:
Code:
//if (messages[msgID].BodyBinary.Length>0)
//{
FileStream fs2 = File.Create("\\Opslagkaart\\Debug\\body_" + Convert.ToString(msgID) + ".dat");
BinaryWriter bw2 = new BinaryWriter(fs2);
bw2.Write(messages[msgID].BodyBinary);
bw2.Close();
fs2.Close();
//}
The code part of the customized MAPIdotnet:
Code:
private static IntPtr ReadBuffer;
static int Read(OpenNETCF.Runtime.InteropServices.ComTypes.IStream strm, byte[] buffer)
{
if (ReadBuffer == IntPtr.Zero) ReadBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)));
try
{
strm.Read(buffer, buffer.Length, ReadBuffer);
}
catch (NullReferenceException e)
{
//do nothing
}
return Marshal.ReadInt32(ReadBuffer);
}
public byte[] BodyBinary
{
get
{
int buffsize = 1024*1024*2; /* If mms body is bigger than 2MB we have a problem here */
byte[] buffer = new byte[buffsize];
Read(this.msg.OpenProperty(cemapi.PropTags.PR_BODY, 0), buffer);
byte[] data = buffer;//ms.ToArray();
Marshal.FreeCoTaskMem(ReadBuffer);
return data;
}
}
But now ALL bodies are saved as 2MB files.. including the empty ones from for example a sms. And not all mms bodies are of the max size of 2mb. My carrier/phone supports up to 1MB. Perhaps I need to get some 'dynamic size' buffer instead of the fixed one. Does anyone have an idea on how to determine the size of the
this.msg.OpenProperty(cemapi.PropTags.PR_BODY, 0)
Click to expand...
Click to collapse
stream ?
I've solved all my problems by means of the following code (for mapidotnet):
Code:
private static IntPtr ReadBuffer;
static int Read(OpenNETCF.Runtime.InteropServices.ComTypes.IStream strm, byte[] buffer)
{
int returnvalue = 0;
if (ReadBuffer == IntPtr.Zero) ReadBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)));
try
{
strm.Read(buffer, buffer.Length, ReadBuffer);
returnvalue = Marshal.ReadInt32(ReadBuffer);
}
catch (NullReferenceException e)
{
returnvalue = 0;
}
return returnvalue;
}
public byte[] BodyBinary
{
get
{
int newdatasize = 0;
int buffsize = 1024*1024*3; /* If mms body is bigger than 3MB we have a problem here */
byte[] buffer = new byte[buffsize];
newdatasize = Read(this.msg.OpenProperty(cemapi.PropTags.PR_BODY, 0), buffer);
if (newdatasize < 0) { newdatasize = 0; }
byte[] data = new byte[newdatasize];
Buffer.BlockCopy(buffer, 0, data, 0, newdatasize);
Marshal.FreeCoTaskMem(ReadBuffer);
return data;
}
}
Now all is working fine and the exported files are of their own real size. I'm sure the above code can be optimized but it's working good now.

[VS 2010 Windows Phone] RSS Reader application

At first sorry for my English.
I am making an application on the basis of an RSS reader.
I wanted to add to the code so that the read xml file in addition to the title, content, date and time of the author.
Please help and thank you.
Code:
using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.IO;
using System.ServiceModel.Syndication;
using System.Xml;
using Microsoft.Phone.Tasks;
using System.Windows.Data;
namespace WindowsMania.pl
{
public partial class posty : PhoneApplicationPage
{
public posty()
{
InitializeComponent();
}
private void loadFeedButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new System.Uri(" link to xml "));
}
private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Próba wczytania danych zakończona niepowodzeniem, sprawdź połączenie z siecią.");
});
}
else
{
this.State["feed"] = e.Result;
UpdateFeedList(e.Result);
}
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (this.State.ContainsKey("feed"))
{
if (feedListBox.Items.Count == 0)
{
UpdateFeedList(State["feed"] as string);
}
}
}
private void UpdateFeedList(string feedXML)
{
StringReader stringReader = new StringReader(feedXML);
XmlReader xmlReader = XmlReader.Create(stringReader);
SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
feedListBox.ItemsSource = feed.Items;
loadFeedButton.Content = "Odśwież";
});
}
private void feedListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox listBox = sender as ListBox;
if (listBox != null && listBox.SelectedItem != null)
{
SyndicationItem sItem = (SyndicationItem)listBox.SelectedItem;
if (sItem.Links.Count > 0)
{
Uri uri = sItem.Links.FirstOrDefault().Uri;
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = uri;
webBrowserTask.Show();
}
}
}
}
}
Robert Hägee K. said:
At first sorry for my English.
I am making an application on the basis of an RSS reader.
I wanted to add to the code so that the read xml file in addition to the title, content, date and time of the author.
Please help and thank you.
Click to expand...
Click to collapse
Why don't you try it with the state manager in the expression blend ?

Categories

Resources