add item into List<string> from another class in c# - c#

I have 3 class. Those are places.cs, onePlace.cs and placestovisit.cs.
placestovisit.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class placestovisit
{
public bool IsDataLoaded { get; set; }
public onePlace sunamganj { get; set; }
public static string basePlaces = "Assets/Places/";
private string baseTanguar = basePlaces + "Tanguar/";
private string baseBaruni = basePlaces + "Baruni/";
public void LoadData()
{
sunamganj = createSunamganj();
IsDataLoaded = true;
}
private onePlace createSunamganj()
{
onePlace data = new onePlace();
data.Items.Add(new places()
{
ID = "0",
Title = "Tanguar Haor",
shortDescription="Tanguar Haor (Lowlaying marsh) is a complex landscape of over 46 marshes, 30 km Northwest of Sunamgonj District.",
itemImage = baseTanguar + "1.jpg",
FullDescription = "Tanguar Haor (Lowlaying marsh) is a complex landscape of over 46 marshes, 30 km Northwest of Sunamgonj District. The marshes are inter connected with one another through narrow Channels but merge into a single large water body during monsoon. The aquatic vegetation and less disturbance from the human are instrument to invite a large variety of waterfowl specially winter migrant ducks that congregates in thousands. Resident and local migrant, raptor, waders and passerine birds made the area as one of the Asia's most potential birding place. Tanguar Haor is listed as a Ramsar site under the Ramsar Convention in 2000."
});
}
}
onePlace.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class onePlace
{
public string Title { get; set; }
public List<places> Items { get; set; }
public onePlace()
{
Items = new List<places>();
}
}
}
places.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class places
{
public string ID { get; set; }
public string Title { get; set; }
public string shortDescription { get; set; }
public string FullDescription { get; set; }
public string itemImage { get; set; }
public List<string>Gallery { get; set; }
}
}
I want to add item into Gallery from placestovisit class. For that what to do?
Actually I want to add one photo gallery for each object. But I am not so much good in OOP. At this moment can I go with this concept or need to change the concept. If I can go with this one then how can I add item into Gallery from placestovisit class?

Gallery is just a property of your places class, and you can add items by accessing that property via an instance of places class.
One thing you should remember that the properties of reference types are null by default, so you need to initialize them.You can do that in your constructor:
public class places
{
public places()
{
Gallery = new List<string>();
}
}
Then you can add new items to your list like:
var plc = new places() { /* set the properties */ }
plc.Gallery.Add("new gallery");

Related

Get List from JSON [duplicate]

This question already has answers here:
Parse JSON response where the object starts with a number in c#
(2 answers)
Closed 1 year ago.
I am trying to get the List from a JSON string from a 3rd party API.
I am not able to understand how should I parse it,as the key name starts with numeric.
I do not need the key but I do require value, but I require the value part in my code to be stored in DB.
JSON
{
"5MIN": [
{
"SETTLEMENTDATE": "2021-08-16T00:30:00",
"REGIONID": "NSW1",
"REGION": "NSW1",
"RRP": 39.27,
"TOTALDEMAND": 7416.02,
"PERIODTYPE": "ACTUAL",
"NETINTERCHANGE": -788.69,
"SCHEDULEDGENERATION": 5518.17,
"SEMISCHEDULEDGENERATION": 1076.47
},
{
"SETTLEMENTDATE": "2021-08-16T01:00:00",
"REGIONID": "NSW1",
"REGION": "NSW1",
"RRP": 36.51,
"TOTALDEMAND": 7288.89,
"PERIODTYPE": "ACTUAL",
"NETINTERCHANGE": -828.1,
"SCHEDULEDGENERATION": 5362.3,
"SEMISCHEDULEDGENERATION": 1064.35
}
]
}
I think I am over complicating the issue, but I am confused
As mentioned in the comments above, you can paste the json as code.
Next you add a reference to Newtonsoft.Json:
dotnet add package newtonsoft.json
You then call JsonConvert.Deserialize<T>() as in the example below:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using StackOverflow;
using System.Linq;
//In this example I load the JSON from disk
var json = File.ReadAllText("/home/timothy/data.json");
var record = JsonConvert.DeserializeObject<ServiceResponse>(json);
//No need to convert to List<T> if you're not going to filter it
var results = record.The5Min.ToList();
foreach(var item in results)
{
Console.WriteLine($"{item.Settlementdate}, {item.Regionid}");
}
namespace StackOverflow
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class ServiceResponse
{
[JsonProperty("5MIN")]
public The5Min[] The5Min { get; set; }
}
public partial class The5Min
{
[JsonProperty("SETTLEMENTDATE")]
public DateTimeOffset Settlementdate { get; set; }
[JsonProperty("REGIONID")]
public string Regionid { get; set; }
[JsonProperty("REGION")]
public string Region { get; set; }
[JsonProperty("RRP")]
public double Rrp { get; set; }
[JsonProperty("TOTALDEMAND")]
public double Totaldemand { get; set; }
[JsonProperty("PERIODTYPE")]
public string Periodtype { get; set; }
[JsonProperty("NETINTERCHANGE")]
public double Netinterchange { get; set; }
[JsonProperty("SCHEDULEDGENERATION")]
public double Scheduledgeneration { get; set; }
[JsonProperty("SEMISCHEDULEDGENERATION")]
public double Semischeduledgeneration { get; set; }
}
}

