Select XML Elements and attributes - c#

I'm making a formula 1 app for WP7. I used an API to retrieve information. I managed to retrieve the attributes of the driver element but I can't retrieve the elements under it. I used this API: http://ergast.com/api/f1/2012/drivers
C#
namespace Formule1
{
public partial class DriversPage : PhoneApplicationPage
{
const string URL = "http://ergast.com/api/f1/2012/";
public DriversPage()
{
InitializeComponent();
GetDrivers();
}
private void GetDrivers()
{
string resource = "drivers";
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webclient_DownloadStringCompleted);
webclient.DownloadStringAsync(new Uri(URL + resource));
}
private void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
return;
}
// xml-resultaat parsen
XDocument xmlEntries = XDocument.Parse(e.Result);
// drivers eruit halen
List<Driver> drivers = new List<Driver>();
var ns = xmlEntries.Root.Name.Namespace;
drivers = (from element in xmlEntries.Root.Element(ns + "DriverTable").Descendants(ns + "Driver")
select new Driver(element.Attribute("driverId").Value, element.Element("GivenName").Value)).ToList<Driver>();
DriverListBox.ItemsSource = drivers;
}
}
}
API
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="http://ergast.com/schemas/mrd-1.2.xsl"?>
<MRData xmlns="http://ergast.com/mrd/1.2" series="f1" url="http://ergast.com/api/f1/2012/drivers" limit="30" offset="0" total="24">
<DriverTable season="2012">
<Driver driverId="alonso" url="http://en.wikipedia.org/wiki/Fernando_Alonso">
<GivenName>Fernando</GivenName>
<FamilyName>Alonso</FamilyName>
<DateOfBirth>1981-07-29</DateOfBirth>
<Nationality>Spanish</Nationality>
</Driver>
</DriverTable>
</MRData>

Your problem is that the element name must be qualified with the correct namespace. Change .Element("GivenName") to .Element(ns + "GivenName").

Related

VS 2019 Metadata Not Found and Value Can't Be Null Errors

