How do I convert "Account" in to
<Account>
or "Object Name" into
<Object with matching name>
I'm attempting to parse a string and replace values in a string with object properties.
This is similar to what we do with form letters we send out, you know the Dear [Customer Name], thank you for purchasing [Some Item]. In this case the fields in the letter aren't setup by me and I need a means of converting what is in the text block into an object property.
Currently I'm using a code in the string {value=x; id=y ;property=z} and running that through a switch case to convert it into an object. Then replacing the {} with the object properties.
for example "some random string {value=1; id=1; property=Name} continued random string"
I parse the string to locate {value=, on a hit it runs through a switch case, where on case 1: return Account(ID = 1). The I grab Account.Name
Once I have that I put it in a text box so the user can validate that it is correct before generating a final document to be sent out.
Is there a way to have {Object.Property} in the string then use reflection to convert that string value to the object value?
Get property value from string using reflection
I used the above in other instances, but that requires that I have the object.
public static List<string> GetClassProperties(string className, IEnumerable<string> propertiesToExclude = null)
{
Type theType = Type.GetType(className);
if (theType == null)
{
return null;
}
}
This'll get you the Object type, you do need the full namespace for it to work, can't just be "Account" would need to be Project.Models.Account
Related
I am trying to get string from NSPasteboard in Xamarin.Mac, here is my code
NSPasteboard pasteboard = NSPasteboard.GeneralPasteboard;
string text = "";
Then what method of pasteboard do I use to store the string into text?
If you know you have string-based data on the pasteboard, you can use GetStringForType using the type of NSStringType.
Example:
string text = NSPasteboard.GeneralPasteboard.GetStringForType(NSPasteboard.NSStringType);
Returns a concatenation of the strings for the specified type from all the items in the receiver that contain the type.
Otherwise you can cycle through all the items on in the pasteboard using
PasteboardItems to return an array of NSPasteboardItem and review each item for the type that you are looking for.
I am working with JSON API. As c# doesn't accept characters like - (minus) or . (point), I had to replace each character by _ (underscore). The replacement happens when the JSON response is received as a string so that every attribute name containing a - or a . will have it replaced by a _ , then every attribute name will be the same as the attributes names in the class it will be deserialized into.
To make it clearer, here are some examples:
I recieve the following JSON : { "id": 1, "result": [ { "data": [ { "adm-pass": ""}]}
In the class I want to deserialize into I have this attribute : public String adm_pass {get; set;}
So I replace the minus with an underscore so that the NewtonSoft parser can deserialize it accordingly.
My problem is that I sometimes I get some negative integers in my JSON. So if I do the string replacement in: {"beta" : -1}, I get a parsing exception since the -1 (integer here) becomes _1 and cannot be deserialized properly and raises an exception.
Is there a way to replace the string smartly so I can avoid this error?
For example if - is followed by an int it's not replaced.
If this way does not exist, is there a solution for this kind of problems?
Newtonsoft allows you to specify the exact name of the JSON property, which it will use to serialize/deserialize.
So you should be able to do this
[JsonProperty("adm-pass")]
public String adm_pass { get; set; }
This way you are not restricted to name your properties exactly as the JSON property names. And in your case, you won't need to do a string replace.
Hope this helps.
You'll have to check that you are replacing the key and not the value, maybe by using a regex like http://regexr.com/3d471
Regex could work as wlalele suggests.
But I would create a new object like this:
Create a new object:
var sharpObj = {};
loop through the objects as properties as described here:
Iterate through object properties
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
In the // do stuff section, create a property on sharpObj with the desired string replacements and set the property to the same value.
var cleanProperty = cleanPropertyName(property);
sharpObj[cleanProperty] = orginalObject[property];
Note: I assume you can figure out the cleanPropertyName() method or similar.
Stringify the object
var string = JSON.stringify(sharpObj);
You can substring to check whether the next character is an integer, this can adapt into your code easily as you already find a character, as such you could do
int a;
if(int.TryParse(adm_pass.Substring(adm_pass.IndexOf("-") + 1,1),out a))
{
//Code if next character is an int
}
else
{
adm_pass = adm_pass.Replace("-","_");
}
This kind of code can be looped until there are no remaining hyphens/minuses
I'm attempting to read the DASL value PR_LONGTERM_ENTRYID_FROM_TABLE 0x66700102 mentioned in this thread -
get outlook mailitem for message taken from outlook table
The issue I'm having is with the following line in the code below from the full example below-
string ltEntryid = (string)nextRow["http://schemas.microsoft.com/mapi/proptag/0x66700102".ToString()];
It throws an exception "Cannot convert type 'byte[]' to 'string'"
I might be going about this the wrong way so I'm looking for some advice. I can read all the other tables rows fine (Example- "EntryID(short term), MessageClass, Unread, SenderEmailType).
const string unReadfilter = "[UnRead] = true";
Outlook.Table table = folder.GetTable(unReadfilter, Outlook.OlTableContents.olUserItems);
// Remove the default column set.
table.Columns.RemoveAll();
// Add columns to the table
table.Columns.Add("Unread");
table.Columns.Add("EntryID");
table.Columns.Add("MessageClass");
table.Columns.Add("SenderEmailType");
table.Columns.Add("SenderEmailAddress");
// PR_LONGTERM_ENTRYID_FROM_TABLE
table.Columns.Add("http://schemas.microsoft.com/mapi/proptag/0x66700102".ToString());
// sort table
table.Sort("Unread", true);
while (!table.EndOfTable)
{
Outlook.Row nextRow = table.GetNextRow();
bool unRead = (bool)nextRow["Unread"];
Debug.WriteLine(unRead);
string msgClass = (string)nextRow["MessageClass"];
Debug.WriteLine(msgClass);
string eId = (string)nextRow["EntryID"];
Debug.WriteLine(eId);
string sEaddr = (string)nextRow["SenderEmailAddress"];
Debug.WriteLine(sEaddr);
string sEtype = (string)nextRow["SenderEmailType"];
Debug.WriteLine(sEtype);
// PR_LONGTERM_ENTRYID_FROM_TABLE ***Exception with the following line***
string ltEntryid = (string)nextRow["http://schemas.microsoft.com/mapi/proptag/0x66700102".ToString()];
Debug.WriteLine(ltEntryid);
if (msgClass.Equals("IPM.Note"))
{
//write to string list
dailyMiInboxList.Add(unRead.ToString());
dailyMiInboxList.Add(msgClass);
dailyMiInboxList.Add(eId);
dailyMiInboxList.Add(sEaddr);
dailyMiInboxList.Add(sEtype);
dailyMiInboxList.Add(sEaddr);
dailyMiInboxList.Add(ltEntryid);
}
}
PT_BINARY property is returned as an array of byte, but you are casting it to a string. If you want to convert it to a hex string, use MAPIFolder.PropertyAccessor.BinaryToString().
OK, I figured this out with Dmitry's help.
First when adding this dasl property to the table -
// PR_LONGTERM_ENTRYID_FROM_TABLE
table.Columns.Add("http://schemas.microsoft.com/mapi/proptag/0x66700102".ToString());
I should've not included the tostring so it should be written as follows-
table.Columns.Add(#"http://schemas.microsoft.com/mapi/proptag/0x66700102");
Next in the While loop, to convert the PT_BINARY property from an array of bytes use this to convert the row-
string PR_LONGTERM_ENTRYID_FROM_TABLE = "http://schemas.microsoft.com/mapi/proptag/0x66700102";
string ltEntryId = (string)nextRow.BinaryToString(PR_LONGTERM_ENTRYID_FROM_TABLE);
Debug.Print(ltEntryId);
This link was very helpful
In particular these comments-
• The value returned for a given column representing a binary (PT_BINARY) value depends on whether a built-in property name or a schema name was used to specify the Column. For explicit built-in property names (such as EntryID), the Row(Column) value is returned as a string. For property names referencing a namespace that represent a PT_BINARY property, the Row(Column) value is returned as a byte array. Use Row.BinaryToString to convert the byte array to a string.
How do I dynamically pass string methods to be applied to strings at run time.
ex.
Private String Formatting(String Data, String Format)
When we pass String S1 = "S1111tring Manipulation" and format = Remove(1,4) - behind the scenes it becomes S1.Remove(1,4) resulting in "String Manipulation"
or if we pass String S1 = "S1111tring Manipulation" and format = ToLower() behind the scene it becomes S1.ToLower() resulting in "s1111tring manipulation"
I should be able to pass any valid method like PadLeft(25,'0'), PadRight, Replace etc...
I would appreciate a complete example
This is what I have tried and it does not work
using System.Reflection;
string MainString = "S1111tring Manipulation";
string strFormat = "Remove(1, 4)";
string result = DoFormat(MainString, strFormat);
private string DoFormat(string data, string format)
{
MethodInfo mi = typeof(string).GetMethod(format, new Type[0]);
if (null == mi)
throw new Exception(String.Format("Could not find method with name '{0}'", format));
return mi.Invoke(data, null).ToString();
}
throws an error (Could not find method with name 'Remove(1, 4)') - so I am not sure how to proceed
Have a look at Reflection. You can essentially implement what you're describing using it save for the parsing of the user supplied text.
The smiple example you've used there would be something like,
var method = "ToLower()";
var methodInfo = typeof(String).GetMethod(method);
var string = "foo";
string.GetType().InvokeMember(....);
Consider using an enum instead of the second string parameter. It will be helpful as for type safety.
public enum StringManipulationType
{
ToLower,
ToUpper
}
and then rewrite the manipulation method you had with the following:
private string Formatting(String data, StringManipulationType manipulationType)
{
switch (manipulationType)
{
case StringManipulationType.ToLower:
return data.ToLower();
case StringManipulationType.ToUpper:
return data.ToUpper();
case default:
throw new ArgumentException();
}
}
In all the places where you had the earlier "string parameter", change it with enum like this:
I'm reading dicom tags using openDicom.net like this:
string tag = "";
string description = "";
string val_rep = "";
foreach (DataElement elementy in sq)
{
tag = elementy.Tag.ToString();
description = elementy.VR.Tag.GetDictionaryEntry().Description;
val_rep = elementy.VR.ToString();
}
How can I read dicom tag values?
the value.ToString() method isn't implemented. Implement your own method in Value.cs and you will get a value for "Value".
For example (only strings and numeric values):
public override string ToString()
{
return valueList[0].ToString();
}
I'm assuming that sq is a Sequence...
I've not worked with openDicom, but I'm pretty sure what you're doing there isn't going to yield the results you want.
You have a single tag, description, and val_rep variable, but you're filling them using a foreach, meaning the last DataElement in the Sequence will be the only values you retrieve. You would achieve the same effect by using:
string tag = sq[sq.Count - 1].Tag.ToString();
string description = sq[sq.Count -1].VR.Tag.GetDictionaryEntry().Description;
string val_rep = sq[sq.Count - 1].VR.ToString();
Thus retrieving the last set of values from the Sequence. I believe you'll find that if you step through the foreach as it executes, it will be loading all the different DataElements contained in your DICOM file.
Feel free to return a comment or post more information in your original post if I'm way off base here.
The tag value is retrieved as an array of generic object from the 'Value' member in 'DataElement' using the 'ToArray()' overriding method in the 'Value' class.
cniDicomTagList = new List<CNIDicomTag>();
foreach (DataElement element in sq)
{
string tag = element.Tag.ToString();
string description = element.VR.Tag.GetDictionaryEntry().Description;
object[] valueArr = element.Value.ToArray();
cniDicomTagList.Add(new CNIDicomTag(tag, description, valueArr));
}