Coding in C#, I am blocked on a silly JSON deserialization and hoping your expert eyes will find what I'm missing.
I am trying to extract the following JSON file:
{
"Document":
{
"Version": "1.0.0",
"LastUpdate": "10.08.2020",
"Description": "This document enumarates manufactuer capabilities",
"Id": ""
},
"Capacities": [
{
"Id": 0,
"Description": "",
"Enable": true,
"RelativePath": "Company1\\manifest.json"
},
{
"Id": 1,
"Description": "",
"Enable": true,
"RelativePath": "Company2\\manifest.json"
}
]
}
The ManifestDescriptor class should self-extract (and store) JSON data through its constructor call. The implementation is as follow:
using JsonTools;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Serilog;
using SessionService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace BaseService.Manifest
{
public class ManifestDescriptor : JObject
{
/// <summary>
/// Contains Json document descriptor data
/// </summary>
private DocSection _document;
private List<Capacity> _capacity;
/// <summary>
/// Contains Json document descriptor data
/// </summary>
[JsonProperty("Document")]
public DocSection Document
{
get => _document;
set
{
if (value != _document)
{
_document = value;
}
}
}
/// <summary>
/// Contains document capacities
/// </summary>
[JsonProperty("Capacities")]
public List<Capacity> Capacities
{
get => _capacity;
internal set
{
if (value != _capacity)
{
_capacity = value;
}
}
}
public ManifestDescriptor(string absolutePath)
{
string l_rawJson = string.Empty;
if (File.Exists(absolutePath))
{
_fileInfo = new FileInfo(absolutePath);
if (!JsonParser.LoadJsonFile(absolutePath, ref l_rawJson))
{
Log.Error("Could not extract Json file data.");
return;
}
// Populate current class with manifest data
JsonConvert.PopulateObject(l_rawJson, this);
}
else Log.Warning("Given manifest file do not exist: \n\r {0}", absolutePath);
}
}
}
ManifestDescriptor contains a Document property implemented as follow:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
namespace BaseService.Manifest
{
/// <summary>
/// Class container giving Json document version & its utility
/// </summary>
public class DocSection
{
private Version _version;
private DateTime _lastUpdate;
private string _description;
private string _id;
private string _class;
/// <summary>
/// Contains document version
/// </summary>
[JsonProperty("Version")]
public Version Version
{
get => _version;
internal set
{
if (value != _version)
{
_version = value;
}
}
}
/// <summary>
/// Contains last update document version
/// </summary>
[JsonProperty("LastUpdate")]
public DateTime LastUpdate
{
get => _lastUpdate;
internal set
{
if(value != _lastUpdate)
{
_lastUpdate = value;
}
}
}
/// <summary>
/// Contains document description
/// </summary>
[JsonProperty("Description")]
public string Description
{
get => _description;
internal set
{
if(value != _description)
{
_description = value;
}
}
}
/// <summary>
/// Contains document ID
/// </summary>
[JsonProperty("Id")]
public string Id
{
get => _id;
internal set
{
if (value != _id)
{
_id = value;
}
}
}
/// <summary>
/// Object class type to instanciate regarding capacity data of the document
/// </summary>
[JsonIgnore]
[JsonProperty("Class")]
public string Class
{
get => _class;
internal set
{
if(value != _class)
{
_class = value;
}
}
}
}
}
However when reaching the line JsonConvert.PopulateObject(l_rawJson, this); called in ManifestDescriptor class constructor, I am reaching the following execption:
Cannot populate JSON object onto type
'BaseService.Manifest.ManifestDescriptor'. Path 'Document', line 2,
position 13."
May you have an idea of the issue?
Thanks for your attention,
As per #SelimYildiz, you really need to separate the population of objetc outside of the object you are trying to serialize.
If your intention is to serialize your ManifestDescriptor without knowing the process of it all you need is to past your json. Then you can create a wrapper class that will do the thing.
What is your intention of making the ManifestDescriptor inherit a JObject?
This might give you a hint, for this sample demo I didn't inherit the JObject and instead of JsonConvert.PopulateObject I used JsonConvert.Deserialized.
Wrapper Class
public class ParserWrapper<T>
where T : new()
{
private FileInfo _fileInfo;
public T ParsedObject { get; set; }
public ParserWrapper(string absolutePath)
{
string l_rawJson = string.Empty;
if (File.Exists(absolutePath))
{
_fileInfo = new FileInfo(absolutePath);
if (!JsonParser.LoadJsonFile(absolutePath, ref l_rawJson))
{
System.Diagnostics.Debug.Write("Could not extract Json file data.");
return;
}
// Populate current class with manifest data
ParsedObject = JsonConvert.DeserializeObject<T>(l_rawJson);
}
else System.Diagnostics.Debug.Write("Given manifest file do not exist: \n\r {0}", absolutePath);
}
}
ManifestorDescriptor
public class ManifestDescriptor
{
private DocSection _document;
private List<Capacity> _capacity;
[JsonProperty("Document")]
public DocSection Document
{
get => _document;
set
{
if (value != _document)
{
_document = value;
}
}
}
[JsonProperty("Capacities")]
public List<Capacity> Capacities
{
get => _capacity;
internal set
{
if (value != _capacity)
{
_capacity = value;
}
}
}
}
Implementation
var obj = new ParserWrapper<ManifestDescriptor>("json1.json");
Output:
Thanks for your attention. Combined comments help me to find out the issue. Coming back from #Rahul Sharma code answer and drawing back towards my original code, I could detect the two following issues:
Setter should not be declared as internal otherwise JsonConvert.PopulateObject(...) function will end with a nullable object.
I've set ManifestDescriptor class as child of Jobject. Removing the parent seems to resolve the raised exception I get.
The working code is then:
ManifestDescriptor class:
public class ManifestDescriptor
{
/// <summary>
/// Manifest file information field
/// </summary>
private FileInfo _fileInfo;
/// <summary>
/// Contains Json document descriptor data
/// </summary>
private DocSection _document;
private List<Capacity> _capacity;
/// <summary>
/// Manifest file information
/// </summary>
public FileInfo FileInfo
{
get => _fileInfo;
set
{
if(value != _fileInfo)
_fileInfo = value;
}
}
/// <summary>
/// Contains Json document descriptor data
/// </summary>
[JsonProperty("Document")]
public DocSection Document
{
get => _document;
set
{
if (value != _document)
{
_document = value;
}
}
}
/// <summary>
/// Contains document capacities
/// </summary>
[JsonProperty("Capacities")]
public List<Capacity> Capacities
{
get => _capacity;
internal set
{
if (value != _capacity)
{
_capacity = value;
}
}
}
public ManifestDescriptor(string absolutePath)
{
string l_rawJson = string.Empty;
if (File.Exists(absolutePath))
{
_fileInfo = new FileInfo(absolutePath);
if (!JsonParser.LoadJsonFile(absolutePath, ref l_rawJson))
{
Log.Error("Could not extract Json file data.");
return;
}
// Populate current class with manifest data
JsonConvert.PopulateObject(l_rawJson, this);
}
else Log.Warning("Given manifest file do not exist: \n\r {0}", absolutePath);
}
}
DocSection class (Document property):
/// <summary>
/// Class container giving Json document version & its utility
/// </summary>
public class DocSection
{
private Version _version;
private DateTime _lastUpdate;
private string _description;
private string _id;
private string _class;
/// <summary>
/// Contains document version
/// </summary>
[JsonProperty("Version")]
public Version Version
{
get => _version;
set
{
if (value != _version)
{
_version = value;
}
}
}
/// <summary>
/// Contains last update document version
/// </summary>
[JsonProperty("LastUpdate")]
public DateTime LastUpdate
{
get => _lastUpdate;
set
{
if(value != _lastUpdate)
{
_lastUpdate = value;
}
}
}
/// <summary>
/// Contains document description
/// </summary>
[JsonProperty("Description")]
public string Description
{
get => _description;
set
{
if(value != _description)
{
_description = value;
}
}
}
/// <summary>
/// Contains document ID
/// </summary>
[JsonProperty("Id")]
public string Id
{
get => _id;
internal set
{
if (value != _id)
{
_id = value;
}
}
}
}
Related
This question already has answers here:
Why does Property Set throw StackOverflow exception?
(3 answers)
Closed 2 years ago.
I designed a class implementing the Builder design pattern. But creating that class using its builder, it throws System Exception that is StackOverFlow Exception. I know its builder is recursive but I only call three times its building chain. What throwing I really don't understand and it doesn't come to me logically. Below is my class that involves its own builder.
SnirgeeDosya sn = new SnirgeeDosya.SnirgeeDosyaBuilder()
.setDosyaId(0)
.setDosyaAdi("Dosya1")
.setUserId(1214)
.setDBFactory(new DatabaseFactory()).build();
public class SnirgeeDosya:ISnirgeeDosyaOracleCommands
{
public int dosyaId { set { dosyaId = value; } get { return dosyaId; } }
public int userId { set { userId = value; } get { return userId; } }
public DateTime baslangicZaman { get { return DateTime.Now; } }
public String dosyaAdi { set { dosyaAdi = value; } get { return dosyaAdi; } }
private SnirgeeOracleDBWorker oracleDbWorker{ set { oracleDbWorker = value; } get { return oracleDbWorker; } }
/// <summary>
/// SnirgeeDosya olusturması sırasında kullanılır. ilgili parametreler girildikten sonra build edilip SnirgeeDosya elde edilir. Kullanım şekli aşağıdaki gibidir.
/// SnirgeeDosya sn = new SnirgeeDosya.SnirgeeDosyaBuilder().setDosyaAdi("Dosya1").setUserId(1214).setDBFactory(new DatabaseFactory()).build();
/// </summary>
public class SnirgeeDosyaBuilder
{
public int dosyaId { set { dosyaId = value; } get { return dosyaId; } }
public int userId { set { userId = value; } get { return userId; } }
public String dosyaAdi { set { dosyaAdi = value; } get { return dosyaAdi; } }
public SnirgeeOracleDBWorker oracleDbWorker { set { oracleDbWorker = value; } get { return oracleDbWorker; } }
/// <summary>
/// Dosya Builder içerinde dosya adının belirlenmesi.
/// </summary>
/// <param name="dosyaadi"></param>
/// <returns></returns>
public SnirgeeDosyaBuilder setDosyaAdi(String dosyaadi)
{
this.dosyaAdi = dosyaadi;
return this;
}
/// <summary>
/// Dosya Builder içerinde SnirgeeDosyasının kime ait olduğunu belirten metotdur.
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public SnirgeeDosyaBuilder setUserId(int userid)
{
this.userId = userid;
return this;
}
/// <summary>
/// Dosya Builder içerinde SnirgeeDosyasının kime ait olduğunu belirten metotdur.
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public SnirgeeDosyaBuilder setDosyaId(int dosyaId)
{
this.dosyaId = dosyaId;
return this;
}
/// <summary>
/// Snirgee Dosyasının içerisine Veritabanı işlemleri yapan classın eklenmesi.
/// Elementlerin yazılması ve okunması sırasında bu class içerisinde kullanılacaktır.
/// </summary>
/// <param name="db"></param>
/// <returns></returns>
public SnirgeeDosyaBuilder setDBFactory(DatabaseFactory db)
{
this.oracleDbWorker = new SnirgeeOracleDBWorker(db);
return this;
}
/// <summary>
/// dosyaAdı, kullanıcıId ve Veritabanı işlerini yapacak DatabaseFactory parametreleri atandıktan sonra Snirgee Dosyasını oluşturan methodtur.
/// Henüz veritabanı SnirgeeDosya tablosuna herhangi bir kayıt atanmaz.
/// </summary>
/// <returns></returns>
public SnirgeeDosya build()
{
return new SnirgeeDosya(this);
}
}
/// <summary>
/// SnirgeeDosya'sını oluşturan SnirgeeDosyaBuilder classı build metodu içerisinde kullanılır.
/// </summary>
/// <param name="formBuilder"></param>
private SnirgeeDosya(SnirgeeDosyaBuilder formBuilder)
{
this.dosyaId = formBuilder.dosyaId;
this.userId = formBuilder.userId;
this.dosyaAdi = formBuilder.dosyaAdi;
this.oracleDbWorker = formBuilder.oracleDbWorker;
}
}
Common mistake. Your property is calling itself in the getter/setter. So when you set dosyaId, it sets dosyaId, which sets dosyaId, which sets dosyaId, which... until the call stack is full and you get a StackOverflowException.
Change
public int dosyaId { set { dosyaId = value; } get { return dosyaId; } }
to
public int dosyaId { set; get; }
And the same for the other properties. I see no need for you to have a backing field based on what you've posted. In fact, I see no need for the set... methods either - you can just set the properties directly.
It's an infinite loop - in the property, you're setting the property, which calls the property setter, which sets the property, etc. until the exception.
Either create a member variable (with a different name, this is known as a backing field) that the property sets and gets, or, since these are very simple properties, make them auto-implemented:
public int dosyaId { get; set; }
I have a requirement to create a nested configuration section. The issue is that I need to write an application that accesses any number of databases. These could be oracle, sql, or anything else... I want to make my config section look like this:
<connectionconfigurations>
<databaseConnection dbname="connection1" dbsourceConnect="connectionstring1" provider="sql">
<sqlQueries>
<add name="querynumber1"
sqlFilePath="C:\Users\me\Desktop\sql"/>
<add name="querynumber2"
sqlFilePath="C:\Users\me\Desktop\sql"/>
</sqlQueries>
</databaseConnection>
<databaseConnection dbname="connection1" dbsourceConnect="connectionstring2" provider="oracle">
<sqlQueries>
<add name="querynumber3"
sqlFilePath="C:\Users\me\Desktop\oracle"/>
<add name="querynumber4"
sqlFilePath="C:\Users\me\Desktop\oracle"/>
</sqlQueries>
</databaseConnection>
</connectionconfigurations>
The issue is that I am having trouble accessing all my parameters. How do I create nested config sections like this and access them through code?
I've made a class like this to handle the connection section:
public class Connectionconfigurations : ConfigurationSection
{
private static ConfigurationPropertyCollection _connectionConfiguration;
private static ConfigurationPropertyCollection _sqlQueries;
private static ConfigurationPropertyCollection _properties;
static Connectionconfigurations()
{
_connectionConfiguration = new ConfigurationProperty(
ConfigConstants.CONFIG_DATABASECONNECTION,
typeof(DatabaseConnectionElementCollection),
null,
ConfigurationPropertyOptions.IsRequired);
_sqlQueries = new ConfigurationProperty(
ConfigConstants.CONFIG_SQLQUERIES,
typeof(DatabaseConnectionElementCollection),
null,
ConfigurationPropertyOptions.IsRequired);
_properties = new ConfigurationPropertyCollection();
// Add other properties
_properties.Add(_databaseConnection);
}
[ConfigurationProperty("databaseConnection")]
public DatabaseConnectionElementCollection DatabaseConnection
{
get { return (DatabaseConnectionElementCollection)base[_databaseConnection]; }
}
}
However, I am getting the error: "Unrecognized attribute 'dbname'. Note that attribute names are case-sensitive."
DatabaseConnectionElement class:
public class DatabaseConnectionElement : ConfigurationElement
{
private static ConfigurationProperty _name;
private static ConfigurationProperty _sourceConnect;
private static ConfigurationProperty _provider;
private static SqlQueryElementCollection _sqlCollection; // Collection of sql queries for this DB element
private static ConfigurationPropertyCollection _properties;
static DatabaseConnectionElement()
{
_name = new ConfigurationProperty(ConfigConstants.CONFIG_DB_NAME, typeof(string), string.Empty,
ConfigurationPropertyOptions.IsKey);
_sourceConnect = new ConfigurationProperty(ConfigConstants.CONFIG_DB_SOURCECONNECT, typeof(string), string.Empty,
ConfigurationPropertyOptions.IsRequired);
_provider = new ConfigurationProperty(ConfigConstants.CONFIG_DB_PROVIDER, typeof(string), string.Empty,
ConfigurationPropertyOptions.IsRequired);
_sqlCollection = new SqlQueryElementCollection();
_properties = new ConfigurationPropertyCollection();
_properties.Add(_name);
_properties.Add(_sourceConnect);
_properties.Add(_reconnectDelay);
}
[ConfigurationProperty("dbname", IsKey = true)]
public string Name
{
get
{
return (string)base[_name];
}
}
[ConfigurationProperty("dbsourceConnect", IsRequired = true)]
public string SourceConnect
{
get
{
return (string)base[_sourceConnect];
}
}
[ConfigurationProperty("provider", IsRequired = true)]
public string Provider
{
get
{
return (string)base[_provider];
}
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
}
I think this might be helpful. I created a generic config section that has a list of subelements. I just called them elements. You could call them whatever you want.
/// <summary>
/// Defines a generic custom configuration section with a collection of elements of type T.
/// Reference: http://www.abhisheksur.com/2011/09/writing-custom-configurationsection-to.html
/// </summary>
public class GenericSection<T> : ConfigurationSection
where T : ConfigurationElement, IConfigurationElement, new()
{
// Attribute argument must be a constant expression.
protected const string _elementsTag = "elements";
public GenericSection()
{
}
[ConfigurationProperty(_elementsTag, Options = ConfigurationPropertyOptions.IsDefaultCollection)]
public GenericElementCollection<T> Elements
{
get { return ((GenericElementCollection<T>)(base[_elementsTag])); }
set { base[_elementsTag] = value; }
}
}
Here's the Generic Element collection.
/// <summary>
/// Defines a generic ConfigurationElementCollection
/// </summary>
[ConfigurationCollection(typeof(IConfigurationElement))]
public class GenericElementCollection<T> : ConfigurationElementCollection
where T : ConfigurationElement, IConfigurationElement, new()
{
internal const string _elementName = "elements";
protected override string ElementName
{
get { return _elementName; }
}
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
}
protected override bool IsElementName(string elementName)
{
return elementName.Equals(_elementName, StringComparison.InvariantCultureIgnoreCase);
}
public override bool IsReadOnly()
{
return false;
}
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
/// <summary>
/// Return key value for element.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
/// <remarks></remarks>
protected override object GetElementKey(ConfigurationElement element)
{
return ((T)element).Name;
}
/// <summary>
/// Default index property.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public T this[int index] // #c160704 was IConfigruationElement
{
get { return (T)BaseGet(index); }
}
/// <summary>
/// Returns content element by name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public T GetElementByName(string name)
{
return (T)BaseGet(name);
}
public IEnumerable<T> Elements
{
get
{
for (int index = 0; index < this.Count; index++) yield return (T)BaseGet(index);
}
}
/// <summary>
/// Add an element to the collection
/// </summary>
/// <param name="element"></param>
public void AddElement(T element)
{
BaseAdd(element);
}
}
This is the interface I use for the Elements. It requires that the element have a Name property and an active flag.
public interface IConfigurationElement
{
string Name { get; set; }
bool Active { get; set; }
}
Here's a an example of instantiating and using the generic to create configuration section that has a list of folders.
Instantiation the GenericSection with the Element Type.
/// <summary>
/// Defines a custom configuration section for folder elements.
/// Reference: http://www.abhisheksur.com/2011/09/writing-custom-configurationsection-to.html
/// </summary>
public class FolderSection : GenericSection<FolderElement>
{
// This section doesn't require any addition properties.
}
We don't need to do anything with the GenericElementCollection.
Here's the FolderElement:
/// <summary>
/// Defines a configuration folder
/// </summary>
public class FolderElement : ConfigurationElement, IConfigurationElement
{
protected const string NameKey = "name";
protected const string VolumeKey = "volume";
protected const string PathKey = "path";
[ConfigurationProperty(NameKey, DefaultValue = "", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)base[NameKey]; }
set { base[NameKey] = value; }
}
[ConfigurationProperty(VolumeKey, DefaultValue = "", IsKey = false, IsRequired = false)]
public string VolumeLabel
{
get { return (string)base[VolumeKey]; }
set { base[VolumeKey] = value; }
}
[ConfigurationProperty(PathKey, DefaultValue = "", IsKey = false, IsRequired = true)]
public string Path
{
get { return (string)base[PathKey]; }
set { base[PathKey] = value; }
}
[ConfigurationProperty("active", DefaultValue = "true", IsKey = false, IsRequired = false)]
public bool Active
{
get { return (bool)base["active"]; }
set { base["active"] = value; }
}
}
Here's what my App.config looks like. I have two folder sections.
<configuration>
<configSections>
<section name="recent-folders" type="Common.Config.FolderSection, Common.Core"/>
<section name="hidden-folders" type="Common.Config.FolderSection, Common.Core"/>
</configSections>
...
<hidden-folders>
<elements>
<add name="folder1" volume="OS" path="C:\some\hidden\path" />
<add name="folder2" volume="OS" path="C:\some\other\hidden\path" />
</elements>
</hidden-folders>
<recent-folders>
<elements>
<add name="folder1" volume="OS" path="C:\Some\path" />
<add name="folder2" volume="OS" path="C:\Some\other\path" />
</elements>
</recent-folders>
</configururation>
Hello StackOverFlow users,
Iam trying to create an XSD from a dll that i created, but when i try to generate the XSD i get the following error message:
You must implement a default accessor on System.Configuration.ConfigurationLockCollection because it inherits from ICollection.
(Also tried different framework version (Did not work))
Command that gets executed:
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools>xsd "J:\
Programming\C#\NightBitsLogger Library\NightBitsLogger\bin\Debug\NightBitsLogger
.dll"
Does anyone know what i have to do to have a default accessor for the ConfigurationLockCollection?
(Because it seems that this is a bug in the .NET framework)
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Collections;
namespace NightBitsLogger.Configuration
{
/// <summary>
/// This class is an abstract class for a Collection of Config Elements
/// </summary>
/// <typeparam name="T"></typeparam>
///
[ConfigurationCollection(typeof(ConfigurationItem), AddItemName = "ConfigurationElement" )]
public abstract class CollectionOfElements<T> : ConfigurationElementCollection
where T : ConfigurationItem, new()
{
/// <summary>
/// Default Accessor for the collections
/// </summary>
[ConfigurationProperty("ConfigurationCollection", IsRequired = true)]
public CollectionOfElements<ConfigurationItem> ConfigurationCollection
{
get
{
return base["ConfigurationCollection"] as CollectionOfElements<ConfigurationItem>;
}
}
/// <summary>
/// Create and return a new Configuration Element
/// </summary>
/// <returns></returns>
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
/// <summary>
/// Return the element key.
/// </summary>
/// <param name="element"></param>
/// <returns>(ConfigurationElement)key</returns>
protected override object GetElementKey(ConfigurationElement element)
{
return ((ConfigurationItem)element).Name;
}
/// <summary>
/// Return the element with the given index
/// Basic accessor for elements
/// </summary>
/// <param name="index"></param>
/// <returns>[Element]byIndex</returns>
public T this[int index]
{
get
{
return (T)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
/// <summary>
/// Add a element to the collection
/// </summary>
/// <param name="collectionOfLoggerElement"></param>
public void Add(T collectionOfLoggerElement)
{
BaseAdd(collectionOfLoggerElement);
}
/// <summary>
/// Return the element with the given index
/// </summary>
/// <param name="name"></param>
/// <returns>[Element]byName</returns>
public new T this[string name]
{
get
{
return (T)BaseGet(name);
}
}
}
/// <summary>
/// The CollectionOfLoggers Collection
/// </summary>
[ConfigurationCollection(typeof(CollectionOfLoggersElement), AddItemName = "CollectionOfLoggers", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class CollectionOfLoggers : CollectionOfElements<CollectionOfLoggersElement>
{
// Do nothing
}
/// <summary>
/// The FileLogger Collection
/// </summary>
[ConfigurationCollection(typeof(FileLoggerElement), AddItemName = "fileLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class FileLoggers : CollectionOfElements<FileLoggerElement>
{
// Do nothing
}
/// <summary>
/// The RollingDateFileLogger Collection
/// </summary>
[ConfigurationCollection(typeof(RollingDateFileLoggerElement), AddItemName = "rollingDateFileLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class RollingDateFileLoggers : CollectionOfElements<RollingDateFileLoggerElement>
{
// Do nothing
}
/// <summary>
/// The RollingSizeFileLogger Collection
/// </summary>
[ConfigurationCollection(typeof(RollingSizeFileLoggerElement), AddItemName = "rollingSizeFileLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class RollingSizeFileLoggers : CollectionOfElements<RollingSizeFileLoggerElement>
{
// Do nothing
}
/// <summary>
/// The EmailLogger Collection
/// </summary>
[ConfigurationCollection(typeof(EmailLoggerElement), AddItemName = "emailLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class EmailLoggers : CollectionOfElements<EmailLoggerElement>
{
// Do nothing
}
/// <summary>
/// The SocketLogger Collection
/// </summary>
[ConfigurationCollection(typeof(SocketLoggerElement), AddItemName = "socketLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class SocketLoggers : CollectionOfElements<SocketLoggerElement>
{
// Do nothing
}
/// <summary>
/// The WindowsEventLogLogger Collection
/// </summary>
[ConfigurationCollection(typeof(WindowsEventLogLoggerElement), AddItemName = "WindowsEventLogLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class WindowsEventLogLoggers : CollectionOfElements<WindowsEventLogLoggerElement>
{
// Do nothing
}
/// <summary>
/// The ConsoleLogger Collection
/// </summary>
[ConfigurationCollection(typeof(ConsoleLoggerElement), AddItemName = "consoleLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class ConsoleLoggers : CollectionOfElements<ConsoleLoggerElement>
{
// Do nothing
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.ComponentModel;
namespace NightBitsLogger.Configuration
{
/// <summary>
/// This is the baseClass that represents a Config Item (Logger)
/// </summary>
public class ConfigurationItem : ConfigurationSection
{
/// <summary>
/// Get the configuration
/// </summary>
/// <returns></returns>
public static ConfigurationItem GetConfiguration()
{
ConfigurationItem configuration = ConfigurationManager.GetSection("NightBitsLogger.Configuration") as ConfigurationItem;
if (configuration != null)
{
return configuration;
}
return new ConfigurationItem();
}
/// <summary>
/// Occurs after the element is deserialized
/// </summary>
///
protected override void PostDeserialize()
{
base.PostDeserialize();
Validate();
}
/// <summary>
/// Validate the element. Throw a exception if not valid.
/// </summary>
protected virtual void Validate()
{
if ((IncludeCategories.Trim() != "") && (ExcludeCategories.Trim() != ""))
{
throw new ConfigurationErrorsException("logging element can have either includeCategories or excludeCategories, but not both.");
}
}
/// <summary>
/// Return true if the Logger Element is configured for the current machine; otherwise return false.
/// </summary>
/// <returns></returns>
public bool IsConfiguredForThisMachine()
{
var machineNames = Machine.Trim().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return (machineNames.Length == 0) || new List<string>(machineNames).Exists(name => name.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase));
}
/// <summary>
/// Get the name of the Logger
/// </summary>
[ConfigurationProperty("name", DefaultValue = "", IsKey = true, IsRequired = true)]
[Description("The name of the logger")]
public string Name
{
get
{
return (string)this["name"];
}
}
/// <summary>
/// The machine names (separated by commas) for which the Logger will be created. An empty value creates it on all machines.
/// </summary>
[ConfigurationProperty("machine", DefaultValue = "", IsRequired = false)]
[Description("The machine names (separated by commas) for which this logger will be created. Leaving it empty will create it on all machines")]
public string Machine
{
get
{
return (string)this["machine"];
}
}
/// <summary>
/// Check if the Internal Exception Logging is enabled
/// </summary>
[ConfigurationProperty("enableInternalExceptionLogging", DefaultValue = false, IsRequired = false)]
[Description("true if the internal exceptionLogging is enabled; otherwise false")]
public bool IsInternalLoggingEnabled
{
get
{
return (bool)this["isInternalLoggingEnabled"];
}
}
/// <summary>
/// Check if the Logger is enabled
/// </summary>
[ConfigurationProperty("isEnabled", DefaultValue = true, IsRequired = false)]
[Description("true if the logger is enabled; otherwise false")]
public bool IsEnabled
{
get
{
return (bool)this["isEnabled"];
}
}
/// <summary>
/// The LogLevel of the Logger
/// </summary>
[ConfigurationProperty("logLevel", DefaultValue = LogLevel.Debug, IsRequired = false)]
[Description("The logLevel of the logger")]
public LogLevel LogLevel
{
get
{
return (LogLevel)this["logLevel"];
}
}
/// <summary>
/// Categories to include (leave blank for all)
/// </summary>
[ConfigurationProperty("includeCategories", DefaultValue = "", IsRequired = false)]
[Description("The categories, separated by commas, to include when logging. Leave blank to include everything.")]
public string IncludeCategories
{
get
{
return (string)this["includeCategories"];
}
}
/// <summary>
/// Categories to exclude
/// </summary>
[ConfigurationProperty("excludeCategories", DefaultValue = "", IsRequired = false)]
[Description("The categories, separated by commas, to exclude when logging.")]
public string ExcludeCategories
{
get
{
return (string)this["excludeCategories"];
}
}
/// <summary>
/// If true, wrap the Logger in an KeepLoggingLogger.
/// </summary>
[ConfigurationProperty("keepLogging", DefaultValue = false, IsRequired = false)]
[Description("if true, the logger will be wrapped in a KeepLoggingLogger")]
public bool keepLogging
{
get
{
return (bool)this["keepLogging"];
}
}
/// <summary>
/// If true, wrap the Logger in an AsynchronousLogger.
/// </summary>
[ConfigurationProperty("isAsynchronous", DefaultValue = false, IsRequired = false)]
[Description("if true, the logger will be wrapped in a AsynchronousLogger")]
public bool IsAsynchronous
{
get
{
return (bool)this["isAsynchronous"];
}
}
/// <summary>
/// The FormatString for the Logger
/// </summary>
[ConfigurationProperty("formatString", DefaultValue = "", IsRequired = false)]
[Description("The format string of the logger. If blank, it will use the format string of the enclosing section (the CollectionOfLoggers).")]
public virtual string FormatString
{
get
{
return (string)this["formatString"];
}
}
}
}
I'm busy creating an assembly that will gather CodeModel information wich in turn is used to generate code with a T4 template.
I'm struggling with CodeModel because of the lack of good information. I found a few books describing the CodeModel but only the true basics. Found no in-depth documentation.
The past week I created the mentioned assembly and the following construct worked fine for over 4 days.
/// <summary>
/// The CodeType of the property
/// </summary>
public CodeType CodeType
{
get
{
if (!m_CodeTypeInitialized)
{
CodeTypeRef codeTypeRef = CodeProperty.Type;
m_CodeType = codeTypeRef.CodeType;
m_CodeTypeInitialized = true;
}
return m_CodeType;
}
}
Yesterday suddenly this construct no longer returns the CodeType anymore. I've now changed the code to this
/// <summary>
/// The CodeType of the property
/// </summary>
public CodeType CodeType
{
get
{
if (!m_CodeTypeInitialized)
{
if (CodeProperty.IsCodeType)
{
CodeTypeRef codeTypeRef = CodeProperty.Type;
m_CodeType = codeTypeRef.CodeType;
}
m_CodeTypeInitialized = true;
}
return m_CodeType;
}
}
This no longer causes an exception but the outcome is always 'null'. I'm lost. What could cause the CodeProperty to, all of a sudden, loose it's CodeType?
I really need the CodeType because a lot of code is hinging on it's information.
I was able to create a work arround like this. It's not nice but it works fine:
private FileCodeModel m_FileCodeModel;
/// <summary>
/// The FileCodeModel the entity of this property is found in.
/// </summary>
public FileCodeModel FileCodeModel
{
get
{
if (m_FileCodeModel == null)
{
m_FileCodeModel = EntityMetadata.FileCodeModel;
}
return m_FileCodeModel;
}
}
private Project m_Project;
/// <summary>
/// The project this properties entity is contained in.
/// </summary>
public Project ContainingProject
{
get
{
if (m_Project == null)
{
m_Project = FileCodeModel.Parent.ContainingProject;
}
return m_Project;
}
}
private CodeModel m_CodeModel;
/// <summary>
/// The CodeModel for the properties entity.
/// </summary>
public CodeModel CodeModel
{
get
{
if (m_CodeModel == null)
{
m_CodeModel = ContainingProject.CodeModel;
}
return m_CodeModel;
}
}
/// <summary>
/// De CodeType van de property
/// </summary>
public CodeType CodeType
{
get
{
if (!m_CodeTypeInitialized)
{
if (CodeProperty.IsCodeType)
{
CodeTypeRef codeTypeRef = CodeProperty.Type;
m_CodeType = codeTypeRef.CodeType;
}
else
{
m_CodeType = CodeModel.CodeTypeFromFullName(CodeProperty.Type.AsFullName);
}
m_CodeTypeInitialized = true;
}
return m_CodeType;
}
}
I have been trying to get the Wolframalpha API for C# working to no avail. I have been trying to use these two resources:
Stack Question
Wolfram API demos
The answer in the post was semi helpful but I can't get anything to compile. I'm new to C# so its a bit overwhelming. I am really having trouble trying to just get it to accept input and then output the result.
If anyone could either help me get this code working so I can work with a valid example or knows of an example project that I can model from it would be appreciated.
This is the code I cut and pasted into a C# (Visual Studio) console project:
namespace WolframAlpha {
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Net;
using System.IO;
public partial class DefaultPodEntity {
private String _PlainText;
private String _Img;
private String _Title;
private String _ParentTitle;
private Int16 _ParentPosition;
private String _ParentId;
public String PlainText {
get {
return this._PlainText;
}
set {
this._PlainText = value;
}
}
public String Img {
get {
return this._Img;
}
set {
this._Img = value;
}
}
public String Title {
get {
return this._Title;
}
set {
this._Title = value;
}
}
public String ParentTitle {
get {
return this._ParentTitle;
}
set {
this._ParentTitle = value;
}
}
public Int16 ParentPosition {
get {
return this._ParentPosition;
}
set {
this._ParentPosition = value;
}
}
public String ParentId {
get {
return this._ParentId;
}
set {
this._ParentId = value;
}
}
}
public partial class HtmlPodEntity {
private String _Markup;
private String _Title;
private Int16 _Position;
private String _Id;
private String _Css;
private String _Scripts;
public String Markup {
get {
return this._Markup;
}
set {
this._Markup = value;
}
}
public String Title {
get {
return this._Title;
}
set {
this._Title = value;
}
}
public Int16 Position {
get {
return this._Position;
}
set {
this._Position = value;
}
}
public String Id {
get {
return this._Id;
}
set {
this._Id = value;
}
}
public String Css {
get {
return this._Css;
}
set {
this._Css = value;
}
}
public String Scripts {
get {
return this._Scripts;
}
set {
this._Scripts = value;
}
}
}
public partial class PlainTextPodEntity {
private String _PlainText;
private String _Title;
private String _ParentTitle;
private Int16 _ParentPosition;
private String _ParentId;
public String PlainText {
get {
return this._PlainText;
}
set {
this._PlainText = value;
}
}
public String Title {
get {
return this._Title;
}
set {
this._Title = value;
}
}
public String ParentTitle {
get {
return this._ParentTitle;
}
set {
this._ParentTitle = value;
}
}
public Int16 ParentPosition {
get {
return this._ParentPosition;
}
set {
this._ParentPosition = value;
}
}
public String ParentId {
get {
return this._ParentId;
}
set {
this._ParentId = value;
}
}
}
public partial class WolframAlphaFactsContainer : System.Data.Services.Client.DataServiceContext {
public WolframAlphaFactsContainer(Uri serviceRoot) :
base(serviceRoot) {
}
/// <summary>
/// </summary>
/// <param name="Input">Query string Sample Values : weather|msft|derivative of x^4 sin x|SAT scores</param>
/// <param name="Location">Location used for computation Sample Values : Madrid|Springfield, IL</param>
/// <param name="LatitudeLongitude">Latitude/Longitude used for computation Sample Values : 40.42,-3.71|-22.54,-43.12</param>
/// <param name="Width">Width in pixels for images returned Sample Values : 300|500</param>
public DataServiceQuery<DefaultPodEntity> GetImageResults(String Input, String Location, String LatitudeLongitude, Int16? Width) {
if ((Input == null)) {
throw new System.ArgumentNullException("Input", "Input value cannot be null");
}
DataServiceQuery<DefaultPodEntity> query;
query = base.CreateQuery<DefaultPodEntity>("GetImageResults");
if ((Input != null)) {
query = query.AddQueryOption("Input", string.Concat("\'", Input, "\'"));
}
if ((Location != null)) {
query = query.AddQueryOption("Location", string.Concat("\'", Location, "\'"));
}
if ((LatitudeLongitude != null)) {
query = query.AddQueryOption("LatitudeLongitude", string.Concat("\'", LatitudeLongitude, "\'"));
}
if (((Width != null)
&& (Width.HasValue == true))) {
query = query.AddQueryOption("Width", Width.Value);
}
return query;
}
/// <summary>
/// </summary>
/// <param name="Input">Query string Sample Values : weather|msft|derivative of x^4 sin x|SAT scores</param>
/// <param name="Location">Location used for computation Sample Values : Madrid|Springfield, IL</param>
/// <param name="LatitudeLongitude">Latitude/Longitude used for computation Sample Values : 40.42,-3.71|-22.54,-43.12</param>
/// <param name="Width">Width in pixels for images returned Sample Values : 300|500</param>
public DataServiceQuery<HtmlPodEntity> GetHtmlResults(String Input, String Location, String LatitudeLongitude, Int16? Width) {
if ((Input == null)) {
throw new System.ArgumentNullException("Input", "Input value cannot be null");
}
DataServiceQuery<HtmlPodEntity> query;
query = base.CreateQuery<HtmlPodEntity>("GetHtmlResults");
if ((Input != null)) {
query = query.AddQueryOption("Input", string.Concat("\'", Input, "\'"));
}
if ((Location != null)) {
query = query.AddQueryOption("Location", string.Concat("\'", Location, "\'"));
}
if ((LatitudeLongitude != null)) {
query = query.AddQueryOption("LatitudeLongitude", string.Concat("\'", LatitudeLongitude, "\'"));
}
if (((Width != null)
&& (Width.HasValue == true))) {
query = query.AddQueryOption("Width", Width.Value);
}
return query;
}
/// <summary>
/// </summary>
/// <param name="Input">Query string Sample Values : weather|msft|derivative of x^4 sin x|SAT scores</param>
/// <param name="Location">Location used for computation Sample Values : Madrid|Springfield, IL</param>
/// <param name="LatitudeLongitude">Latitude/Longitude used for computation Sample Values : 40.42,-3.71|-22.54,-43.12</param>
/// <param name="Width">Width in pixels for images returned Sample Values : 300|500</param>
public DataServiceQuery<PlainTextPodEntity> GetPlainTextResults(String Input, String Location, String LatitudeLongitude, Int16? Width) {
if ((Input == null)) {
throw new System.ArgumentNullException("Input", "Input value cannot be null");
}
DataServiceQuery<PlainTextPodEntity> query;
query = base.CreateQuery<PlainTextPodEntity>("GetPlainTextResults");
if ((Input != null)) {
query = query.AddQueryOption("Input", string.Concat("\'", Input, "\'"));
}
if ((Location != null)) {
query = query.AddQueryOption("Location", string.Concat("\'", Location, "\'"));
}
if ((LatitudeLongitude != null)) {
query = query.AddQueryOption("LatitudeLongitude", string.Concat("\'", LatitudeLongitude, "\'"));
}
if (((Width != null)
&& (Width.HasValue == true))) {
query = query.AddQueryOption("Width", Width.Value);
}
return query;
}
}
}
This codeplex project claims to cover the latest Wolfram Alpha API and includes a sample:
http://wolframalphaapi20.codeplex.com/
Console applications use a static Main method as their entry point. This routine can normally be found in a file program.cs that is created automatically when a new project for a console application is created.
If the compiler says it can't find Main then it probably was deleted or was never created. Difficult to say without any code to look at. More errors may show when the issue with the Main method was resolved.
I am currently playing with a lib call WolframAlpha.NET. Code source is on github. There is a nuget package (Last published 2019-06-24).
Examples (from readme)
Here is the simplest form of getting data from Wolfram|Alpha:
static void Main(string[] args)
{
//First create the main class:
WolframAlpha wolfram = new WolframAlpha("APPID HERE");
//Then you simply query Wolfram|Alpha like this
//Note that the spelling error will be correct by Wolfram|Alpha
QueryResult results = wolfram.Query("Who is Danald Duck?");
//The QueryResult object contains the parsed XML from Wolfram|Alpha. Lets look at it.
//The results from wolfram is split into "pods". We just print them.
if (results != null)
{
foreach (Pod pod in results.Pods)
{
Console.WriteLine(pod.Title);
if (pod.SubPods != null)
{
foreach (SubPod subPod in pod.SubPods)
{
Console.WriteLine(subPod.Title);
Console.WriteLine(subPod.Plaintext);
}
}
}
}
}
For more examples, take a look at the WolframAlphaNet.Examples and WolframAlphaNet.Tests projects.
You have copy-pasted class definitions (like DefaultPodEntity and WolframAlphaFactsContainer) that allow you to interact with the Wolfram API, but you do not have a definition for the Main() function that defines what your program should be doing with those classes. You will need to add the method definition
static void Main(string[] args)
{
// TODO: call methods of WolframAlphaFactsContainer
}
to one of the classes (e.g. WolframAlphaFactsContainer or a new one, like Program, that is not listed in your question. Once this compiles, you need to replace the TODO comment with C# statements that specify how you are interacting with the WolframAlphaFactsContainer class (e.g. create an instance of that class and call its GetImageResults() method with the proper parameters).
Note: you will need to learn basic C# programming idioms before you can successfully tackle the problem of writing a working, correct program in C# that does what you want to do (as opposed to relying on other people's code).
Note: Read the documentation on Main() and how to pass command line parameters to your program (should you want to do that).
Note: the class WolframAlphaFactsContainer is marked partial, which means there might be other parts of this class (see documentation). If there are, you will need to include those in your code as well.
I know this post is old, but seeing as how it comes up in google near the top:
https://wapiex.codeplex.com/
This is the wrapper I just finished. It includes much more than the other codeplex project. Feel free to use it