Building a cross-platform App with Xamarin Forms (Most Recent Version).
These are my errors:
Metadata file 'C:\Users\sethb\source\repos\App\App\App\bin\Debug\netstandard2.0\ref\App.dll' could not be found. On File CSC, Line 1.
Value Cannot be null on File NewTicket.xaml, Line 1.
I have tried many solutions to solve this problem, such as:
Updating my Nuget Packages (including Xamarin and the Net Standard Library).
Updating Visual Studio 2019.
Various combinations of clean, empty bin/obj/nugget cache, restart app, build individual solutions, re-build entire project.
Comment out the Xamarin code I was working on when this error occurred.
Adjusting Configuration Manager for different platforms / build / deploy combinations
Uninstall and re-install the Net Standard Library.
I even tried deleting the offending page and re-building it from scratch.
Obviously, the core issue for problem #1 is that key files aren't making it into my netstandard2.0 file, but I have no idea why. Hopefully, solving that will also fix the "Value Cannot be Null" error.
I have noticed when I look up "NETStandard.Library" in my list of installed apps, the arrow symbol marking it as installed doesn't pop up. But when I click on it, it says version 2.0.3 is already installed. Strange.
I think the issue is deeper in the build order of my Project, but I'll add in the pages I was working on when this error occurred. Maybe you will find something I have missed.
Let me know if there's anything else I can provide on my end to help resolve this problem. I can't launch my emulators until this is fixed. Client is waiting on their new app and I'm dead in the proverbial water.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using App.Classes;
using Xamarin.Essentials;
using App.Tickets_Module;
using App.Dashboard_Module;
using App.PO_Module;
namespace App.Tickets_Module
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NewTicket : ContentPage
{
public List<Company> CompanyNames { get; set; }
public string Client_Name = null;
public int Client_Index;
public string Client_Id = null;
public string NewTicketPriority = null;
public NewTicket()
{
InitializeComponent();
/*
* CONSIDER: adding in a web link so they can click the ticket and go to Bento.
*/
string email = App.UserEmail;
//New Company List
List<Company> CompanyNames = new List<Company>();
//Send Open Ticket API Query
NewTicketAsync(email, CompanyNames);
}
//Check for empty fields...
private async void SendNewTicket(string email, string CheckTitle, string CheckPhone, string CheckDescription, string ClientId, string TicketPriority)
{
//Get Client Id
//Client_Id = CompanyNames[Client_Index].Id;
string Email = email;
string Pass = LoadAPIKey().Result;
string TicketClient = Client_Name;
string TicketClientId = ClientId;
string TicketPhone = CheckPhone;
string ThisPriority = TicketPriority;
//Add Backslashes
string TicketTitle = CheckTitle;
TicketTitle = TicketTitle.Replace("'", "''");
string TicketDescription = CheckDescription;
TicketDescription = TicketDescription.Replace("'", "''");
//POST URL BELOW
string url = "https://domain/tickets/new_ticket_sub.php?";
//POST REQUEST
using (HttpClient client = new HttpClient())
{
//JSON Content
string content = "{'" + Email + "',*&'" + Pass + "',*&'" + TicketClient
+ "',*&'" + TicketTitle + "',*&'" + TicketPhone
+ "',*&'" + TicketDescription + "',*&'"+ TicketClientId + "',*&'" + ThisPriority + "'}";
//Prep JSON Message
var JSON = JsonConvert.SerializeObject(content);
var POSTdata = new StringContent(JSON.ToString(), Encoding.UTF8, "application/json");
POSTdata.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//Send JSON Message
var response = await client.PostAsync(url, POSTdata);
var status = response.StatusCode.ToString();
//Await Response
var responseString = await response.Content.ReadAsStringAsync();
//Convert JSON Object into Usable Array
var message = (JsonConvert.DeserializeObject<TestMessage>(responseString)).Message;
if (message == "Email Not Found.")
{
//New Response
string newMessage = "Email does not exist. Please register a bento account for this email address.";
//Print Response
restMessage.Text = newMessage;
restMessage.IsVisible = true;
}
else if (message == "Connection Failed.")
{
//New Response
string newMessage = "Connection failed. Please contact support.";
//Print Response
restMessage.Text = newMessage;
restMessage.IsVisible = true;
}
else if (message == "API Login Error.")
{
//New Response
string newMessage = "Internal key failure, please contact support.";
//Print Response
restMessage.Text = newMessage;
restMessage.IsVisible = true;
}
else if (message == "Submission Failed.")
{
//New Response
string newMessage = "Internal ticket error, please contact support.";
//Print Response
restMessage.Text = newMessage;
restMessage.IsVisible = true;
}
else if (message == "Submission Succeeded.")
{
//Send user to Dashboard
await Navigation.PushAsync(new TicketsPage());
}
}
}
private async void NewTicketAsync(string email, List<Company> CompanyNames)
{
string Email = email;
string Pass = LoadAPIKey().Result;
//POST URL BELOW
string url = "https://domain/tickets/new_ticket_page.php?";
//POST REQUEST
using (HttpClient client = new HttpClient())
{
//JSON Content
string content = "{'" + Email + "','" + Pass + "'}";
//Prep JSON Message
var JSON = JsonConvert.SerializeObject(content);
var POSTdata = new StringContent(JSON.ToString(), Encoding.UTF8, "application/json");
POSTdata.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//Send JSON Message
var response = await client.PostAsync(url, POSTdata);
var status = response.StatusCode.ToString();
//Await Response
var responseJSON = await response.Content.ReadAsStringAsync();
//Convert JSON Object into Usable Array
var ParsedTickets = JsonConvert.DeserializeObject<List<Company>>(responseJSON);
var length = ParsedTickets.Count();
//Load array into individual Tickets
for (int i = 0; i < length; i++)
{
var companyModel = new Company
{
Company_Name = ParsedTickets[i].Company_Name,
Id = ParsedTickets[i].Id
};
CompanyNames.Add(companyModel);
}
//Load Ticket List
//OpenTickets = (JsonConvert.DeserializeObject<List<Ticket>>(responseJSON));
//Load into new Tickets List
NewTicketCompany.ItemsSource = CompanyNames;
}
}
private async Task<string> LoadAPIKey()
{
string api_key = "";
//Load API KEY
try
{
api_key = await SecureStorage.GetAsync("api_key");
}
catch (Exception)
{
// Possible that device doesn't support secure storage on device.
}
return api_key;
}
private void NewTicketCompany_SelectedIndexChanged(object sender, EventArgs e)
{
Picker NewTicketCompany = sender as Picker;
int selectedIndex = NewTicketCompany.SelectedIndex;
Client_Name = NewTicketCompany.Items[selectedIndex];
}
private void SubmitNewTicket_Clicked(object sender, EventArgs e)
{
string CheckTitle = NewTicketTitle.Text;
string CheckPhone = NewTicketPhone.Text;
string CheckDescription = NewTicketDescription.Text;
string ClientId = ThisClientId.Text;
string TicketPriority = NewTicketPriority;
if (Client_Name == null || CheckTitle == null || CheckPhone == null || CheckDescription == null || ClientId == null)
{
restMessage.Text = "Please fill out all form fields";
}
else
{
string email = App.UserEmail;
SendNewTicket(email, CheckTitle, CheckPhone, CheckDescription, ClientId, TicketPriority);
}
}
//NAVIGATION METHODS
private void Home_link_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new Dashboard());
}
private void User_profile_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new User());
}
private void Clients_profile_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new Clients());
}
private void Tickets_list_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new TicketsPage());
}
private void Orders_list_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new OrdersPage());
}
/* private void TicketPriorityPicker_SelectedIndexChanged(object sender, EventArgs e)
{
var picker = (Picker)sender;
int selectedIndex = picker.SelectedIndex;
if (selectedIndex != -1)
{
NewTicketPriority = (string)picker.ItemsSource[selectedIndex];
}
}
*/
}
}

