C# - Converting from string to my object - c#

In my code I load a text file and read it, looking for specific parameters. After I get them, I save them as string, and now I need to send them to a set-method, that only gets MyProperties type variables. ("MyProperties" is an enum class, and the method that receives the parameter needs to get an enum of this type)
So my question is: how can I convert them from string to MyProperties type?
Reading the file:
string input = File.ReadAllText("C:/avi/properties/" + propertiesFile);
After I get a parameter I need, I save it in a string var named mode.
string mode; // ---> Needs to be "MyProperties mode;"
vpa.Set(MyProperties.Mode, mode);
Solutions like checking if (mode.equals("string")) or "switch" are too long because there is a lot to check.

Been able to find an answer on another post, this is what i used:
TypeConverter converter = TypeDescriptor.GetConverter(type);
MyProperties prop = (MyProperties)converter.ConvertFrom(mode);

Related

How to change text dynamic in unity

at line 161,I want to insert my text in parameter t,but it won't change when i debug it.although the parameter tmp had alredy changed.
I want to change this Text in UI,when my parameter t changes.
With respect to your specific issue, Insert is defined as:
public string Insert (int startIndex, string value);
and returns a new string. In C#, strings aren't modified, new strings are created. In this way, they act like a value type, even though they're a reference type. In other words, once a string is created, it is never modified - it's 'immutable'. So, you need to store your newly created string.
In cases like this, I like to use the string interpolation, as it allows me to get a slightly clearer representation of what the final string will look like.
var tmp = System.Text.Encoding.UTF8.GetString ( e.Message );
t.text = $"{tmp}\n{t.text}"; // Note that a newline is represented as \n
Or, if you add the System.Text namespace; you could reduce it down to:
using System.Text;
...
t.text = $"{Encoding.UTF8.GetString ( e.Message )}\n{t.text}";
The string type in c# is immutable, therefore Insert returns a new string instead of modifying the current one.
Do:
t = t.text.Insert(0, tmp + "//n");
See also
How to modify string contents in C#

c#: string(json) to object(generic) conversion adds extra braces

I have a json as string. I want to convert it into an object. But during conversion, everything is fine, except i get an extra braces outside of the object. That is not a valid json.
string st = "{\"Category\":\"test\"}";
var someType = JsonConvert.DeserializeObject(st);
//output of someType is {{"Category": "test"}}
//expected output {"Category": "test"}
I tried "JObject.Parse()" too. But the result is the same. It adds extra braces to the object.
I want the output as an object compulsorily.
Is there anything that i'm doing wrong? Am i missing something?
In the context of what you're asking, JsonConver.DeserializeObject(st) is doing exactly what you're asking it to do. You're asking it to convert a string representation of the "object" {"Category": "test"} to a json object. The problem with your approach, is that the compiler does not know how to interpret that string as anything other than an object, so it wraps it in a JSON object.
To get the result you're looking for, without declaring a POCO (i.e. deserializing an anonymous type), you'd need to do something like this
var definition = new { Category = "" };
var data = #"{'Category':'Test'}";
var me = JsonConvert.DeserializeAnonymousType(data, definition);
Console.WriteLine(me);
Adding another solution, given what was asked for in the comments.
dynamic deserialized = JObject.Parse("{\"Category\":\"test\"}");

Strange object returned when using content picker

