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.
Related
As the title says, is it possible to optimize the following code by using yield, is it worth and if so, how?
public static void LoadSettings(string fileName)
{
try
{
var xml = new XmlDocument();
xml.Load(fileName);
var userNodes = xml.SelectNodes("/settings");
foreach (XmlNode node in userNodes)
{
globals.username = node.SelectSingleNode("username").InnerText;
globals.password = node.SelectSingleNode("password").InnerText;
globals.rank = node.SelectSingleNode("rank").InnerText;
}
}
catch
{
Console.WriteLine("Oops, something is wrong.");
}
}
Edit: Thanks for answers guys!
No, you cannot. yield return can only implemented for methods actually returning something. You don't have a return value, so the answer is no.
As an example, this could be an application of yield return, but that would change the meaning of your method:
public static IEnumerable<Setting> LoadSettings(string fileName)
{
try
{
var xml = new XmlDocument();
xml.Load(fileName);
var userNodes = xml.SelectNodes("/settings");
foreach (XmlNode node in userNodes)
{
Setting globals = new Setting();
globals.username = node.SelectSingleNode("username").InnerText;
globals.password = node.SelectSingleNode("password").InnerText;
globals.rank = node.SelectSingleNode("rank").InnerText;
yield return globals;
}
}
catch
{
Console.WriteLine("Oops, something is wrong.");
}
}
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("/"));
}
I have the following xml. I am trying to search for a specific node (i.e. IcMDetails Cluster="") and return the node level details.
The code that I have will find a specific cluster (i.e. IcMDetails Cluster="ClusterA"). However, I am unable to figure out how to get the node level details (i.e. IncidientId, Title, AssignedTo, etc) and assign those details to variables that I can use in another function.
<CapacityIssues xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<IcMDetails Cluster="ClusterA">
<IncidentId>0000001</IncidentId>
<Title>Capacity Issues AA2</Title>
<AssignedTo>DCIM</AssignedTo>
<Description>Cluster A OFR % is X with only 5 Empty nodes.</Description>
<State>Active</State>
<Severity>2</Severity>
<DateCreated>2016-09-10</DateCreated>
</IcMDetails>
<IcMDetails Cluster="ClusterB">
<IncidnetId>0000002</IncidnetId>
<Title>Capacity Issues AA2</Title>
<AssignedTo>DCMx</AssignedTo>
<Description>This is a test</Description>
<State>Active</State>
<Severity>0</Severity>
<DateCreated>2016-10-10</DateCreated>
</IcMDetails>
</CapacityIssues>
Code
public static void Update()
{
XmlTextReader reader = new XmlTextReader(filePath);
while (reader.Read())
{
try
{
if (reader.HasAttributes)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
string s = reader[i];
bool contains = s != null && s.Contains("ClusterA");
if (contains)
{
Console.WriteLine(" {0} and {1}", s, true);
}
}
reader.MoveToElement();
}
}
catch (Exception e)
{
Console.WriteLine($"Cannot load XML, failures detected ruleset as {e.Message}");
}
}
}
Using Linq
btw... watch out for the typo in your sample xml
<IncidnetId>0000002</IncidnetId> incident is misspelled
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace XMLNodeAttributeSearch_41228129
{
class Program
{
static void Main(string[] args)
{
string filepath = #"M:\StackOverflowQuestionsAndAnswers\XMLNodeAttributeSearch_41228129\XMLNodeAttributeSearch_41228129\sample.xml";
Update(filepath);
}
public static void Update(string incomingFilePath)
{
XDocument theDoc = XDocument.Load(incomingFilePath, LoadOptions.None);
List<XElement> ClusterElements = theDoc.Descendants("IcMDetails").ToList();
foreach (XElement item in ClusterElements)
{
if (item.Attribute((XName)"Cluster").Value == "ClusterA")
{
string incidentid = item.Element((XName)"IncidentId").Value;
Console.WriteLine(incidentid);
}
else if (item.Attribute((XName)"Cluster").Value == "ClusterB")
{
string incidentid = item.Element((XName)"IncidentId").Value;
Console.WriteLine(incidentid);
}
}
Console.ReadLine();
}
}
}
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").
I'm trying to edit an xml and then save it with the same name.
I have the following code:
public int ModifyFile(string xmlpath, string option, int returnCode)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlpath);
XmlNode parentNode = xmlDoc.DocumentElement;
if (option.Equals("delete"))
{
returnCode = DeleteTag(parentNode, "identity", returnCode);
}
xmlDoc.Save(xmlpath);
return returnCode;
}
public int DeleteTag(XmlNode root, string deleteName, int returnCode)
{
foreach (XmlNode node in root.ChildNodes)
{
if (node.Name == deleteName)
{
root.RemoveChild(node);
returnCode = 1;
}
else
{
returnCode = DeleteTag(node, deleteName, returnCode);
}
}
return returnCode;
}
I'm getting "The process cannot access the file 'c:\temp\testfile.xml' because it is being used by another process" when it executes xmlDoc.Save(path).
How would I be able to save testfile.xml with the changes made? I need to keep the path and name the same.
public static bool hasIdentityTag(string path)
{
bool isTextPresent = false;
if (File.Exists(path))
{
XmlTextReader rdrXml = new XmlTextReader(path);
do
{
switch (rdrXml.NodeType)
{
case XmlNodeType.Element:
if (rdrXml.Name.Equals("identity"))
{
isTextPresent = true;
rdrXml.Close();
}
break;
}
} while (rdrXml.Read());
}
else
{
Console.WriteLine("The file {0} could not be located", path);
}
return isTextPresent;
}
One option would be to save the new XML to a temporary file, close the XmlDocument and dispose of the object, then move the temporary file back to the right place.
You could try this re-write using LinqToXml:
XElement root = XElement.Load(xmlpath);
bool modified = false;
try
{
switch(option)
{
case "delete":
var toDelete = root.Descendants("identity").ToArray();
foreach(XElement x in toDelete)
{
x.Remove();
modified = true;
returnCode = 1;
}
break;
}
}
finally
{
if(modified)
root.Save(xmlpath);
}
return returnCode;
How about loading the XmlDocument from a Stream instead of by file name? If you still encounter errors, this would indicate that something outside of your method/process is blocking the save.
Try rewriting theModifyFile method like this:
public int ModifyFile(string xmlpath, string option, int returnCode)
{
var fs = File.Open(xmlpath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fs); // use the stream, not file name
fs.Close(); // now close the stream... file should not be locked from this point
XmlNode parentNode = xmlDoc.DocumentElement;
if (option.Equals("delete"))
{
returnCode = DeleteTag(parentNode, "identity", returnCode);
}
xmlDoc.Save(path);
return returnCode;
}