How to get specific value from Web Service - c#

I am using Global Weather Web Service in my asp.net application http://www.webservicex.net/globalweather.asmx?op=GetWeather.
The code works fine but I want to get only temperature to be displayed on label.
ServiceReference1.GlobalWeatherSoapClient client = new ServiceReference1.GlobalWeatherSoapClient("GlobalWeatherSoap");
string weather = client.GetWeather("Karachi Airport", "Pakistan");
Label1.Text = weather;
Label control is showing complete data provided by service (i.e Date, Time, Country and city name etc)

According to the link you have provided it returns that string in XML form.
So Use it as below:
var doc = XDocument.Parse(weather); //use .Load if you are pulling an xml file.
var location = doc.Root.Element("Location").Value;
var Temperature = doc.Root.Element("Temperature").Value;
Label1.Text = Temperature;
Just Like above you can get another values too e.g. DewPoint, RelativeHumidity etc
var DewPoint= doc.Root.Element("DewPoint").Value;
var RelativeHumidity = doc.Root.Element("RelativeHumidity ").Value;

You can get it like this also
string weather = client.GetWeather("Karachi Airport", "Pakistan");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(weather );
XmlNodeList elemlist = xmlDoc.GetElementsByTagName("Temperature");
string temp= elemlist[0].InnerXml;

Related

Write on other sharepoint site using webserivces

I have 2 Sharepoint 2013 sites.
When user adding new item in SPList at first SPSite -> starting workflow, what must added copy of item in SPList at second SPSite. This is my code:
public void UpdateSPList(string Title)
{
using (AuthenticationSvc.Authentication authSvc = new AuthenticationSvc.Authentication())
{
try
{
using (ListsSvc.Lists list = new ListsSvc.Lists())
{
list.Url = #"http://second-srharepoint-site.com/_vti_bin/Lists.asmx";
list.CookieContainer = new System.Net.CookieContainer();
list.AllowAutoRedirect = true;
list.PreAuthenticate = true;
list.Credentials = new System.Net.NetworkCredential("domain\\username", "password");
string strBatch = "<Method Cmd='New'><Field Name='Title'>" + Title + "</Field> ";
XmlDocument xmlDoc = new XmlDocument();
XmlElement elBatch = xmlDoc.CreateElement("Batch");
elBatch.SetAttribute("OnError", "Continue");
elBatch.InnerXml = strBatch;
XmlNode ndReturn = list.UpdateListItems("SPListName", elBatch);
}
}
finally
{
}
}
}
But on line elBatch.InnerXml = strBatch; I get exception:
$exception {"Unexpected end of file has occurred. The following elements are not closed: Method. Line 1, position 60."}
System.Exception {System.Xml.XmlException}
I don't know how fix this problem. Help me, please.
First, the string isn't valid XML because the closing Method element is missing. It should be
"<Method Cmd='New'><Field Name='Title'>" + Title + "</Field></Method>"
Second, the ASMX services were deprecated back in 2010. You shouldn't use them for any king of development, especially against SP 2013. The client-side object model (CSOM) is a lot simpler and easier to use. There are a lot of examples in the documentation. The snippet that creates a new item is :
// Starting with ClientContext, the constructor requires a URL to the
// server running SharePoint.
ClientContext context = new ClientContext("http://SiteUrl");
// Assume that the web has a list named "Announcements".
List announcementsList = context.Web.Lists.GetByTitle("Announcements");
// We are just creating a regular list item, so we don't need to
// set any properties. If we wanted to create a new folder, for
// example, we would have to set properties such as
// UnderlyingObjectType to FileSystemObjectType.Folder.
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newItem = announcementsList.AddItem(itemCreateInfo);
newItem["Title"] = "My New Item!";
newItem["Body"] = "Hello World!";
newItem.Update();
context.ExecuteQuery();
No XML fiddling, you simply create a new item, set its properties and call Update

Issue with Xml Project

