List showing in console - c#

I am adding 2items to my list and I want to look at them in console. But something went wrong, maybe you can help? I think main problem is in foreach loop. Where it says Part can not be found.
class Program
{
static void Main(string[] args)
{
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
}
​
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts { get; set; }
DocConfig()
{
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb", TexLine = #"\include{bbb.tex}" });
this.Parts = new List<DocPart>();
foreach (DocPart part in doc.Parts)
{
Console.WriteLine(part.Title);
Console.ReadLine();
}
}
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
​
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
var config = (DocConfig)serializer.ReadObject(ms);
​
return config;
}
​
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}

Can't you just use linq string.Join(",", my list)?

Related

how to save the List inside the object using linq to xml?

I am trying to save a list of objects with nested lists in XDocument. So how to implement it?
I have a class:
public class Book
{
public string Id { get; }
public string Title { get; set; }
public string Isbn { get; set; }
public List<string> Authors { get; set; }
public int Pages { get; set; }
...
}
And a class to store it all:
public class FileBookStore : IEntryStore<Book>
{
private List<Book> loadedBooks;
private string filename;
...
private static async Task<IEnumerable<Book>> ReadDataAsync(string filename)
{
...
IEnumerable<Book> result = XDocument.Parse(text)
.Root
.Elements("book")
.Select(e =>
new Book
{
Title = e.Attribute("title").Value,
Isbn = e.Attribute("isbn").Value,
Authors = new List<string>() //and here
});
return result;
}
static async Task SaveDataAsync(string filename, IEnumerable<Book> books)
{
XDocument root = new XDocument(
new XElement("catalog",
books.Select(n =>
new XElement("book",
new XAttribute("title", n.Title ?? ""),
new XAttribute("isbn", n.Isbn ?? ""),
//stuck in a line below
new XElement("authors", books.Select(n => new XElement("author"), new XAttribute("name"))),
new XAttribute("pages", n.Pages),
new XAttribute("year", n.Year),
new XAttribute("publisher", n.Publisher ?? "")))));
using (StreamWriter writer = new StreamWriter(filename))
{
await writer.WriteAsync(root.ToString()).ConfigureAwait(false);
}
}
I'm totally hung up on this part. How do I save and load objects to/from the collection?
Change the line you are stuck on to:
//stuck in a line below
new XElement("authors", n.Authors.Select(x => new XElement("author", new XAttribute("name",x)))),

get correct json output from c# class

Please check from Json output i wanted using JavaScriptSerializer. Then check class helper i created using json2csharp.com. Problem is in controller. I am not getting correct output as per my required Jason. I am doing correct in controller? Where the problem can be? Please ask question if you want to know something specific, sorry its hard to describe more clearly.
Helper Class Code:
public class ItemsFromFile
{
public string ASIN { get; set; }
public string Title { get; set; }
public List<Product> products { get; set; }
}
public class ItemsDeatails
{
public List<ItemsFromFile> ItemsFromFile { get; set; }
}
public class File
{
public string nameLocator { get; set; }
public ItemsDeatails itemsDeatails { get; set; }
}
public class RootObject
{
public string Token { get; set; }
public File file { get; set; }
}
Controller code:
if (type == "Salefreaks")
{
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var ItemsFromFile = new ItemsFromFile()
{
products = new List<Product>()
};
var ItemsDeatails = new ItemsDeatails()
{
};
var File = new File()
{
nameLocator = "testimport1"
};
var RootObject = new RootObject()
{
Token = token
};
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems)
{
ItemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
var json = new JavaScriptSerializer().Serialize(RootObject);
}
Required Json Output code:
{
"Token": "7f3099b0-36b1",
"file": {
"nameLocator": "testimport1",
"itemsDeatails": {
"ItemsFromFile": [
{
"ASIN": "B011KVFT9Y",
"Title": "Disney Batman Durable Party Beach Outdoor Adventure Camp Chair w/ Storage Bag"
},
{
"ASIN": "B01D4KRBW2",
"Title": "High Quality Diy Oil Painting Paint Number Kit Theme-Romantic Street A Frameless"
}
]
}
}
}
You can initialize internal objects in the code in the constructor as well.
public class RootObject
{
public string Token { get; set; }
public File file { get; set; }
}
public class File
{
public File()
{
this.itemsDeatails = new ItemsDeatails();
}
public string nameLocator { get; set; }
public ItemsDeatails itemsDeatails { get; set; }
}
public class ItemsDeatails
{
public ItemsDeatails(){
this.ItemsFromFile = new List<ItemsFromFile>();
}
public List<ItemsFromFile> ItemsFromFile { get; set; }
}
public class ItemsFromFile
{
public ItemsFromFile(){
this.products = new List<Product>();
}
public List<Product> products { get; set; }
}
public class Product {
public string ASIN { get; set; }
public string Title { get; set; }
}
Initialize your items properly. And create Root Object from the ground up.
Populate the internal classes first and then later ones.
var itemDetails = new ItemsDeatails();
itemDetails.ItemsFromFile = new ItemsFromFile();
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems)
{
itemDetails.ItemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
var fl = new File(){
nameLocator = "testimport1",
itemsDeatails = itemDetails
}
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var root = new RootObject()
{
Token = token,
file = fl
}
var json = new JavaScriptSerializer().Serialize(root);
Ensure that all your objects are assigned appropriately.
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var RootObject = new RootObject() {
Token = token,
file = new File() {
nameLocator = "testimport1",
itemsDeatails = new ItemsDeatails() {
ItemsFromFile = new List<ItemsFromFile>()
}
}
};
var itemsFromFile = new ItemsFromFile();
itemsFromFile.products = new List<Product>();
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems) {
itemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
RootObject.file.itemsDeatails.ItemsFromFile.Add(itemsFromFile);
var json = new JavaScriptSerializer().Serialize(RootObject);
That being said, it appears that you do not need the list of products inside of the ItemsFromFile class. This definition likely makes more sense:
public class ItemsFromFile {
public string ASIN { get; set; }
public string Title { get; set; }
}
Then your code would be something like this:
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var RootObject = new RootObject() {
Token = token,
file = new File() {
nameLocator = "testimport1",
itemsDeatails = new ItemsDeatails() {
ItemsFromFile = new List<ItemsFromFile>()
}
}
};
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems) {
RootObject.file.itemsDeatails.ItemsFromFile.Add(new ItemsFromFile { ASIN = item.ASIN, Title = item.EbayTitle });
}