Unable to call using Skype API in C#

I am trying to make calls through Skype API in C#. I can only open Skype but I am not able to make calls. I am looking for some suggestions to solve the issue.
public void MakeCall()
{
string PhoneName = Mike;
string MyXMLFilePath = AppDomain.CurrentDomain.BaseDirectory + #"Database\ContactsData.xml";
XmlDocument MyXmlDoc = new XmlDocument();
MyXmlDoc.Load(MyXMLFilePath);
XmlNode RootNode = MyXmlDoc.SelectSingleNode("Users");
XmlNodeList FirstLevelNodeList = RootNode.ChildNodes;
foreach (XmlNode Node in FirstLevelNodeList)
{
XmlNode SecondLevelNode1 = Node.FirstChild;
if (SecondLevelNode1.InnerText == PhoneName)
{
XmlNode SecondLevelNode2 = Node.ChildNodes[1];
PhoneNumber = SecondLevelNode2.InnerText;
}
}
if (PhoneNumber != null)
{
call(PhoneNumber);
}
else
{
MessageBox.Show("Phone number is not available.");
}
}
public void call(string number)
{
new WebBrowser().Navigate("skype:" + number + "?call");
}
It's the XML code I use:
<Users>
<User>
<Name>Mike</Name>
<Number>1234</Number>
</User>
</Users>
Here's the Skype page after I run the code.
Any hint? Thanks in advance.

Cutting a live stream into separate mp4 files