Im currently making usercontrol for umbraco that takes all Nodes indside a Node names "Features"...
And it all works perfekt, until i wanted to get content from the "Content Picker" property (named linkToPage).
When i tried to use GetProperty("linkToPage").Value, I got an error about it being an object.
So i then added it to a var and debugged, and saw it returned somthing a bit strange...
var linkIdVar = child.GetProperty("linkToPage");
Returns:
- linkIdVar {1081} umbraco.interfaces.IProperty {umbraco.NodeFactory.Property}
- [umbraco.NodeFactory.Property] {1081} umbraco.NodeFactory.Property
Alias "linkToPage" string
Value "1081" string
+ Version {00000000-0000-0000-0000-000000000000} System.Guid
+ Non-Public members
Alias "linkToPage" string
Value "1081" string
+ Version {00000000-0000-0000-0000-000000000000} System.Guid
And i can't seem to get the Value to a Int without getting error about it being an object...
So does anyone know how to get arround this, or know a better way to get the page from a Content Picker?
I think you might need to unbox the value to an integer, like so:
var val = (int) child.GetProperty("linkToPage").Value;
However, if the content of the property value is not an integer, but a string, as the debugging information seems to indicate, then you need to convert to an integer, like so:
var val = int.Parse(child.GetProperty("linkToPage").Value as string);

Providing DateTime values in OData

I'm currently writing a special client application to allow our unit tests to work with an OData interface using the XML structure for atom feeds.
All seems to be working properly, but i'm running into trouble when I need to pass a DateTime value as property.
I've written the following code that extracts the DateTime value from the property of the object and stores it in a specific format:
private static void GenerateProperty<T>(StringBuilder xml, T obj, PropertyInfo info)
{
// Extract the information about the property if it contains a value.
if (info.GetValue(obj, null) == null) return;
string type = info.GetGetMethod().ReturnType.ToString().Split('.').Last();
string value = info.GetValue(obj, null).ToString();
if (type == "DateTime")
value = ((DateTime)info.GetValue(obj, null)).ToString("yyyy-mm-ddThh:mm:ss");
if (type == "Boolean") value = value.ToLower();
// Append the property to the generated XML.
xml.Append(type.ToLower().Equals("string") ?
string.Format("<d:{0}>{1}</d:{0}>", info.Name, value) :
string.Format("<d:{0} m:type=\"Edm.{1}\">{2}</d:{0}>", info.Name, type, value));
}
The code is heavy on reflection, but that's beside the point. The values returned by this code for a DateTime are in the following format: 2011-49-13T11:49:41Z
However, i'm receiving the following error from my OData Service:
Error processing request
stream. Error encountered in converting the value from request payload
for property 'Created' to type 'System.DateTime', which is the
property's expected type. See inner exception for more
detail.
The string '2011-49-13T11:49:41Z' is not a valid AllXsd
value.
System.FormatException
at System.Xml.XmlConvert.ToDateTime(String s,
XmlDateTimeSerializationMode dateTimeOption)
 at
System.Data.Services.Parsing.WebConvert.StringToPrimitive(String text,
Type targetType)
 at
System.Data.Services.Serializers.PlainXmlDeserializer.ConvertValuesForXml(Object
value, String propertyName, Type typeToBeConverted)
So apparently it doesn't understand the DateTime format, but when I look at the documentation that's posted here: http://www.odata.org/developers/protocols/overview#AbstractTypeSystem
I'd expect it to be valid. Anyone have any experience with this?
yyyy-mm-ddThh:mm:ss
should be
yyyy-MM-ddTHH:mm:ssZ
ToString("O") will solve the problem too.

C# get string name's name [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get variable name using reflection?
How to get the string name's name not the value of the string
string MyString = "";
Response.Write(MyString.GetType().Name);//Couldn't get the string name not the value of the string
The result should display back the string name "MyString"
I've found some suggested codes and rewrite it to make it shorter but still didn't like it much.
static string VariableName<T>(T item) where T : class
{
return typeof(T).GetProperties()[0].Name;
}
Response.Write(VariableName(new { MyString }));
I am looking another way to make it shorter like below but didn't how to use convert the current class so i can use them in the same line
Response.Write( typeof(new { MyString }).GetProperties()[0].Name);
While Marcelo's answer (and the linked to "duplicate" question) will explain how to do what you're after, a quick explanation why your code doesn't work.
GetType() does exactly what it says: it gets the Type of the object on which it is called. In your case, it will return System.String, which is the Type of the object referenced by your variable MyString. Thus your code will actually print the .Name of that Type, and not the name of the variable (which is what you actually want.)

Categories