How to add more items to my list

I have created list. And it compiles and shows only one item. I need to make it show all my inserted items. For example I try insert one more. How should i do that?
namespace ConsoleApplication5
{
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts;
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
public class Program
{
public static int Main()
{
List<DocPart> Parts = new List<DocPart>();
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts = new List<DocPart>();
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb ", TexLine = #"\include{bbb.tex}" });
foreach (DocPart part in doc.Parts)
{
Console.WriteLine(part.Title);
Console.ReadLine();
Console.ReadKey();
{
return 0;
}
}
return -1;
}
}
}
}
The reason it is only showing one is because your loop over parts is returning from the method and therefore it never gets chance to complete any other iterations.
The solution is to not return early (Remove the return 0;) from this method and instead let it run to the end.
Some other changes I made below were:
Removed the read keys from the for loop. You probably don't want the user to have to press a key every iteration either.
Un-nested classes. Your nested classes also seemed wierd to me and will just lead you to messy code.
namespace ConsoleApplication5
{
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts;
}
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
}
public class Program
{
public static int Main()
{
List<DocPart> Parts = new List<DocPart>();
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts = new List<DocPart>();
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb ", TexLine = #"\include{bbb.tex}" });
foreach (DocPart part in doc.Parts)
{
Console.WriteLine(part.Title);
}
Console.ReadKey();
return -1;
}
}
}

What is best way to include List<> as parameter in class?