I am doing a research for cutting a live stream in piece and save it as mp4 files. I am using this source for the proof of concept:
https://learn.microsoft.com/en-us/azure/media-services/media-services-dotnet-creating-live-encoder-enabled-channel#download-sample
And this is the example code I use:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MediaServices.Client;
using Newtonsoft.Json.Linq;
namespace AMSLiveTest
{
class Program
{
private const string StreamingEndpointName = "streamingendpoint001";
private const string ChannelName = "channel001";
private const string AssetlName = "asset001";
private const string ProgramlName = "program001";
// Read values from the App.config file.
private static readonly string _mediaServicesAccountName =
ConfigurationManager.AppSettings["MediaServicesAccountName"];
private static readonly string _mediaServicesAccountKey =
ConfigurationManager.AppSettings["MediaServicesAccountKey"];
// Field for service context.
private static CloudMediaContext _context = null;
private static MediaServicesCredentials _cachedCredentials = null;
static void Main(string[] args)
{
// Create and cache the Media Services credentials in a static class variable.
_cachedCredentials = new MediaServicesCredentials(
_mediaServicesAccountName,
_mediaServicesAccountKey);
// Used the cached credentials to create CloudMediaContext.
_context = new CloudMediaContext(_cachedCredentials);
IChannel channel = CreateAndStartChannel();
// Set the Live Encoder to point to the channel's input endpoint:
string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString();
// Use the previewEndpoint to preview and verify
// that the input from the encoder is actually reaching the Channel.
string previewEndpoint = channel.Preview.Endpoints.FirstOrDefault().Url.ToString();
IProgram program = CreateAndStartProgram(channel);
ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength);
IStreamingEndpoint streamingEndpoint = CreateAndStartStreamingEndpoint();
GetLocatorsInAllStreamingEndpoints(program.Asset);
// Once you are done streaming, clean up your resources.
Cleanup(streamingEndpoint, channel);
}
public static IChannel CreateAndStartChannel()
{
//If you want to change the Smooth fragments to HLS segment ratio, you would set the ChannelCreationOptions’s Output property.
IChannel channel = _context.Channels.Create(
new ChannelCreationOptions
{
Name = ChannelName,
Input = CreateChannelInput(),
Preview = CreateChannelPreview()
});
//Starting and stopping Channels can take some time to execute. To determine the state of operations after calling Start or Stop, query the IChannel.State .
channel.Start();
return channel;
}
private static ChannelInput CreateChannelInput()
{
return new ChannelInput
{
StreamingProtocol = StreamingProtocol.RTMP,
AccessControl = new ChannelAccessControl
{
IPAllowList = new List<IPRange>
{
new IPRange
{
Name = "TestChannelInput001",
// Setting 0.0.0.0 for Address and 0 for SubnetPrefixLength
// will allow access to IP addresses.
Address = IPAddress.Parse("0.0.0.0"),
SubnetPrefixLength = 0
}
}
}
};
}
private static ChannelPreview CreateChannelPreview()
{
return new ChannelPreview
{
AccessControl = new ChannelAccessControl
{
IPAllowList = new List<IPRange>
{
new IPRange
{
Name = "TestChannelPreview001",
// Setting 0.0.0.0 for Address and 0 for SubnetPrefixLength
// will allow access to IP addresses.
Address = IPAddress.Parse("0.0.0.0"),
SubnetPrefixLength = 0
}
}
}
};
}
public static void UpdateCrossSiteAccessPoliciesForChannel(IChannel channel)
{
var clientPolicy =
#"<?xml version=""1.0"" encoding=""utf-8""?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers=""*"" http-methods=""*"">
<domain uri=""*""/>
</allow-from>
<grant-to>
<resource path=""/"" include-subpaths=""true""/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>";
var xdomainPolicy =
#"<?xml version=""1.0"" ?>
<cross-domain-policy>
<allow-access-from domain=""*"" />
</cross-domain-policy>";
channel.CrossSiteAccessPolicies.ClientAccessPolicy = clientPolicy;
channel.CrossSiteAccessPolicies.CrossDomainPolicy = xdomainPolicy;
channel.Update();
}
public static IProgram CreateAndStartProgram(IChannel channel)
{
IAsset asset = _context.Assets.Create(AssetlName, AssetCreationOptions.None);
// Create a Program on the Channel. You can have multiple Programs that overlap or are sequential;
// however each Program must have a unique name within your Media Services account.
IProgram program = channel.Programs.Create(ProgramlName, TimeSpan.FromHours(3), asset.Id);
program.Start();
return program;
}
public static ILocator CreateLocatorForAsset(IAsset asset, TimeSpan ArchiveWindowLength)
{
// You cannot create a streaming locator using an AccessPolicy that includes write or delete permissions.
var locator = _context.Locators.CreateLocator
(
LocatorType.OnDemandOrigin,
asset,
_context.AccessPolicies.Create
(
"Live Stream Policy",
ArchiveWindowLength,
AccessPermissions.Read
)
);
return locator;
}
public static IStreamingEndpoint CreateAndStartStreamingEndpoint()
{
var options = new StreamingEndpointCreationOptions
{
Name = StreamingEndpointName,
ScaleUnits = 1,
AccessControl = GetAccessControl(),
CacheControl = GetCacheControl()
};
IStreamingEndpoint streamingEndpoint = _context.StreamingEndpoints.Create(options);
streamingEndpoint.Start();
return streamingEndpoint;
}
private static StreamingEndpointAccessControl GetAccessControl()
{
return new StreamingEndpointAccessControl
{
IPAllowList = new List<IPRange>
{
new IPRange
{
Name = "Allow all",
Address = IPAddress.Parse("0.0.0.0"),
SubnetPrefixLength = 0
}
},
AkamaiSignatureHeaderAuthenticationKeyList = new List<AkamaiSignatureHeaderAuthenticationKey>
{
new AkamaiSignatureHeaderAuthenticationKey
{
Identifier = "My key",
Expiration = DateTime.UtcNow + TimeSpan.FromDays(365),
Base64Key = Convert.ToBase64String(GenerateRandomBytes(16))
}
}
};
}
private static byte[] GenerateRandomBytes(int length)
{
var bytes = new byte[length];
using (var rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(bytes);
}
return bytes;
}
private static StreamingEndpointCacheControl GetCacheControl()
{
return new StreamingEndpointCacheControl
{
MaxAge = TimeSpan.FromSeconds(1000)
};
}
public static void UpdateCrossSiteAccessPoliciesForStreamingEndpoint(IStreamingEndpoint streamingEndpoint)
{
var clientPolicy =
#"<?xml version=""1.0"" encoding=""utf-8""?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers=""*"" http-methods=""*"">
<domain uri=""*""/>
</allow-from>
<grant-to>
<resource path=""/"" include-subpaths=""true""/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>";
var xdomainPolicy =
#"<?xml version=""1.0"" ?>
<cross-domain-policy>
<allow-access-from domain=""*"" />
</cross-domain-policy>";
streamingEndpoint.CrossSiteAccessPolicies.ClientAccessPolicy = clientPolicy;
streamingEndpoint.CrossSiteAccessPolicies.CrossDomainPolicy = xdomainPolicy;
streamingEndpoint.Update();
}
public static void GetLocatorsInAllStreamingEndpoints(IAsset asset)
{
var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);
var ismFile = asset.AssetFiles.AsEnumerable().FirstOrDefault(a => a.Name.EndsWith(".ism"));
var template = new UriTemplate("{contentAccessComponent}/{ismFileName}/manifest");
var urls = locators.SelectMany(l =>
_context
.StreamingEndpoints
.AsEnumerable()
.Where(se => se.State == StreamingEndpointState.Running)
.Select(
se =>
template.BindByPosition(new Uri("http://" + se.HostName),
l.ContentAccessComponent,
ismFile.Name)))
.ToArray();
}
public static void Cleanup(IStreamingEndpoint streamingEndpoint,
IChannel channel)
{
if (streamingEndpoint != null)
{
streamingEndpoint.Stop();
streamingEndpoint.Delete();
}
IAsset asset;
if (channel != null)
{
foreach (var program in channel.Programs)
{
asset = _context.Assets.Where(se => se.Id == program.AssetId)
.FirstOrDefault();
program.Stop();
program.Delete();
if (asset != null)
{
foreach (var l in asset.Locators)
l.Delete();
asset.Delete();
}
}
channel.Stop();
channel.Delete();
}
}
}
}
Now I want to make a method to cut a live stream for example every 15 minutes and save it as mp4 but don't know where to start.
Can someone point me in the right direction?
Kind regards
UPDATE:
I want to save the mp4 files on my hard disk.
You can use ffmpeg to save the stream on your hard drive. Please see the code:
ffmpeg -i InputStreamURL -acodec aac -strict -2 -vcodec libx264 -hls_wrap 100 -f hls -hls_time 20 /var/www/html/ts/1.m3u8
The -hls_time 20 use for the time of your saved data. In fact you use ffmpeg for a HLS stream but its doing the things you want. You could access the saved data on your Hard drive in /var/www/html/ts/ (and you could change this as you want).
Or could use VLC :
cvlc -vvv rtp://#239.1.2.1:60001
--sout '#std{access=livehttp{seglen=5,delsegs=true,numsegs=5,
index=/path/to/stream.m3u8,
index-url=http://example.org/stream-########.ts},
mux=ts{use-key-frames},
dst=/path/to/stream-########.ts}'
In above command either you could change the duration of the saved data in hard drive. But I personally do not use VLC and prefer use ffmpeg
Finally you could call one of above command in your C# application and see the result. Good Luck.

