Very new to C# and I'm trying to create a list of node data which contains a variable list length of Link data.
class Data
{
public List<Node> Node { get; set; }
}
public class Node
{
public string viewer { get; set; }
public int viewerId { get; set; }
public string log { get; set; }
public List <Link> Link { get; set; }
}
public class Link
{
public string keyName { get; set; }
public int value { get; set; }
}
i have a for loop iterating through the configured nodes and an inner for loop
to grab any configured links.
Data data = new Data();
data.Node = new List<Node>();
I'm doing the following for each new node, which is working how i want it.
data.Node.Add( new Node {
viewer = setup.Device[moduleNr].viewer,
viewerId = setup.Device[moduleNr].viewerId ,
log = setup.Device[moduleNr].log
// how to add one or more lists of Link to this list???
});
The problem i'm having is adding a new list/lists inside the existing data.Node???
Ultimately i would like to achieve the following -
data
|->Node
|->[0]
|->Link
|->[0]
|->keyname
|->value
|->[1]
|->keyname
|->value
|->[2]
|->keyname
|->value
|->log
|->viewerId
|->viewer
|->[1]
|->Link
|->[0]
|->keyname
|->value
|->[1]
|->keyname
|->value
|->log
|->viewerId
|->viewer
|->[2]
|->Link
|->[0]
|->keyname
|->value
|->log
|->viewerId
|->viewer
Would really appreciate some help with this issue - Thanks
You can add a new instance of a List<Link> like this and use the constructor to add new items:
data.Node.Add(new Node {
viewer = setup.Device[moduleNr].viewer,
viewerId = setup.Device[moduleNr].viewerId ,
log = setup.Device[moduleNr].log,
Link = new List<Link>
{
new Link
{
keyName = "Link 1",
value = 0
},
new Link
{
keyName = "Link 2",
value = 1
}
}
});
Related
I have created a class:
internal class Movie
{
public class BaseResponse
{
public Item[] search { get; set; }
public string response { get; set; }
}
public class Item
{
public string title { get; set; }
}
I want to create n objects for search array like this:
public void Generate()
{
Movie.BaseResponse baseResponse = new Movie.BaseResponse();
baseResponse.response = "True!";
baseResponse.search = new Movie.Item[] { new Movie.Item()};
baseResponse.search[0].title = "Title one";
baseResponse.search[1].title = "Title two"; //Error accurs here****
string response = JsonConvert.SerializeObject(baseResponse);
}
but this script does not work right and it gives the following error:
Index was outside the bounds of the array
Can anyone explain how can I create n objects of search array in the Movie class?
Rather than using an array (T[]), you may be better off using a List<T>. You need to know how many items will be in an array up front (since they get allocated contiguously). You can add new items to a List at any time.
Changing your code:
internal class Movie
{
public class BaseResponse
{
public List<Item> Search { get; set; } = new List<Item>();
public string Response { get; set; }
}
public class Item
{
public string Title { get; set; }
}
}
public void Generate()
{
Movie.BaseResponse baseResponse = new Movie.BaseResponse();
baseResponse.Response = "True!";
baseResponse.Search.Add (new Movie.Item { Title = "Title One" });
baseResponse.Search.Add (new Movie.Item { Title = "Title Two" });
string response = JsonConvert.SerializeObject(baseResponse);
}
That seems to work. I get this as response:
{
"Search":[
{"Title":"Title One"},
{"Title":"Title Two"}],
"Response":"True!"
}
You've create an array with 1 item, but you're trying to access the non-existent second item.
Change the relevant line to something like:
baseResponse.search = new Movie.Item[] { new Movie.Item(), new Movie.Item() };
I am trying to convert a html list to xml format with a console application, but i did what i planned and now i dont know how to continue. I will share my code and explain a bit. What i dont know for now , and is confusing me is where the 'magic' happens. Ok i know i have to take that list from the page , read the list with all the tags inside, but what next, how can i transform that list into xml format? I am new to xml i know some basics so please help me.
Here is the application :
static void Main(string[] args)
{
string _url = "http://example.com/media";
int newsCounter = 0;
List<News> _newsList = new List<News>();
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(_url);
HtmlNode ulNode = doc.DocumentNode.SelectSingleNode("//ul[#class='content articles']");
HtmlNodeCollection liNode = ulNode.SelectNodes(".//li");
foreach (HtmlNode node in ulNode.SelectNodes(".//div[#class='article_box']"))
{
var news = new News();
news.Imgsrc = node.FirstChild.SelectSingleNode("//img").Attributes["src"].Value;
var nodes = doc.DocumentNode.FirstChild.SelectNodes("//img[#src]");
foreach (HtmlNode childNode in node.SelectNodes(".//div[#class='box_info']"))
{
// string src = node.SelectSingleNode("//img").Attributes["src"].Value;
foreach(HtmlNode _node in childNode.SelectNodes(".//h3"))
{
news.Link = "";
news.Title = _node.FirstChild.InnerText;
news.Date = _node.NextSibling.NextSibling.InnerText;
news.Text = _node.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
}
}
_newsList.Add(news);
newsCounter++;
}
and also the News class :
public class News
{
public string Imgsrc { get; set; }
public string Title { get; set; }
public string Link { get; set; }
public string Date { get; set; }
public string Text { get; set; }
}
these are all the parameters i have to read from the list.I am able to read them and return all of the news in my list , but what next , how to transform my list into xml format? Any suggestions are welcomed.
There are many way of creating xml. There are not a lot of items in your case so just using Xml linq is very simple. Putting it into a class may produce cleaner code or you can just use the code directly like Sledge suggested.
public class News
{
public string Imgsrc { get; set; }
public string Title { get; set; }
public string Link { get; set; }
public string Date { get; set; }
public string Text { get; set; }
public XElement ToXml()
{
return new XElement("news", new object[] {
new XElement("Imgscr", Imgsrc),
new XElement("Title", Title),
new XElement("Link", Link),
new XElement("Date", Date),
new XElement("Text", Text),
});
}
}
Thanks to everyone guys. I marked 'News' class as Serializable and with a few lines of code managed to generate the xml file. Here is the code, really simple :
XmlSerializer serializer = new XmlSerializer(typeof(List<News>));
using (TextWriter writer = new StreamWriter(#"D:\News.xml"))
{
serializer.Serialize(writer, _newsList);
}
I want to create multi level Json, Using http://json2csharp.com/. I created classes. But not sure how to use it.
public class MassPay
{
public string legal_name { get; set; }
public string account_number { get; set; }
public string routing_number { get; set; }
public string amount { get; set; }
public string trans_type { get; set; }
public string account_class { get; set; }
public string account_type { get; set; }
public string status_url { get; set; }
public string supp_id { get; set; }
public string user_info { get; set; }
}
public class MassPayList
{
public string oauth_consumer_key { get; set; }
public string bank_id { get; set; }
public string facilitator_fee { get; set; }
public IList<MassPay> mass_pays { get; set; }
}
These are my classes and this is Json Format i want to create...
there are extra elements...
{
"oauth_consumer_key":"some_oauth_token",
"mass_pays":[
{"legal_name":"SomePerson1",
"account_number":"888888888",
"routing_number":"222222222",
"amount":"10.33",
"trans_type":"0",
"account_class":"1",
"account_type":"2"
},
{"legal_name":"SomePerson2",
"account_number":"888888888",
"routing_number":"222222222",
"amount":"10.33",
"trans_type":"0",
"account_class":"1",
"account_type":"1"}
]
}
So far i have come up with below code..I am using JObject, and all others wer single level so it was pretty easy. but when it comes to two or three level its difficult.
public JObject AddMassPayRequest(MassPayList lMassPayList, MassPay lMassPay)
{
JObject pin = new JObject(
new JProperty("legal_name", lMassPay.legal_name),
new JProperty("account_number", lMassPay.account_number),
new JProperty("routing_number", lMassPay.routing_number),
new JProperty("amount", lMassPay.amount),
new JProperty("trans_type", lMassPay.trans_type),
new JProperty("account_class", lMassPay.account_class),
new JProperty("account_type", lMassPay.account_type),
new JProperty("status_url", lMassPay.status_url),
new JProperty("supp_id", lMassPay.supp_id),
new JProperty("status_url", lMassPay.status_url),
new JProperty("user_info", lMassPay.user_info)
);
return pin;
}
public JObject AddMassPayRequestList(MassPayList lMassPayList, MassPay lMassPay)
{
JObject pin = new JObject(
new JProperty("mass_pays", lMassPayList.mass_pays),
new JProperty("bank_id", lMassPayList.bank_id),
new JProperty("facilitator_fee", lMassPayList.facilitator_fee),
new JProperty("oauth_consumer_key", lMassPayList.oauth_consumer_key)
);
return pin;
}
Can some one help me how to do this..?
if you're using ASP.NET MVC you just need to use the Json response action using your existing classes.
You could simply do something like this in a controller:
return Json(new { PoId = newPoId, Success = true });
or an actual concrete model class:
var _AddMassPayRequestList = new AddMassPayRequestList();
...
returning a populated instance of your AddMassPayRequestList class:
return Json(_AddMassPayRequestList);
So finally I got this answer, Its simple structure. Using this u can create any type of Json... It doesnt have to follow same structure..
The logic behind this is add things you want at start, create class and inside that properties you want to add into json. SO while passign just add for loop and pass Object to the list.. It will loop through and create JSon for You..
If you have any doubts, let me know happy to help you
public String ToJSONRepresentation(List<MassPay> lMassPay)
{
StringBuilder sb = new StringBuilder();
JsonWriter jw = new JsonTextWriter(new StringWriter(sb));
jw.Formatting = Formatting.Indented;
jw.WriteStartObject();
jw.WritePropertyName("oauth_consumer_key");
jw.WriteValue("asdasdsadasdas");
jw.WritePropertyName("mass_pays");
jw.WriteStartArray();
int i;
i = 0;
for (i = 0; i < lMassPay.Count; i++)
{
jw.WriteStartObject();
jw.WritePropertyName("legal_name");
jw.WriteValue(lMassPay[i].legal_name);
jw.WritePropertyName("account_number");
jw.WriteValue(lMassPay[i].account_number);
jw.WritePropertyName("routing_number");
jw.WriteValue(lMassPay[i].routing_number);
jw.WritePropertyName("amount");
jw.WriteValue(lMassPay[i].amount);
jw.WritePropertyName("trans_type");
jw.WriteValue(lMassPay[i].trans_type);
jw.WritePropertyName("account_class");
jw.WriteValue(lMassPay[i].account_class);
jw.WritePropertyName("account_type");
jw.WriteValue(lMassPay[i].account_type);
jw.WritePropertyName("status_url");
jw.WriteValue(lMassPay[i].status_url);
jw.WritePropertyName("supp_id");
jw.WriteValue(lMassPay[i].supp_id);
jw.WriteEndObject();
}
jw.WriteEndArray();
jw.WriteEndObject();
return sb.ToString();
}
Given this document class:
public class Tea
{
public String Id { get; set; }
public String Name { get; set; }
public TeaType Type { get; set; }
public Double WaterTemp { get; set; }
public Int32 SleepTime { get; set; }
}
public enum TeaType
{
Black,
Green,
Yellow,
Oolong
}
I store a new Tea with the following code:
using (var ds = new DocumentStore { Url = "http://localhost:8080/" }.Initialize())
using (var session = ds.OpenSession("RavenDBFirstSteps"))
{
Tea tea = new Tea() { Name = "Earl Grey", Type = TeaType.Black, WaterTemp = 99d, SleepTime = 3 };
session.Store(tea);
session.SaveChanges();
Console.WriteLine(tea.Id);
}
The tea will be successfully saved, but when I try to query all black teas with linq, I am getting no results:
using (var ds = new DocumentStore { Url = "http://localhost:8080/" }.Initialize())
using (var session = ds.OpenSession("RavenDBFirstSteps"))
{
var dbTeas = from teas in session.Query<Tea>()
where teas.Type == TeaType.Black
select teas;
foreach (var dbTea in dbTeas)
{
Console.WriteLine(dbTea.Id + ": " + dbTea.Name);
}
}
I also tried to save the Enum as Integer with the following command:
ds.Conventions.SaveEnumsAsIntegers = true;
But, the result is the same. All works when I use the Name or the WaterTemp. Does RavenDB supports Enums in this way or I am totally wrong?
It seemed that I got the answer. It is always not recommended to use properties with a name like Type, which can be a reserved keyword.
I renamed Type and everything works, so the answer is:
public class Tea
{
public String Id { get; set; }
public String Name { get; set; }
public TeaType TeaType { get; set; }
public Double WaterTemp { get; set; }
public Int32 SleepTime { get; set; }
}
I need to add a ObservableCollection ObservableCollection within another, is it possible?
Items = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement wid in document.Root.Elements("widget"))
{
WidgetCollectionItem item = new WidgetCollectionItem();
item.nombreWidget = wid.Attribute("caption").Value;
foreach (XElement service in wid.Elements("service"))
{
item.nombreServicio = service.Attribute("caption").Value;
item.valor = service.Element("xvalue").Value;
item.color = service.Element("xcolor").Value;
item.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
Items.Add(item);
}
}
The problem is that each (item.nombreWidget) contains more than one (item.nombreServicio). And I need a ObservableCollection of services within an ObservableCollection of nombreWidget
Yes, you can.
new ObservableCollection<ObservableCollection<WidgetCollectionItem>>()
so you can do something like this:
Items = new ObservableCollection<ObservableCollection<WidgetCollectionItem>>();
foreach (XElement wid in document.Root.Elements("widget"))
{
ObservableCollection<WidgetCollectionItem> services = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement service in wid.Elements("service"))
{
WidgetCollectionItem widget = new WidgetCollectionItem();
widget.nombreWidget = wid.Attribute("caption").Value;
widget.nombreServicio = service.Attribute("caption").Value;
widget.valor = service.Element("xvalue").Value;
widget.color = service.Element("xcolor").Value;
widget.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
services.Add(widget);
}
Items.Add(services)
}
Good idea kindasimple, but still can not show what I want. I grab a xml data, and these want them displayed in a grid
The end result would be this:
nombreWidget1
nombreServicio1
nombreWidget2
nombreServicio2
nombreServicio2
nombreServicio2
If nombreWidget has only one service is fine, but if you have more than one nombreWidget nombreServicio, I can not show well on screen
I need the ObservableCollection
public class WidgetCollectionItem
{
public string nombreWidget { get; set; }
}
Contains an ObservableCollection
public class WidgetServiciosCollectionItem
{
public string nombreServicio { get; set; }
public string valor { get; set; }
public string color { get; set; }
public string alerta { get; set; }
}
Looks like I got what I wanted to achieve, but still does not show me all the data in the grid:
Solution to earlier:
Items = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement wid in document.Root.Elements("widget"))
{
WidgetCollectionItem widget = new WidgetCollectionItem();
widget.nombreWidget = wid.Attribute("caption").Value;
foreach (XElement service in wid.Elements("service"))
{
ServiciosWidgetCollectionItem ser = new ServiciosWidgetCollectionItem();
widget.ItemsSer = new ObservableCollection<ServiciosWidgetCollectionItem>();
ser.nombreServicio = service.Attribute("caption").Value;
ser.valor = service.Element("xvalue").Value;
ser.color = service.Element("xcolor").Value;
ser.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
widget.ItemsSer.Add(ser);
}
Items.Add(widget);
}
public class WidgetCollectionItem
{
public string nombreWidget { get; set; }
public ObservableCollection<ServiciosWidgetCollectionItem> ItemsSer { get; set; }
}
public class ServiciosWidgetCollectionItem
{
public string nombreServicio { get; set; }
public string valor { get; set; }
public string color { get; set; }
public string alerta { get; set; }
}
How do I go also in the data grid ObservableCollection?