I have 2classes and I want to add a list to it. I will use check boxes to fill in my list. But for now how I should create list?
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
}
​
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts { get; set; }
​
public static DocConfig LoadFromString(string jsonData)
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
​
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
var config = (DocConfig)serializer.ReadObject(ms);
​
return config;
}
​
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
I want to create list for example at start for 2 items. I am thinking of this code:
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts = new List<DocPart>();
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}"});
doc.Parts.Add(new DocPart { Title = "bbb", TexLine = #"\include{bbb.tex}" });
how should I do this?
EDIT:
Also how can I display list records in console application?
EDIT:
Maybe I did mistakes in my code:
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts { get; set; }
DocConfig()
{
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb", TexLine = #"\include{bbb.tex}" });
this.Parts = new List<DocPart>()
foreach (Part part in doc.Parts)
{
Console.WriteLine(part.Title);
}
}
add to your DocConfig class this:
DocConfig()
{
this.Parts= new List<DocPart>();
}
and remove
doc.Parts = new List<DocPart>();
also read about constructors, rest of your coud is fine.
EDIT:
to check your list in console you can use foreach loop that is best option to use with List:
foreach (var part in doc.Parts)
{
Console.WriteLine(part.Title);
}

Parsing JSON data in Windows app

Suppose this is my JSON data received through an API:
[
{
"id": "1",
"title": "Test_rom",
"subtitle": "",
"icon": "http://lpl.info/Admin/upload/cat.1.png"
},
{
"id": "2",
"title": "Jewelry",
"subtitle": "",
"icon": "http://lpl.info/Admin/upload/cat.2.png"
},
{
"id": "3",
"title": "Jackets",
"subtitle": "All sizes available",
"icon": "http://lpl.info/Admin/upload/cat.3.png"
}
]
I created a class called "RootObject":
public class RootObject {
public string id { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string icon { get; set; }
}
I only want to extract values of "title" keys from the array. How can I achieve that?
I tried the following code, but I am getting error in "Encoding" word:
var result = await response.Content.ReadAsStringAsync();
RootObject TotalList = new RootObject();
RootObject childlistonly = new RootObject();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(TotalList.GetType());
TotalList = ser.ReadObject(ms) as RootObject;
string category = "";
foreach(var d in TotalList.title) {
category = category + " " + d.ToString() + "\n";
}
ResultsText.Text = category;
I used the following, but it is giving an error:
var titlevariable = myobj.title;
Textblock.Text = titlevariable; // (under a click button method)...
Try this
foreach(var d in TotalList) {
category = category + " " + d.title.ToString() + "\n";
}
#kickaha..
private async void Butoon_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient();
var uri = new Uri("http://www.blabla.com/alliance/App/mobilelogin.php?KG=MA&EM="+Textboxname.Text+"&PA="+password.Password);
var response = await client.GetAsync(uri);
var result = await response.Content.ReadAsStringAsync();
RootObject TotalList = new RootObject();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
RootObject resu = (RootObject)ser.ReadObject(ms);
NavigationContext nav = new NavigationContext()
{
ID = resu.USERID.ToString(),
Name = resu.NAME.ToString(),
Email = resu.EMAIL.ToString()
}
SaveFile();
RestoreFile();
}
private async void SaveFile()
{
StorageFile userdetailsfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserDetails", CreationCollisionOption.ReplaceExisting);
IRandomAccessStream raStream = await userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);
using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
{
// Serialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(NavigationContext));
serializer.WriteObject(outStream.AsStreamForWrite(), nav);
await outStream.FlushAsync();
}
}
private async void RestoreFile()
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("UserDetails");
if (file == null) return;
IRandomAccessStream inStream = await file.OpenReadAsync();
// Deserialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(NavigationContext));
var StatsDetails = (NavigationContext)serializer.ReadObject(inStream.AsStreamForRead());
inStream.Dispose();
string hu = StatsDetails.Name + "\n" + StatsDetails.Email;
// UserName.Text = "Welcome " + StatsDetails.Name;
// UserProfileId = StatsDetails.Id;
resultblock.Text = hu;
}
}
public class RootObject
{
public string USERID { get; set; }
public string EMAIL { get; set; }
public string NAME { get; set; }
public string FIRST_NAME { get; set; }
public string LAST_NAME { get; set; }
public string CITY { get; set; }
}
public class NavigationContext
{
public string ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Email { get; set; }
}
}
i am getting null value in "instream" property of Restorefile() method...

Categories

Resources