treat AbsoluteUri C#

I'm trying to figure out what is the best way to treat an URL from a MVC project.
As you will see I'm reading a XML file to distinguish witch client goes where into IIS.
My problem is, sometimes i get empty URl, sometimes clients gets redirect to a wrong path. As I'm using node.Value.Contains(ClientUrl) and .FirstOrDefault(). so whenever that happens I need to adapt the XML to it like adding /login# etc..
As all URL's are Kind similar I would like to treat the URL/path to each client an use node.Value.Equals(ClientUrl) instead.
Thanks all.
Controller
public ActionResult Index(string returnUrl)
{
try
{
Response.ClearContent();
Response.ClearHeaders();
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
var useragent = Request.UserAgent;
string UrlDoCliente = Request.Url.AbsoluteUri;
SysConfig _SysConfig = new SysConfig(ClientUrl);
var isAndroid = false;
int Id = SyscoopWebConfig.Empresa;
if (useragent != null)
{
if (useragent.ToLower().Contains("Android".ToLower()))
{
isAndroid = true;
}
else
{
isAndroid = Request.Browser.IsMobileDevice;
}
}
if (isAndroid)
{
string url = SysWebConfig.urlAppMobile;
if (url != "")
{
return Redirect(url);
}
}
if (!Request.IsAuthenticated)
{
Session["sesParam"] = null;
return Redirect(SysWebConfig.urlAppDesktop + "/login#");
}
}
catch (Exception e)
{
ViewBag.message = e.Message.ToString() + ". Url wsdl: " + SysWebConfig.Wsdl;
}
return View();
}
Reading xml
private static void readXMLConfig(string ClientUrl)
{
try
{
XmlDocument docX = new XmlDocument();
string sysWebPath = AppDomain.CurrentDomain.BaseDirectory;
docX.Load(WebPath + "/SysWebConfig.xml");
XElement xml = docX.ToXElement();
var config = (from nodes in xml.Descendants("client")
from node in nodes.Attributes("url")
where node.Value.Contains(ClientUrl)
select nodes).FirstOrDefault();
if (config != null)
{
_client = int.Parse(config.Element("clientId").Value);
_wsdl = config.Element("wsdl").Value;
_urlAppMobile = config.Element("urlAppMobile").Value;
_urlAppDesktop = config.Element("urlAppDesktop").Value;
}
}
catch (Exception)
{
throw new Exception('error reading xml file');
}
}
XML sample
<?xml version="1.0" encoding="utf-8"?>
<ClientConfig>
<SysWeb>
<client url="http://192.168.2.31/sysweb/client1">
<wsdl>http://192.168.2.25/wssysweb/sysweb.dll/soap/ISysWeb</wsdl>
<clientId>001</clientId>
<urlAppMobile>http://192.168.2.31/syswebmobile/AppClient1</urlAppMobile>
<urlAppDesktop>http://192.168.2.31/sysweb/AppClient1</urlAppDesktop>
</client>
<client url="http://192.168.2.31/sysweb/client1/login#">
<wsdl>http://192.168.2.25/wssysweb/sysweb.dll/soap/ISysWeb</wsdl>
<clientId>001</clientId>
<urlAppMobile>http://192.168.2.31/syswebmobile/AppClient1</urlAppMobile>
<urlAppDesktop>http://192.168.2.31/sysweb/AppClient1</urlAppDesktop>
</client>
<client url="http://192.168.2.31/sysweb/client2">
<wsdl>http://192.168.2.25/wssyweb/syspweb.dll/soap/ISysWeb</wsdl>
<clientId>002</clientId>
<urlAppMobile>http://192.168.2.31/syswebmobile/AppClient2</urlAppMobile>
<urlAppDesktop>http://192.168.2.31/sysweb/AppClient2</urlAppDesktop>
</client>
<client url="http://192.168.2.31/sysweb/client3">
<wsdl>http://192.168.2.25/wssyweb/syspweb.dll/soap/ISysWeb</wsdl>
<clientId>003</clientId>
<urlAppMobile>http://192.168.2.31/syswebmobile/AppClient3</urlAppMobile>
<urlAppDesktop>http://192.168.2.31/sysweb/AppClient3</urlAppDesktop>
</client>
</SysWeb>
</ClientConfig>
I´ve decided to go simple by using an array to set them all the same.
string ClientUrl = Request.Url.AbsoluteUri;
string[] vUrlArray = ClientUrl.Split('/');
if (vUrlArray.Count() >= 6)
{
ClientUrl = "";
for (int i = 0; i <= 4; i++)
{
ClientUrl = ClientUrl + vUrlArray[i] + "/";
}
ClientUrl = ClientUrl.Substring(0, UrlDoCliente.LastIndexOf("/"));
}

