i want to use enum as a key to get value from an resource file
in my project i use and method to get value from resx file:
using System;
using System.Reflection;
using System.Resources;
using System.Web;
using Utility.Tools.ExtensionMethods;
using Utility.Tools.Infrastructure;
using Utility.Tools.Utilities.Storage;
namespace MultiLanguage
{
public enum LocaleConfig_Type : byte
{
FA,
AR,
DARI
}
public class MultiLangToolkit
{
public static string GetTranslate(MainKeys key)
{
var lang = LanguegesToolkit.GetCurentLang();
return GetTranslate(key, lang);
}
public static string GetTranslate(MainKeys key, LocaleConfig_Type locale)
{
try
{
string value;
switch (locale)
{ case LocaleConfig_Type.FA:
{
var fa_resx = new ResourceManager("MultiLanguage.FA", Assembly.GetExecutingAssembly());
value = fa_resx.GetString(key.ToString());
}
break;
case LocaleConfig_Type.AR:
{
var ar_resx = new ResourceManager("MultiLanguage.AR", Assembly.GetExecutingAssembly());
value = ar_resx.GetString(key.ToString());
}
break;
case LocaleConfig_Type.DARI:
{
var dari_resx = new ResourceManager("MultiLanguage.DARI", Assembly.GetExecutingAssembly());
value = dari_resx.GetString(key.ToString());
}
break;
default:
value = "No Language Selected!";
break;
}
if (!string.IsNullOrEmpty(value))
return value;
return "Key Or Value NotFound!";
}
catch (Exception)
{
return "Exception when translate";
}
}
}
public class LanguegesToolkit
{
public static LocaleConfig_Type GetCurentLang()
{
try
{
object sessionDefalutLocale = null;
if (HttpContext.Current.Session != null)
{
sessionDefalutLocale = HttpContext.Current.Session[SessionManager.SESSION_USER_DEFAULT_LOCAL];
}
if (sessionDefalutLocale != null)
{
return sessionDefalutLocale.ToString().ToEnum<LocaleConfig_Type>();
}
else
{
var defaultLocale = RequestGlobalProperties.CurrentUserRequest.DefaultLocale;
if (defaultLocale.IsNullOrEmpty())
return Constants.ServiceDefaultLocale.ToEnum<LocaleConfig_Type>();
return defaultLocale.ToEnum<LocaleConfig_Type>();
}
}
catch (Exception)
{
return LocaleConfig_Type.FA;
}
}
}
}
and i have a enum class to store enums:
namespace MultiLanguage
{
public enum MainKeys
{
/// <summary>
/// login to account
/// </summary>
Sign_in,
/// <summary>
/// password
/// </summary>
Password,
/// <summary>
/// user name
/// </summary>
Username
}
}
and i use this code to get value from my resx files
MultiLanguage.MultiLangToolkit.GetTranslate(MultiLanguage.MainKeys.Username)
but this type of code is too many for getting a value from my resx file
i just want to write this code instants the code above:
MultiLanguage.MainKeys.Username
simply just call the enum and get translated value from resx file
i use this code in a dll file to use that in my other projects and use and enum as a key instants of string because strings is not a good choice and my cause and runtime issue and it's hard to debug that. and using summery on the enums to see that is the value in resx file(yes i copy the value frome my rex file into summery)
how can i do that?
is that possible ?
If you really want to stick with your enumerations then you could just create an extension method to simplify the usage. Something like
public static class EnumExtensions
{
public static string Translate(this MainKeys key)
{
return MultiLanguage.MultiLangToolkit.GetTranslate(key);
}
}
then you can just use
MultiLanguage.MainKeys.Username.Translate();
Related
I have created the following class:
namespace com.censureret.motions
{
public class EnumPlayerStances {
public const int OneHandSword = 50;
/// <summary>
/// Friendly name of the type
/// </summary>
public static string[] Names = new string[] {
"One handed Sword"
};
}
}
Now I wish to use this in my following class:
namespace com.censureret.motions{
public class OneHandSword_Idle : MotionControllerMotion
{
public override bool TestActivate()
{
if (!mIsStartable) { return false; }
if (!mMotionController.IsGrounded) { return false; }
if (mActorController.State.Stance != EnumPlayerStances.OneHandSword)
return false;
}
}
}
However Visual Studio says it's an error.
I'm fairly new to C#. What can I try next?
You defeated the point of an enum. It should be declared and used like this:
using System;
namespace StackOverflow_Events
{
class Program
{
static void Main(string[] args)
{
string enumName = Enum.GetName(typeof(EnumPlayerStances), EnumPlayerStances.One_Handed_Sword).Replace("_", " ");
int value = (int)EnumPlayerStances.One_Handed_Sword;
var example = EnumPlayerStances.One_Handed_Sword;
switch (example)
{
case EnumPlayerStances.One_Handed_Sword:
// do stuff
break;
}
Console.WriteLine($"Name: {enumName}, Value: {value}");
Console.ReadKey();
}
}
public enum EnumPlayerStances
{
One_Handed_Sword = 50
}
}
Note that it's declared as "enum" not "class".
Also note, that if you declare the enum like:
public enum EnumPlayerStances
{
No_Sword, // 0
One_Handed_Sword, // 1
Two_Handed_Sword // 2
}
The value of the first name begins at 0 and autoincrements by 1 for each following name.
I have an application splittet into two projects: a web application and a class library. The Startup is only in the web application:
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
I wanna have my appsettings.json in that class library and being loaded from there. Is that possible? How can I do that?
The best solution I have found requires creating a new IFileProvider and IFileInfo, and then embedding the JSON settings files in your assembly.
The solution reuses the existing AddJsonFile logic. This way you only need to tell the configuration system how and where to locate the JSON file, not how to parse it.
The solution is compatible with .NET Core 1.0.
Usage:
public class Startup
{
private readonly AppSettings _appSettings;
public Startup(IHostingEnvironment env)
{
Assembly assembly = GetType().GetTypeInfo().Assembly;
new ConfigurationBuilder()
.AddEmbeddedJsonFile(assembly, "appsettings.json")
.AddEmbeddedJsonFile(assembly, $"appsettings.{env.EnvironmentName.ToLower()}.json")
.Build();
}
...
}
Embed the files by updating the project.json for the class library:
...
"buildOptions": {
"embed": [
"appsettings.json",
"appsettings.development.json",
"appsettings.production.json"
]
}
...
IEmbeddedFileInfo implementation:
public class EmbeddedFileInfo : IFileInfo
{
private readonly Stream _fileStream;
public EmbeddedFileInfo(string name, Stream fileStream)
{
if (name == null) throw new ArgumentNullException(nameof(name));
if (fileStream == null) throw new ArgumentNullException(nameof(fileStream));
_fileStream = fileStream;
Exists = true;
IsDirectory = false;
Length = fileStream.Length;
Name = name;
PhysicalPath = name;
LastModified = DateTimeOffset.Now;
}
public Stream CreateReadStream()
{
return _fileStream;
}
public bool Exists { get; }
public bool IsDirectory { get; }
public long Length { get; }
public string Name { get; }
public string PhysicalPath { get; }
public DateTimeOffset LastModified { get; }
}
IFileInfo implementation:
public class EmbeddedFileProvider : IFileProvider
{
private readonly Assembly _assembly;
public EmbeddedFileProvider(Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
_assembly = assembly;
}
public IFileInfo GetFileInfo(string subpath)
{
string fullFileName = $"{_assembly.GetName().Name}.{subpath}";
bool isFileEmbedded = _assembly.GetManifestResourceNames().Contains(fullFileName);
return isFileEmbedded
? new EmbeddedFileInfo(subpath, _assembly.GetManifestResourceStream(fullFileName))
: (IFileInfo) new NotFoundFileInfo(subpath);
}
public IDirectoryContents GetDirectoryContents(string subpath)
{
throw new NotImplementedException();
}
public IChangeToken Watch(string filter)
{
throw new NotImplementedException();
}
}
Create the easy to use AddEmbeddedJsonFile extension method.
public static class ConfigurationBuilderExtensions
{
public static IConfigurationBuilder AddEmbeddedJsonFile(this IConfigurationBuilder cb,
Assembly assembly, string name, bool optional = false)
{
// reload on change is not supported, always pass in false
return cb.AddJsonFile(new EmbeddedFileProvider(assembly), name, optional, false);
}
}
Yes you could implement IConfigurationProvider
There is a base class ConfigurationProvider that you can inherit from then override all the virtual methods.
You can also see how the JsonConfigurationProvider is implemented.
So I guess your implementation could use the Json provider code internally against embedded json files.
Then you would also want to implement ConfigurationBuilder extension to register your provider similar as the code for using json config.
Someone else can correct me, but I don't think what you are looking for exists.
App Configs and AppSettings files are read at runtime by the application that is running.
The Class Library cannot see any AppSettings specific to itself, because when it runs at run time, it is in the folder of the running application.
The only potential way I can see for you to get your class library contain the json file, is to have the json file as an embedded resource.
Eg: In the solution, select the json file, and set it to Embedded Resource instead of 'content'.
The problem becomes getting the embedded config file out of your assembly, and then loaded.
AddJsonFile accepts a path to the json file.
You could however extract the Json file to a temp directory, then load from there.
static byte[] StreamToBytes(Stream input)
{
int capacity = input.CanSeek ? (int)input.Length : 0;
using (MemoryStream output = new MemoryStream(capacity))
{
int readLength;
byte[] buffer = new byte[capacity/*4096*/]; //An array of bytes
do
{
readLength = input.Read(buffer, 0, buffer.Length); //Read the memory data, into the buffer
output.Write(buffer, 0, readLength);
}
while (readLength != 0); //Do all this while the readLength is not 0
return output.ToArray(); //When finished, return the finished MemoryStream object as an array.
}
}
Assembly yourAssembly = Assembly.GetAssembly(typeof(MyTypeWithinAssembly));
using (Stream input = yourAssembly.GetManifestResourceStream("NameSpace.Resources.Config.json")) // Acquire the dll from local memory/resources.
{
byte[] byteData = StreamToBytes(input);
System.IO.File.WriteAllBytes(Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData)+"//Config.json",new byte[]{});
}
var builder = new ConfigurationBuilder()
.AddJsonFile(Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData)+"//Config.json");
You should in theory be able to specify a type from the class library, in order to help the c# code target that class library specifically. Then you just need to provide the namespace and path to the embedded json file.
Here is my solution, thanks Baaleos and Joe for your advices.
project.json
"resource": [
"appsettings.json"
]
startup.cs
var builder = new ConfigurationBuilder()
.Add(new SettingsConfigurationProvider("appsettings.json"))
.AddEnvironmentVariables();
this.Configuration = builder.Build();
namespace ClassLibrary
{
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
/// <summary>
/// A JSON file based <see cref="ConfigurationProvider"/> for embedded resources.
/// </summary>
public class SettingsConfigurationProvider : ConfigurationProvider
{
/// <summary>
/// Initializes a new instance of <see cref="SettingsConfigurationProvider"/>.
/// </summary>
/// <param name="name">Name of the JSON configuration file.</param>
/// <param name="optional">Determines if the configuration is optional.</param>
public SettingsConfigurationProvider(string name)
: this(name, false)
{
}
/// <summary>
/// Initializes a new instance of <see cref="SettingsConfigurationProvider"/>.
/// </summary>
/// <param name="name">Name of the JSON configuration file.</param>
/// <param name="optional">Determines if the configuration is optional.</param>
public SettingsConfigurationProvider(string name, bool optional)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Name must be a non-empty string.", nameof(name));
}
this.Optional = optional;
this.Name = name;
}
/// <summary>
/// Gets a value that determines if this instance of <see cref="SettingsConfigurationProvider"/> is optional.
/// </summary>
public bool Optional { get; }
/// <summary>
/// The name of the file backing this instance of <see cref="SettingsConfigurationProvider"/>.
/// </summary>
public string Name { get; }
/// <summary>
/// Loads the contents of the embedded resource with name <see cref="Path"/>.
/// </summary>
/// <exception cref="FileNotFoundException">If <see cref="Optional"/> is <c>false</c> and a
/// resource does not exist with name <see cref="Path"/>.</exception>
public override void Load()
{
Assembly assembly = Assembly.GetAssembly(typeof(SettingsConfigurationProvider));
var resourceName = $"{assembly.GetName().Name}.{this.Name}";
var resources = assembly.GetManifestResourceNames();
if (!resources.Contains(resourceName))
{
if (Optional)
{
Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
else
{
throw new FileNotFoundException($"The configuration file with name '{this.Name}' was not found and is not optional.");
}
}
else
{
using (Stream settingsStream = assembly.GetManifestResourceStream(resourceName))
{
Load(settingsStream);
}
}
}
internal void Load(Stream stream)
{
JsonConfigurationFileParser parser = new JsonConfigurationFileParser();
try
{
Data = parser.Parse(stream);
}
catch (JsonReaderException e)
{
string errorLine = string.Empty;
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
IEnumerable<string> fileContent;
using (var streamReader = new StreamReader(stream))
{
fileContent = ReadLines(streamReader);
errorLine = RetrieveErrorContext(e, fileContent);
}
}
throw new FormatException($"Could not parse the JSON file. Error on line number '{e.LineNumber}': '{e}'.");
}
}
private static string RetrieveErrorContext(JsonReaderException e, IEnumerable<string> fileContent)
{
string errorLine;
if (e.LineNumber >= 2)
{
var errorContext = fileContent.Skip(e.LineNumber - 2).Take(2).ToList();
errorLine = errorContext[0].Trim() + Environment.NewLine + errorContext[1].Trim();
}
else
{
var possibleLineContent = fileContent.Skip(e.LineNumber - 1).FirstOrDefault();
errorLine = possibleLineContent ?? string.Empty;
}
return errorLine;
}
private static IEnumerable<string> ReadLines(StreamReader streamReader)
{
string line;
do
{
line = streamReader.ReadLine();
yield return line;
} while (line != null);
}
}
}
You need also the JsonConfigurationFileParser:
namespace ClassLibrary
{
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
internal class JsonConfigurationFileParser
{
private readonly IDictionary<string, string> _data = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private readonly Stack<string> _context = new Stack<string>();
private string _currentPath;
private JsonTextReader _reader;
public IDictionary<string, string> Parse(Stream input)
{
_data.Clear();
_reader = new JsonTextReader(new StreamReader(input));
_reader.DateParseHandling = DateParseHandling.None;
var jsonConfig = JObject.Load(_reader);
VisitJObject(jsonConfig);
return _data;
}
private void VisitJObject(JObject jObject)
{
foreach (var property in jObject.Properties())
{
EnterContext(property.Name);
VisitProperty(property);
ExitContext();
}
}
private void VisitProperty(JProperty property)
{
VisitToken(property.Value);
}
private void VisitToken(JToken token)
{
switch (token.Type)
{
case JTokenType.Object:
VisitJObject(token.Value<JObject>());
break;
case JTokenType.Array:
VisitArray(token.Value<JArray>());
break;
case JTokenType.Integer:
case JTokenType.Float:
case JTokenType.String:
case JTokenType.Boolean:
case JTokenType.Bytes:
case JTokenType.Raw:
case JTokenType.Null:
VisitPrimitive(token);
break;
default:
throw new FormatException($#"
Unsupported JSON token '{_reader.TokenType}' was found.
Path '{_reader.Path}',
line {_reader.LineNumber}
position {_reader.LinePosition}.");
}
}
private void VisitArray(JArray array)
{
for (int index = 0; index < array.Count; index++)
{
EnterContext(index.ToString());
VisitToken(array[index]);
ExitContext();
}
}
private void VisitPrimitive(JToken data)
{
var key = _currentPath;
if (_data.ContainsKey(key))
{
throw new FormatException($"A duplicate key '{key}' was found.");
}
_data[key] = data.ToString();
}
private void EnterContext(string context)
{
_context.Push(context);
_currentPath = string.Join(Constants.KeyDelimiter, _context.Reverse());
}
private void ExitContext()
{
_context.Pop();
_currentPath = string.Join(Constants.KeyDelimiter, _context.Reverse());
}
}
}
I want to return a date in the UK format, rather than the US format that it currently stored.
Therefore, I decided to add a getter and setter to the value within my class.
However, when I run the code with a getter and setter in place, the page fails to load.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Globalisation for converting dates from American to British format
using System.Globalization;
/// <summary>
/// Class to hold the summary of an order take from database TOEHEAD
/// </summary>
public class OrderSummary
{
public string order_number { get; set; }
public string order_date
{
get
{
try
{
string ukDateTimeFormat = Convert.ToString(DateTime.Parse(this.order_date, CultureInfo.CreateSpecificCulture("en-US")));
return ukDateTimeFormat;
}
catch (FormatException e)
{
return "Error";
}
}
set
{
this.order_date = value;
}
}
public string order_total { get; set; }
public OrderSummary()
{
}
}
If I put this code in to a function and return it that way, it works fine.
Have I formatted something wrong?
You cause a Stack Overflow by calling the same property from your get code
string ukDateTimeFormat = Convert.ToString(DateTime.Parse(**this.order_date**, CultureInfo.CreateSpecificCulture("en-US")));
You do this also in the set
this.**order_date** = value;
Fixed code:
private string m_order_date;
public string order_date
{
get
{
try
{
string ukDateTimeFormat = Convert.ToString(DateTime.Parse(m_order_date, CultureInfo.CreateSpecificCulture("en-US")));
return ukDateTimeFormat;
}
catch (FormatException e)
{
return "Error";
}
}
set
{
m_order_date = value;
}
}
It looks like you have a circular reference. Your getter for order_date is calling order_date.
I am using ASP.NET Web Forms and C# in my application. I have a class file named Global.cs, in which I define variables using set and get properties. I use those variables anywhere on any pages by instantiating that class object.
Here is my Global.cs file:
using System;
using System.Data;
using System.Linq;
using System.Web;
/// <summary>
/// Contains my site's global variables.
/// </summary>
public static class Global
{
/// <summary>
/// Global variable storing important stuff.
/// </summary>
public static string gDate;
public static string gMobLength;
public static string gDateFormat;
public static string gApplicationNo;
public static string gBranchNo;
public static string gMemId;
public static string gIsEditable="false";
public static string gLoggedInUserName;
public static string ImportantData
{
get
{
return gDate;
}
set
{
gDate = value;
}
}
public static string MobileLength
{
get
{
return gMobLength;
}
set
{
gMobLength = value;
}
}
public static string DateFormat
{
get
{
return gDateFormat;
}
set
{
gDateFormat = value;
}
}
public static string ApplicationNo
{
get
{
return gApplicationNo;
}
set
{
gApplicationNo = value;
}
}
public static string BranchNo
{
get
{
return gBranchNo;
}
set
{
gBranchNo = value;
}
}
}
Is this a proper way of using variables throughout the project? What are the possible pros and cons with this approach and what approach would you guys take for using global variables?
First, I'd recommend using autoimplemented properties.
public static string BranchNo { get; set; }
Simplifies your code a bit. As to whether or not this is a good approach, it depends. Sometimes simple and straight-forward is better, and this falls into that category. If the values should not change once initialized, you may want to use a proper singleton with initialization:
public class Settings
{
private static Settings _current;
private static readonly object _lock = new object();
public static Settings Current
{
get
{
lock(_lock)
{
if (_current == null) throw new InvalidOperationException("Settings uninitialized");
return _current;
}
}
set
{
if (value == null) throw new ArgumentNullException();
if (_current != null) throw new InvalidOperationException("Current settings can only be set once.");
if (_current == null)
{
lock(_lock)
{
if (_current == null) _current = value;
}
}
}
}
public string ImportantData { get; private set; }
// etc.
}
Initializing settings:
Settings.Current = new Settings{ ImportantData = "blah blah blah"};
Accessing:
var data = Settings.Current.ImportantData;
Outside of the two bromides "globals are bad" and "properties are good" ... there's nothing intrinsically wrong with your approach. Go for it!
IMHO .. PSM
The reason why you do not see the variable after you instantiate that class object is because the variables are declared as static. Static variables are meant to be used by that manor ClassName.variableName or ClassName.PropertyName
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