I'm looking for some help.
I created an mp3 web service using visual studio c# and xml to store the data. I created a method that will allow a user to create a new playlist id to be stored to the xml document. I set my xml file as follows:
public class Service : System.Web.Services.WebService
{
//used as an access path to the xml file
string xmlFileName = "F:\\WebServices\\Mp3Server\\SongList.xml";
This is before any of the methods in my program.
My songlist.xml file is stored correctly and is the correct path from what I can see.
I currently had mp3 id's stored on the songlist.xml file is as follows:
<Playlist ID="123">
<Song Title="Bump">
<Artist>Ed Sheeran</Artist>
<Album>Asylum</Album>
<Year>2011</Year>
<Genre>Folk</Genre>
</Song>
<Song Title="3 AM">
<Artist>Matchbox Twenty</Artist>
<Album>Exile On Mainstream</Album>
<Year>2007</Year>
<Genre>Rock</Genre>
</Song>
</Playlist>
The code I wrote to create a new playlist id is as follows:
//creates a new playlist
[WebMethod]
public string createPlaylistName(string playlistID)
{
string errorMessage = "";
List<string> playlistNames = createPlaylist("/SongList//Playlist/ID");
if (playlistNames.Contains(playlistID))
{
errorMessage = "error! Id already exists";
}
else
{
string xpath = "/SongList/Playlist[#ID'" + playlistID + "']";
XmlDocument doc = new XmlDocument();
doc.Load(xmlFileName);
XmlElement root = doc.DocumentElement;
XmlNode playistNode = root.SelectSingleNode(xpath);
XmlElement playList = doc.CreateElement("Playlist");
XmlAttribute ID = doc.CreateAttribute("ID");
ID.Value = playlistID;
playList.Attributes.Append(ID);
playistNode.InsertAfter(playList, playistNode.LastChild);
doc.Save(xmlFileName);
errorMessage = "success";
}
return errorMessage;
}
But when I run the program, create a new playlist Id and invoke the command: it displays "page not found" webpage.
I can't figure out why the create method is crashing.
If anyone can give any advice, I would appreciate it very much.
Have you tried stepping through it? You'll find that it fails because your XPath expression isn't valid. Your concatenation creates an expression like this:
/SongList/Playlist[#ID'123']
Where it should be:
/SongList/Playlist[#ID='123']
I'm also not entirely sure the logic makes sense. You're checking that a playlist doesn't exist with that ID and then adding one. So how is your XPath expression supposed to return an element?
As an aside, you should probably look into LINQ to XML - it's a much nicer API, for example:
var doc = XDocument.Load(xmlFileName);
var playlist = doc.Descendants("Playlist")
.Single(e => (string)e.Attribute("ID") == "123");
playlist.AddAfterSelf(
new XElement("Playlist",
new XAttribute("ID", "456")
));

Parsing XML String in C#

I have looked over other posts here on the same subject and searched Google but I am extremely new to C# NET and at a loss. I am trying to parse this XML...
<whmcsapi version="4.1.2">
<action>getstaffonline</action>
<result>success</result>
<totalresults>1</totalresults>
<staffonline>
<staff>
<adminusername>Admin</adminusername>
<logintime>2010-03-03 18:29:12</logintime>
<ipaddress>127.0.0.1</ipaddress>
<lastvisit>2010-03-03 18:30:43</lastvisit>
</staff>
</staffonline>
</whmcsapi>
using this code..
XDocument doc = XDocument.Parse(strResponse);
var StaffMembers = doc.Descendants("staff").Select(staff => new
{
Name = staff.Element("adminusername").Value,
LoginTime = staff.Element("logintime").Value,
IPAddress = staff.Element("ipaddress").Value,
LastVisit = staff.Element("lastvisit").Value,
}).ToList();
label1.Text = doc.Element("totalresults").Value;
foreach (var staff in StaffMembers)
{
listBox1.Items.Add(staff.Name);
}
I have printed out the contents of strResponse and the XML is definitely there. However, when I click this button, nothing is added to the listBox1 or the label1 so I something is wrong.
Add Root here to start navigating from the root element (whmcsapi):
string label1_Text = doc.Root.Element("totalresults").Value;

How can I get the LastRunTime for a report using the Business Objects Web Services SDK?

I'm using the Business Objects Web Services SDK to access our Business Objects data. I've successfully got a list of reports, and from that found the LastSuccessfulInstance of a report that has been previously run. However, I can't seem to get the LastRunTime to be populated. When I do a query with no attributes specified it comes back as not set, and I get the same result when I ask for that attribute in particular. I've looked at the report itself and the instance and they both don't have this information. Does anyone know where I can get it from?
Here's my code (hacked from one of SAP's demos):
var sessConnUrl = serviceUrl + "/session";
var boConnection = new BusinessObjects.DSWS.Connection(sessConnUrl);
var boSession = new Session(boConnection);
// Setup the Enterprise Credentials used to login to the Enterprise System
var boEnterpriseCredential = new EnterpriseCredential
{
Domain = cmsname,
Login = username,
Password = password,
AuthType = authType
};
// Login to the Enterprise System and retrieve the SessionInfo
boSession.Login(boEnterpriseCredential);
/************************** DISPLAY INBOX OBJECTS *************************/
// Retrieve the BIPlatform Service so it can be used to add the USER
var biPlatformUrl = boSession.GetAssociatedServicesURL("BIPlatform");
var boBiPlatform = BIPlatform.GetInstance(boSession, biPlatformUrl[0]);
// Specify the query used to retrieve the inbox objects
// NOTE: Adding a "/" at the end of the query indicates that we want to
// retrieve the all the objects located directly under the inbox.
// Without the "/" Path operator, the inbox itself would be returned.
const string query = "path://InfoObjects/Root Folder/Reports/";
// Execute the query and retrieve the reports objects
var boResponseHolder = boBiPlatform.Get(query, null);
var boInfoObjects = boResponseHolder.InfoObjects.InfoObject;
// If the reports contains a list of objects, loop through and display them
if (boInfoObjects != null)
{
// Go through and display the list of documents
foreach (var boInfoObject in boInfoObjects)
{
var report = boInfoObject as Webi;
if (report == null)
continue;
if (!string.IsNullOrEmpty(report.LastSuccessfulInstanceCUID))
{
var instanceQuery = "cuid://<" + report.LastSuccessfulInstanceCUID + ">";
var instanceResponseHolder = boBiPlatform.Get(instanceQuery, null);
var instance = instanceResponseHolder.InfoObjects.InfoObject[0];
}
}
}
Both report.LastRunTimeSpecified and instance.LastRunTimeSpecified are false and both LastRunTime are 01\01\0001, but I can see a last run time in the Web Intelligence UI.
With a little help from Ted Ueda at SAP support I figured it out. Not all the properties are populated by default you need to append #* to the query string to get everything, i.e. change the line:
const string query = "path://InfoObjects/Root Folder/Reports/";
to:
const string query = "path://InfoObjects/Root Folder/Reports/#*";

personalize webpart-problem in giving url to xml file in toolpart

I am creatng a webpart and I am tryng to reference xml from toolpart . I hv created custom properties and its fine if I set the default value to some url otherwise its showing msg fle not found. I want that if its the first time I am loading file it should display the message Open tool part to select the XML.
I m doing lke ths:
private string feedXML;
[Browsable(true),
Personalizable(true),
Category("Example Web Parts"),
DefaultValue(""),
WebPartStorage(Storage.Shared),
FriendlyName("MySetting"),
Description("An example setting")]
public string FeedXML
{
get
{ return feedXML; }
set
{ feedXML = value; }
}
string xmlurl = String.Empty;
string _xsl = string.Empty;
// Load the XML
xmlurl = web.GetFileAsString(GetRelativeURL(feedXML));<---exception as feedXML is null
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlurl);
As the frst time webpart is loadng its quite obvious it wud be feedXML wud be null but I want to display the msg to user "Select XML frm toolpart" as we generally get when we add OOB webpart (like XML Webpart)
Override the CreateChildControls method; if feedXML is null, create a label that says Open tool pane ... and add it to Web Part's Control collection.
Also, check the Creating a Web Part with a Custom Tool Part article.

Categories

Resources