An Error occured while parsing EntityName. Line 32, position 51

I've tried looking at several different methods revolving around using XDocument class to load my xml file. However, this error and other variations have been appearing. If I use the absolute path, it displays an error of it cannot find the file.
The issue is my xml file has a combination of both English and Japanese used in it. The link should allow for anyone to view the xml file.
Here is my code and xml file:
public partial class MainWindow : Window
{
private string URLSource = "https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=0";
public MainWindow()
{
InitializeComponent();
XMLViewer();
}
private void XMLViewer()
{
try
{
XDocument Doc = XDocument.Load(URLSource);
var Kanji = from WordList in Doc.Descendants("Kanji")
select new
{
Word = WordList.Element("Kanji").Value
};
foreach (var Word in Kanji)
{
JpnTxt.ItemsSource = Word.ToString();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}
The URL you use don't contain a XML document but an HTML page :
https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=0
You need to change the value of dl to 1, so Dropbox will return your XML document:
https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=1
As #Florian said you should use second link, but maybe you have problem to read unicode xml, so its better using Request and ResponseStream:
private string URLSource = "https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=1";
private void XMLViewer()
{
try
{
var request = (HttpWebRequest)WebRequest.Create(URLSource);
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream, true))
{
XDocument Doc = XDocument.Load(sr);
var Kanji = from WordList in Doc.Descendants("Kanji")
select new
{
Word = WordList.Element("Kanji").Value
};
foreach (var Word in Kanji)
{
JpnTxt.ItemsSource = Word.ToString();
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

Categories