read XML file to create a 3D model

I have to load the Data from XML (custom but its based on XML file format (URF-8)) and use them to create model in Unity. I used XmlSerializer class, custom creation and tried all XML helps in forums, etc..
I debugged everything (step by step) and everything works fine but after that i always have problem with container. (i have error with reading)
Please, if you have any experince with this, can you tell me what method can be useful for this? ty
XML struct file
here is my try for XMLserializer: (some discriptions of tags XML are commented (tried everything :D)
//load.cs - creating a container
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using UnityEngine;
public class Load
{
//[XmlAttribute("block type")]
public float x_position;
public float y_position;
public float z_position;
}
//[XmlRoot("model version")]
public class Container
{
//[XmlArrayItem("block type")]
public List<Load> Load_container = new List<Load>();
}
//loadFile is main program.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
public class LoadFile: MonoBehaviour
{
public string path;
// Start is called before the first frame update
void Start()
{
var serializer = new XmlSerializer(typeof(Container));
var stream = new FileStream(path, FileMode.Open);
var container_load = serializer.Deserialize(stream) as Container;
stream.Close();
//Debug.Log();
}
// Update is called once per frame
void Update()
{
}
}
Try following :
[XmlRoot("model")]
public class Model
{
[XmlAttribute()]
public string version { get; set; }
[XmlElement("block")]
List<Block> block { get; set; }
}
public class Block
{
[XmlAttribute()]
public string type { get; set; }
public float x_position { get; set; }
public float y_position { get; set; }
public float z_position { get; set; }
}

Error 1 Error 2 on Conference MVC Tutorial

Hi there im following the series of MVC tutorials given by microsoft and i came across this problem:
Error 1 The best overloaded method match for
'System.Data.Entity.DbSet.Add(Conference.Models.Session)'
has some invalid arguments visual studio
2013\Projects\Conference\Conference\Models\ConferenceContextInitializer.cs 18 31 Conference
Error 2 Argument 1: cannot convert from 'Conference.Models.Speaker' to
'Conference.Models.Session' visual studio
2013\Projects\Conference\Conference\Models\ConferenceContextInitializer.cs 19 34 Conference
ConferenceModelInitializer
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Conference.Models
{
public class ConferenceContextInitializer : DropCreateDatabaseAlways<ConferenceContext>
{
protected override void Seed(ConferenceContext context)
{
context.Sessions.Add(
new Session()
{
Title = "I Want Spaghetti",
Abstract = "The Life and times of a spaghetti lover",
Speaker = context.Speakers.Add(
new Speaker()
{
Name = "Jon Pepe",
EmailAddress = "jon#asfdasd.com"
})
});
context.SaveChanges();
}
}
}
ConferenceContext
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Conference.Models
{
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Session> Speakers { get; set; }
}
}
Thank you!
replace:
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Session> Speakers { get; set; }
}
with:
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Speaker> Speakers { get; set; } //since you are referencing the speaker class here
}

Get value from json data using c#

