1

I need to change the values of the properties of a class in C# and I would like to have a generic method for it as it will be used for any class in my project.

Sample Classes (Entities):

    public class Apple
    {
       public string Name {get;set;}
       public string Value {get;set;}
       public int ID {get; set;}
    }

    public class Seller
    {
      public Guid Id {get; set;}
      public bool IsActive {get;set;}
    }

Dummy Get & Serialize methods:

var newApple = GetApple(1); 

Serializing into JSON String gives me:

{ "apple": { "id": 12345, "name": "Apple A", "value": "100" } }

var newSeller = GetSeller(new Guid());

Serializing into JSON String gives me:

{ "seller": { "id": 12345, "isActive": false } }

Expected JSON after encryption:

{"apple": { "id": "A##VSDDSVDGFDG!@12321",
"name": "SDD888#@##ASAS#40((!!AA", "value": "SSDSAD#$$$%^&#ADSAD)AA" }}

I want the JSON to be in the above format where I want to encrypt the property values alone and not the property name. I tried using dynamics in C# but the property names are not being set in dynamic.

My Generic Method:

private List<object> EncryptPropertiesAlone<T>(T newObject)
{
{
Type type = newObject.GetType();
PropertyInfo[] properties = type.GetProperties();
List<object> myObjectList = new List<object>();
foreach (PropertyInfo property in properties)
{
var encString = this.EncryptString(property.GetValue(newObject, null)?.ToString());
var propertName = property.Name;
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.propertName = encString;
myObjectList.Add(MyDynamic);
}
return myObjectList;
}

Any ideas how this can be achieved? If there is any built in method in DOTNET which can achieve this? Thanks in advance.

  • It won't work the way you want. In your example for an expected output the ID is a `string`, but the property is of type `int`. Can't you encrypt it while converting to JSON? – Romano Zumbé Jul 05 '17 at 10:44
  • I think this will answer your question: https://stackoverflow.com/questions/29196809/how-can-i-encrypt-selected-properties-when-serializing-my-objects – Romano Zumbé Jul 05 '17 at 10:45
  • The post Romano Zumbé links to is quite good. It has three solutions to your problem. However, none of them handle the issue with types other than string, and it is a hard nut to crack. After being encrypted the properties will be strings, not matter what they were before, so you cannot use the same class for encrypted and unencrypted data. – Palle Due Jul 05 '17 at 13:04
  • Thanks Romano Zumbe for the link provided. I agree with @PalleDue and any suggestions around how to create an extension or a helper class for the problem or else I have to write separate code for all the places where encryption and decryption is happening. – Lakshmi Naarayanan J Jul 06 '17 at 07:09

0 Answers0