I'm not sure if this is correct, but trying to learn MVVM, how it works, etc.
Currently, the example used to load the data is:
this.SavedItems.Add(new SavedBoard() { ID= "1098", UserDescription = "Test" });
I want to parse XML and load data from there.
This is the c# code I've been trying but doesn't seem to work:
XDocument doc = XDocument.Load("savedstops.xml");
var data = from query in doc.Descendants("Stops")
select new SavedBoard
{
ID = query.Element("ID").Value,
UserDescription = query.Element("UserDescription").Value
};
this.SavedItems.Add(data);
And this is the XML file:
<Stops>
<Stop>
<ID>1022</ID>
<UserDescription>Test</UserDescription>
</Stop>
<Stop>
<ID>1053</ID>
<UserDescription>Test1045</UserDescription>
</Stop>
</Stops>
Where am I going wrong? I also get an error Error "Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable'. 'Select' not found. Are you missing a reference or a using directive for 'System.Linq'?"
Though I'm thinking the error isn't the reason it's not working, but rather the code logic itself.
Thanks in advance!
Use doc.Descendants("Stop") (or doc.Root.Elements("Stop")) instead of Stops, and include the System.Linq namespace with adding: using System.Linq; top of your code.
Related
I'm a beginner at writing and understanding C#. I would like to know how to reuse some code I have that updates a WebService username and password credentials.
Here is code in 1st cs File:
...
public class AuthenticateLogin
{
public static object PassCredentials()
{
ServiceName.UsersClient clientauthentication = new ServiceName.UsersClient();
clientauthentication.ClientCredentials.UserName.UserName = "user";
clientauthentication.ClientCredentials.UserName.Password = "pwd";
}
}
...
Here is code in 2nd cs File:
var test = AuthenticateLogin.PassCredentials();
Console.WriteLine(test.EchoAuthenticated("Successful Login"));
Error Received:
Error CS1061 'AuthenticateLogin' does not contain a definition for 'EchoAuthenticated' and no accessible extension method 'EchoAuthenticated' accepting a first argument of type 'AuthenticateLogin' could be found (are you missing a using directive or an assembly reference?)
Solution desired:
In the second file, I want to be able to use the methods in the 'clientauthentication' of the first file. I need to be able to use the 'clientauthentication' like a common object in multiple other cs files. FYI: I can use the 'clientauthentication' methods fine in the 1st file and it works okay.
I'm trying to read a json string into memory and get this undocumented error msg
$ mcs -r:FortnoxAPILibrary.dll -r:npgsql.dll -r:System.Data.dll -r:Newtonsoft.Json.dll Vouchers.cs
Vouchers.cs(44,18): error CS0103: The name `JArray' does not exist in the current context
Compilation failed: 1 error(s), 0 warnings
My code is
var json = System.IO.File.ReadAllText("test.json");
var objects = JArray.Parse(json); // parse as array
foreach(JObject root in objects)
{
foreach(KeyValuePair<String, JToken> app in root)
{
var appName = app.Key;
var description = (String)app.Value["Description"];
var value = (String)app.Value["Value"];
Console.WriteLine(appName);
Console.WriteLine(description);
Console.WriteLine(value);
Console.WriteLine("\n");
}
}
Where is it documented how this should work?
You are more than likely missing a using statement.
using Newtonsoft.Json.Linq;
Every piece of C# code you write, except for core types, requires a using statement pointing to any dependencies.
C# libraries often don't document the using statement requirements for a block of code. Maybe an oversight, but most users are using an IDE, which warns of the missing statement and offers options to automatically insert them.
It is not documented that I must include this line.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
I am a student studying Computer Engineering in University, and I am trying to develop an application that will read an rss feed from a certain url, then display the titles and links of each item in the feed as a notification whenever a the feed on the url is updated.
Well, I am actually at the very beginning, and I am working on this project for learning purposes, following some tutorials etc.
My plan was to use System.ServiceModel.Syndication library to read the rss feed from the url using the SyndicationFeed object and its methods. But whenever I try to use that I get a strange error. The error is as follows
--- CS0012: The type 'XmlReader' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Xml, Version=5.0.5.0',Culture=neutral, PublicKeyToken='7cec85d7bea7798e'.
Here is the part of code that this error is shown:
public void GetFeed()
{
// Create an xml reader that will read rss data from the given url
var xmlReader = XmlReader.Create(rssUrl);
syndicationFeed = SyndicationFeed.Load(xmlReader);
}
The part where I create the xmlReader has no errors, I also have the following assembly referenced, 'System.Xml'.
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel.Syndication;
using System.Xml; // Here is the System.Xml
Also, trying to add a refenrence to the said library (System.Xml) by right clicking and selecting 'Add Reference' just gives me another error, telling me that I cannot refenrence 'System.Xml' as it is already being referenced by the build system.
I tried using other classes from the System.ServiceModel.Syndication namespace to ensure that the problem is not with the assembly, and every other class, method, etc. worked without errors. For example, I am able to write this and get no error:
SyndicationItem item = new SyndicationItem();
item.Title = new TextSyndicationContent("Me");
item.Links.Add(new SyndicationLink() { Uri = new Uri("http://somesite.con") });
item.PublishDate = DateTime.Now;
I get no errors on the above piece of code. I don't get errors when I use XmlReader like this for example:
var reader = XmlReader.Create(rssUrl);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Attribute:
// Some code here
break;
// Some more cases here......
}
}
I get no errors here about the XmlReader either. I only get the error when passing an instance of XmlReader to a SyndicationFeed.Load(XmlReader instance) method.
// This always gives me error!!!
syndicationFeed = SyndicationFeed.Load(xmlReader);
I have been trying to solve this problem for quite a while now, nearly 6 hours, I searched on the web, referenced different versions of System.ServiceModel.Syndication.dll, trying to find Syndication packages on Nuget package manager. Nothing worked. I am asking this question here as a last resort, and any help would be greatly appreciated.
UWP apps use the Windows Runtime class Windows.Web.Syndication.SyndicationFeed rather than .Net's System.ServiceModel.Syndication.
Windows.Web.Syndication.SyndicationFeed doesn't have an XmlReader constructor. Generally you'll create a SyndicationClient and then call RetrieveFeedAsync(url) to get the SyndicationFeed.
See How to access a web feed (XAML) for a full walkthrough.
I am using RazorEngine for email templating. I have introduced Take() method into the template. I did this so the authors can dictate how many records they want without us having to change any C# in our code directly. I have tried adding the using statements to the template itself as well as using the fluent configuration and adding the namespaces needed but I am not having any luck.
Error:
'System.Collections.Generic.List<object>' does not contain a definition for 'Take'
Here is my fluent configuration for RazorEngine:
var config = new FluentTemplateServiceConfiguration(c =>
c.IncludeNamespaces(
"System",
"System.Linq",
"System.Collections",
"System.Collections.Generic"));
using (var service = new TemplateService(config))
{
//Razor.SetTemplateService(service);
dynamic dyModel = model;
var parsed = string.IsNullOrEmpty(cacheName)
? service.Parse(template, dyModel,null, cacheName)
: service.Parse(template, dyModel,null,null);
return parsed;
}
If I purposely state a namespace incorrectly, I do get an error saying it couldn't find it so I know that it is processing the config data but despite that, I am still getting the error.
Any ideas on what I am doing wrong? I am passing in a dynamic model which either is a List or has a List on it.
So this was kinda lame, there is a ticket on RazorEngine's wiki that states this was fixed, so either I am using it wrong or it hasn't been fixed but this is what I had to do to get it working in the razor file.
var topFive = ((List<dynamic>) Model.MyList).Take(5);
Trying to use Linq to XML for the first time and having some problems. I have this XML file that needs to be read and used for various tasks. The file contains a list of entities called 'interfaces'. To start with I want to display a list of names of these interfaces.
Here is the XML file:
<?xml version="1.0" encoding="utf-8" ?>
<InterfaceList>
<Interface>
<InterfaceName>Account Lookup</InterfaceName>
<RequestXSD>ALREQ.xsd</RequestXSD>
<ResponseXSD>ALRES.xsd</ResponseXSD>
</Interface>
<Interface>
<InterfaceName>Balance Inquiry</InterfaceName>
<RequestXSD>BIREQ.xsd</RequestXSD>
<ResponseXSD>BIRES.xsd</ResponseXSD>
</Interface>
</InterfaceList>
Here is the query code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Stub {
public class InterfaceList : XElement {
public void GetInterfaceNameList() {
var v = from interface in this.Elements("Interface")
select interface.Element("InterfaceName").Value;
}
}
}
The idea is to load InterfaceList from the file, and then to use it to query any I may need.
The problem is that I'm getting error message for everything in the query. here are a few of them:
Error 14 The name 'from' does not exist in the current context
Error 15 The type or namespace name 'select' could not be found (are
you missing a using directive or an assembly reference?)
Error
Error 16 'System.Xml.Linq.XElement.Value' is a 'property' but is used
like a 'type'
What's wrong here?
If you want to call your variable 'interface' (which is a reserved word) you will need to escape it, like this:
var v = from #interface in this.Elements("Interface")
select #interface.Element("InterfaceName").Value;
Probably better to just rename it though....