I am creating a project of Windows Forms Application using C#
I want to show all information(like CityName,CountryCode, etc in different Label) related to IP Address that is on my TextBox.
I already read many article about JsonConvert and I don't want to use JsonConvert.
here is my c# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
namespace GetIPinfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List<LocaionInfo1> locations = new List<LocaionInfo1>();
string url = string.Format("http://ipinfo.io/" + txtip.Text);
using (WebClient client = new WebClient())
{
string json = client.DownloadString(url);
LocaionInfo1 location = new JavaScriptSerializer().Deserialize<LocaionInfo1>(json);
locations.Add(location);
}
if (locations.Count > 0)
{
foreach (LocaionInfo1 loc in locations)
{
label9.Text = loc.CityName;
label10.Text = loc.CountryCode;
label11.Text = loc.CountryName;
}
}
}
public class LocaionInfo1
{
public string IPAddress { get; set; }
public string CountryName { get; set; }
public string CountryCode { get; set; }
public string CityName { get; set; }
public string RegionName { get; set; }
public string ZipCode { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string TimeZone { get; set; }
}
}
}
The problem is that when i Debug this code and Enter IP in my TextBox and then click on Submit Button
My LocaionInfo1 location = new JavaScriptSerializer().Deserialize<LocaionInfo1>(json);
is NULL values.
JSON Data is:
{
"ip": "182.69.151.41",
"hostname": "abts-north-dynamic-041.151.69.182.airtelbroadband.in",
"city": null,
"country": "IN",
"loc": "20.0000,77.0000",
"org": "AS24560 Bharti Airtel Ltd., Telemedia Services"
}
So please help to get these all values.
I am using Visual Studio 2012.
So I can't actually try this because I'm on mobile but for the actual JSON you'd have to add a "/json" to the link
string url = string.Format("http://ipinfo.io/" + txtip.Text + "/json");
You need to help json.net out a bit by giving some mapping by using an attribute on your object properties:
public class LocaionInfo1
{
[JsonProperty(PropertyName = "ip")]
public string IPAddress { get; set; }
....
}
Your property names are inconsistent. For example, in the JSON you have "city" but in your object it is "CityName." How is the deserializer supposed to know how to map them?

Entity Framework 5 Won't Fetch Relationships With Include()

I am quite certain that questions like this have been answered a number of times before, but I can't get any of the suggestions to work.
I am building a MVC 4 application with Entity Framework 5, where the entities were generated from existing tables. I have entity classes that look like this:
namespace RebuildingModel
{
using System;
using System.Collections.Generic;
public partial class StandardCodeTable
{
public StandardCodeTable()
{
this.StandardCodeTableTexts = new HashSet<StandardCodeTableText>();
}
public int TableCode { get; set; }
public string RefTableName { get; set; }
public virtual ICollection<StandardCodeTableText> StandardCodeTableTexts { get; set; }
}
}
namespace RebuildingModel
{
using System;
using System.Collections.Generic;
public partial class StandardCodeTableText
{
public int TableCode { get; set; }
public string LanguageCode { get; set; }
public string TextVal { get; set; }
public virtual StandardCodeTable StandardCodeTable { get; set; }
}
}
namespace RebuildingSite.Models
{
public class CodeTableJoined
{
public int TableCode { get; set; }
public string ReferenceTableName { get; set; }
public string LanguageCode { get; set; }
public string TextValue { get; set; }
}
}
I have a DAO that looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RebuildingModel.Dao
{
public class CodeTableDao
{
public CodeTableDao() { }
public ISet<StandardCodeTableText> GetCode(string refTableName)
{
HashSet<StandardCodeTableText> codes = new HashSet<StandardCodeTableText>();
using (var db = new RebuildingTogetherEntities())
{
db.StandardCodeTableTexts.Include("StandardCodeTables");
var query = from c in db.StandardCodeTableTexts
where c.StandardCodeTable.RefTableName == refTableName
orderby c.TableCode
select c;
foreach (var item in query)
{
codes.Add(item);
}
}
return codes;
}
}
I have a controller that looks like this:
namespace RebuildingSite.Controllers
{
public class CodeTableController : Controller
{
public ActionResult Index(string refTableName)
{
CodeTableDao dao = new CodeTableDao();
ICollection<StandardCodeTableText> codes = dao.GetCode(refTableName);
HashSet<CodeTableJoined> joins = new HashSet<CodeTableJoined>();
foreach (var code in codes)
{
CodeTableJoined join = new CodeTableJoined();
join.TableCode = code.TableCode;
join.LanguageCode = code.LanguageCode;
join.TextValue = code.TextVal;
join.ReferenceTableName = code.StandardCodeTable.RefTableName;
joins.Add(join);
}
ISet<string> refTableNames = dao.GetReferenceTables();
ViewBag.RefTableNames = refTableNames;
return View(joins);
}
}
}
When I run the view attached to the controller, an ObjectDisposedException is thrown at this line, where the relationship is used:
join.ReferenceTableName = code.StandardCodeTable.RefTableName;
This has to be something simple. What am I doing wrong? I have tried adding that Include() call in from the context in many different places, even multiple times.
I've also tried adding an explicit join in the Linq query. I can't get EF to fetch that relationship.
Copying my comment to an answer - Put the include be in the actual query
var query = from c in
db.StandardCodeTableTexts.include("StandardCodeTables"). where
c.StandardCodeTable.RefTableName == refTableName orderby c.TableCode
select c;

Categories