Getter/Setter is crashing my code, but is fine in a Function - c#

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.

Related

Link and enum to get value from resx file

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();

Process is Terminated due to StackOverFlowException C# [duplicate]

This question already has answers here:
Overloading getter and setter causes a stack overflow in C# [duplicate]
(4 answers)
Closed 3 years ago.
This is my code. I am not able to figure out why this code is giving 'Process is Terminated due to StackOverFlowException'.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SadiSDAL4
{
class Program
{
static void Main(string[] args)
{
PrivateVehical privateV = new PrivateVehical("001");
PrivateVehical pVehical = (PrivateVehical)privateV.Clone();
Console.WriteLine("Cloned : {0}", privateV.name);
Console.WriteLine("Cloned : {0}", pVehical.name);
privateV.name = "Sadia's Car";
Console.WriteLine("Cloned : {0}", privateV.name);
Console.WriteLine("Cloned : {0}", pVehical.name);
pVehical.name = "Waheed's Car";
Console.WriteLine("Cloned : {0}", privateV.name);
Console.WriteLine("Cloned : {0}", pVehical.name);
Console.WriteLine(privateV.GetHashCode().ToString());
Console.WriteLine(pVehical.GetHashCode().ToString());
PublicVehical publicV = new PublicVehical("002");
Console.WriteLine(publicV.id);
PublicVehical pubVehi = (PublicVehical)publicV.Clone();
Console.WriteLine("Cloned : {0}", pubVehi.id);
}
}
abstract class Vehical
{
private string vehicalId = "01";
public string name = "Car_1";
public Vehical(string id)
{
this.vehicalId = id;
}
public string id
{
get { return id; }
set { this.vehicalId = id; }
}
public abstract Vehical Clone();
}
class PrivateVehical : Vehical
{
public PrivateVehical(string id)
: base(id)
{
}
public override Vehical Clone()
{
return (Vehical)this.MemberwiseClone();
}
}
class PublicVehical : Vehical
{
public PublicVehical(string id)
: base(id)
{
}
public override Vehical Clone()
{
return (Vehical)this.MemberwiseClone();
}
}
}
This is the output.
Can someone explain what is the cause of it ? Why it is working in first part & not in the other ?
Take a look at this code:
public string id
{
get { return id; }
set { this.vehicalId = id; }
}
Specifically get { return id; }. You are returning property to itself, causing SO error.
Is this what you intended:
public string id
{
get { return this.vehicalId; }
set { this.vehicalId = value; }
}
Your error is occurring on this line of code
Console.WriteLine(publicV.id);
When you try to get the value of a property from your publicV variable it is calling the getter on the base class.
In your case that's this block in the Vehicle class
public string id
{
get { return id; }
set { this.vehicalId = id; }
}
However, when the get is called it executes return id;. So it once again calls the getter for the id property, which executes the return id; line of code again.
So effectively that line of code is calling itself over and over with no resolution, creating your Stack Overflow issue.
(If you're not familiar with this concept see Recursion)
Take a look at the Vehicle's id property again.
You have the right idea for the set version, you assign the value to the vehicleId property. That is also where you should be getting it from.
I expect that if you change the getter to
get { return this.vehicleId; }
that would resolve your issue.
Debugging the code shows you have a cut and paste error.
public string id
{
// having this set to id causes endless recursion
//get { return id; }
//use this instead
get { return vehicalId; }
set { this.vehicalId = id; }
}
Your error is caused by this definition below:
public string id
{
get { return id; }
set { this.vehicalId = id; }
}
That is because the get call is returning a call to itself, that is, get Id calls get Id, which calls get Id, over and over until you run out of memory and get a StackOverflowException. I guess you meant to do this:
public string id
{
get { return vehicalId; }
set { this.vehicalId = id; }
}
By the way, it feels really accomplishing coming to stackoverflow to get help on debugging a StackOverflowException :)

how to use c# snippet prop?

Just got to know about C# snippet. But i am unable to use them in my code.
Help me out please, I am messed up with get set and how they work.
Here is my test class named "myclass"
namespace WindowsFormsApplication1
{
class myclass
{
public string getmessage(string givenName)
{
return "HB "+givenName;
}
private string bmessage;
public string MyProperty
{
get { return bmessage; }
set { bmessage = value; }
}
}
}
In button code from my form. I am unable to use these get set.
It ll be great if someone clears that how can i use these get set.
Moreover what is "MyProperty" here? I know it is not a method. What is its purpose? Thanks
Snippets itself are not executable statements. But are short-cuts that help you in writing executable statements.
For e.g.
If we write prop and press enter, it will give you a auto-generated property. You just have to change Datatype and Property Name.
Similarly propfull will give a property with get and set parts.
In your case MyProperty is the Property Name and string is the DataType. bmessage is the backing field for your property.
The properties of a class are set and retrieved by using set/get methods. Basically these are also methods.
namespace BusinessObjects
{
public class class_BusinessObjects
{
int StusentId;
string StudentName;
public class_BusinessObjects ()
{
StusentId = 0;
StudentName = string.Empty;
}
public int StusentId
{
get
{
return Id;
}
set
{
Id = value;
}
}
public string StudentName
{
get
{
return Name;
}
set
{
Name = value;
}
}
}
}
using BusinessObjects;
namespace MyModel
{
public class A
{
public class_BusinessObjects Dispaly(int id, string name)
{
class_BusinessObjects obj = new class_BusinessObjects();
obj.StusentId = id;
obj.StudentName = name;
return obj;
}
}
}

Proper way of using C# global variables in ASP.NET?

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

C# Wolfram aplha API working example

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

Categories

Resources