I have a list called OrderProductAttributes and I initialzed it like the following:
OrderProductAttributes = new List<OrderProductAttribute>
{orderProductAttribute }
I have to two other nested classes in the OrderProductAttribute and I am trying to instantiate them like the following:
static OrderProductAttribute orderProductAttribute = new OrderProductAttribute()
{
productAttribute = new ProductAttribute()
{
attributeType=new AttributeType()
}
};
I want to see them as a json file and once I open the output json file I see the following:
"OrderProductAttributes":{"["productAttribute":null]"}
I was wondering why the attributeType was not created in the productAttribute since I have initiated it already?
I was expecting to see
"OrderProductAttributes":{"["productAttribute":"attributeType":""]"}
Related
I would like to mock a C# method that returns an Azure.AsyncPageable.
This class has only protected constructors, so I cannot instantiate it directly. Is there any way to create an instance of this class from some other collection, such as an IAsyncEnumerable or just a List?
You can create Page objects using Page<T>.FromValues.
Then, create a AsyncPageable<T> using AsyncPageable<T>.FromPages.
Example:
var page = Page<TableEntity>.FromValues(new List<TableEntity>
{
new TableEntity("1a", "2a"),
new TableEntity("1", "2b")
}, continuationToken: null, new Mock<Response>().Object);
var pages = AsyncPageable<TableEntity>.FromPages(new[] { page });
I'm creating a software on which I added a profiles feature where the user can create profile to load his informations faster. To store these informations, I'm using a JSON file, which contains as much objects as there are profiles.
Here is the format of the JSON file when a profile is contained (not the actual one, an example) :
{
"Profile-name": {
"form_email": "example#example.com",
//Many other informations...
}
}
Here is the code I'm using to write the JSON and its content :
string json = File.ReadAllText("profiles.json");
dynamic profiles = JsonConvert.DeserializeObject(json);
if (profiles == null)
{
File.WriteAllText(jsonFilePath, "{}");
json = File.ReadAllText(jsonFilePath);
profiles = JsonConvert.DeserializeObject<Dictionary<string, Profile_Name>>(json);
}
profiles.Add(profile_name.Text, new Profile_Name { form_email = form_email.Text });
var newJson = JsonConvert.SerializeObject(profiles, Formatting.Indented);
File.WriteAllText(jsonFilePath, newJson);
profile_tr.Nodes.Add(profile_name.Text, profile_name.Text);
debug_tb.Text += newJson;
But when the profiles.json file is completely empty, the profile is successfully written, but when I'm trying to ADD a profile when another one already exists, I get this error :
The best overloaded method match for 'Newtonsoft.Json.Linq.JObject.Add(string, Newtonsoft.Json.Linq.JToken)' has some invalid arguments on the profiles.Add(); line.
By the way, you can notice that I need to add {} by a non-trivial way in the file if it's empty, maybe it has something to do with the error ?
The expected output would be this JSON file :
{
"Profile-name": {
"form_email": "example#example.com",
//Many other informations...
},
"Second-profile": {
"form_email": "anotherexample#example.com"
//Some other informations...
}
}
Okay so I found by reading my code again, so I just replaced dynamic profiles = JsonConvert.DeserializeObject(json); to dynamic profiles = JsonConvert.DeserializeObject<Dictionary<string, Profile_Name>>(json);.
But it still don't fix the non-trivial way I use to add the {} to my file...
The object the first DeserializeObject method returns is actually a JObject, but below you deserialize it as a Dictionary. You shouldn't be mixing the types, choose either one.
If you use the JObject then to add objects you need to convert them to JObjects:
profiles.Add(profile_name.Text, JObject.FromObject(new Profile_Name { form_email = form_email.Text }));
In both cases, when the profile is null you just need to initialize it:
if (profiles == null)
{
profiles = new JObject(); // or new Dictionary<string, Profile_Name>();
}
This question already has answers here:
Return one of two possible objects of different types sharing a method
(6 answers)
Closed 5 years ago.
I am trying to create a Proxy Scraper. For each website I have, I try to scrape the proxies. The scrape code for each website is in a class with the name of the website.
For example:
I have the websites "wwww.proxy.com and www.moreproxy.com"
I have 2 classes: Proxy and MoreProxy with the functions "scrape" that varies for both (since they are different websites).
To get the lists, I do something like this:
//The below code doesn't exist, but just to get my point across
//Each datagrid.Add is in a separate thread
datagrid.Add(new Proxy().scrape());
datagrid.Add(new MoreProxy().scrape());
datagrid.Add(...);
datagrid.Add(...);
//And so on for all the other websites I might add...
Now is there a way to loop this? I was trying something like this, but it does not work:
List<object> objects = new List<object>();
objects.Add(new Proxy(), new MoreProxy(), ..., ...); //I can update this each time I add a new website
foreach(object o in objects)
{
datagrid.Add(o.scrape());
}
The scrape function looks something like this:
public List<string[]> scrape()
{
HtmlDocument PageContent = new HtmlWeb().Load("https://free-proxy-list.net/");
HtmlNode[] nodes = PageContent.DocumentNode.SelectNodes("//td").ToArray();
List<string[]> proxies = new List<string[]>();
for (int i = 0; i < nodes.Length; i += 8)
{
string[] proxy = { nodes[i].InnerHtml, nodes[i + 1].InnerHtml };
proxies.Add(proxy);
}
return proxies;
}
Does something like this exist? Basically I have several classes with a common function scrape. I want to create a list of all these classes as objects, and execute the function scrape. How would I do that (solution needs to be thread safe)
Setup an interface:
public interface IScrape()
{
object Scrape();
}
Have your proxy classes implement the interface:
// repeat for Proxy
public class MyProxy : IScrape{
object Scrape()
{
return something;
}
}
then
List<IScrape> objects = new List<IScrape>();
objects.Add(new Proxy(), new MoreProxy(), ..., ...); //I can update this each time I add a new website
foreach(IScrape o in objects)
{
datagrid.Add(o.Scrape());
}
Interfaces are the problems solution.
Like this:
public interface IScrapable {
void Scrape();
}
public class Proxy : IScrapeable {
public void Scrape() { ...}
}
Now you can Loop and scrape your objects.
List<IScrapable> objects = new List<IScrapable>();
objects.Add(new Proxy(), new MoreProxy(), ..., ...); //I can update this each time I add a new website
foreach(IScrapable o in objects)
{
datagrid.Add(o.scrape());
}
This should do what you want.
I have a problem with passing a list of objects from a WebService to my WinForms app.
I've created a class Osoba in the WebService with a method returning the list of class objects.
The code of this method looks like this by now:
public List<Osoba> ListaOsoba()
{
Osoba nr1 = new Osoba(1,"Name1","Surname1",Uprawnienia.Administrator);
Osoba nr2 = new Osoba(2,"Name2","Surname2",Uprawnienia.Uzytkownik);
Osoba nr3 = new Osoba(3,"Name3","Surname3",Uprawnienia.Uzytkownik);
listaOsób.Add(nr1);
listaOsób.Add(nr2);
listaOsób.Add(nr3);
return listaOsób;
}
In the app, I've added a reference to the WebService, that contains the Osoba class.
My app code looks like this (localhost is my WebService object):
public void SprawdzUprawnienie()
{
foreach (var item in webServiceComarch.ListaOsoba())
{
localhost.Osoba nowaOsoba = new localhost.Osoba();
nowaOsoba(item.indentyfikator, item.imie, item.nazwisko, item.Uprawnienia);
listaOsob.Add(nowaOsoba);
}
}
I get an error
nowaOsoba is a "variable" but is used like a "method".
at the line
nowaOsoba(item.indentyfikator, item.imie, item.nazwisko, item.Uprawnienia);
I've searched through a lot of information on the Web about this kind of problem, but nothing really helped me.
Can anyone help me with this problem? Any tips will be very helpful.
try like this
foreach (var item in webServiceComarch.ListaOsoba())
{
nowaOsoba.indentyfikator = item.indentyfikator;
nowaOsoba.imie = item.imie;
....
....
....
listaOsob.Add(nowaOsoba);
}
try this one
var data= nowaOsoba.nowaOsoba(item.indentyfikator, item.imie, item.nazwisko, item.Uprawnienia);
listaOsob.Add(data);
You need to create a ServiceClient for your WebService and use that client to call the ListaOsoba() method. This should lokk something like that:
var client = new YourWebServiceClient();
var list = client.ListaOsoba();
YourWebServiceClient is a placeholder and will differ acording to the name you have choosen for your actual WebService.
I added a "console" in my game, in which I can type commands, and receive a response (it's based on this). I need to be able to access objects that I instantiate in my Game.cs in my console class. I can't pass them to the constructor, since I don't know how much there will be once the "engine" is done.
I tried using a method to add the objects to a Dictionnary<string, object> but I can't access the properties.
What I'd like to be able to do:
Game1.cs
TileMap tileMap = new TileMap();
BakuConsole console;
...
console = new BakuConsole(this, Content.Load<SpriteFont>("ConsoleFont"));
console.AddRef("tileMap", tileMap);
BakuConsole.cs
public void AddRef(/* some args */) {
// halp!
}
public void Execute(string input) {
switch (input)
{
case "some --command":
console.WriteLine(g.ToString());
// execute stuff, with an object that was added via AddRef()
console.WriteLine("");
console.Prompt(prompt, Execute);
break;
default:
console.WriteLine("> " + input + " is not a valid command.");
console.WriteLine("");
console.Prompt(prompt, Execute);
break;
}
}
I hope I am clear enough. Thanks!
Edit:
I just don't want my constructor to grow too big in case I add more types:
TileMap tileMap = new TileMap();
OtherType1 ot1 = new OtherType1();
OtherType2 ot2 = new OtherType2();
OtherType3 ot3 = new OtherType3();
OtherType4 ot4 = new OtherType4();
OtherType5 ot5 = new OtherType5();
IronPython does exactly what I want to do, and does it via Globals.Add("string", object"). However, I can't seem to find it in the source (of IronPython).
From what you described, you don't actually need a dictionary, you need several properties on some object, probably directly on BakuConsole;
class BakuConsole
{
… // your current code here
public TileMap TileMap { get; set; }
public OtherType1 OtherType1 { get; set; }
…
}
Then, you can set it like this:
console.TileMap = tileMap;
console.OtherType1 = otherType1;
…
And then when you use it, you won't have any problems with accessing properties.
I can see that you are passing a reference of Game to the Console class. Why don't you use that reference to access what you need from the Game class?
You neeed to specify the class name in dictionary of which object you are going to add in dictionary.
Suppose, I had to add "Game1" objects,then we should initialize dictionary in following way...
Dictionary<string, Game1> dicDemo = new Dictionary<string, Game1>();
Game1 objgame1 = new Game1();
dicDemo.Add(string.Empty,objgame1);