tags:

views:

41

answers:

2

Not sure if the question wording is accurate, but here's what I want to do: I want to databind a class with some strings in it:

class MyClass
{
    public string MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

When databinding, everything behaves normally. On the back end, I'm writing to a file and I want MyProperty2 to always be encrypted using some encryption algorithm. I want my back-end code to write each string without needing to know that encryption is required (I want the class to know it should be encrypted, not the consumer). Can I do this with a type converter, or something similar?

EDIT: There are other scenarios as well. Some booleans I want to format as "Y" or "N", other booleans I want formatted as "Enabled" / "Disabled", etc. I can write (and have written) helper methods and let the file writer call the helper methods as appropriate, I'm just wondering if there's a way to do this without the file writer needing to know which objects need which kind of formatting and let the objects tell that to the file writer.

A: 

You can create a private function in MyClass that does the encryption you want. Then in the Get method for MyProperty2 call the private function.

E.g.

public string MyProperty2 
{ 
   get { return DoEncrypt(myProperty2);}
   set; 
}
J Angwenyi
Won't that affect databinding though? In the UI I'm binding MyClass to some WPF page, and I don't want the encryption to occur there.
JHubSharp
A: 

I'm not sure exactly what you're trying to achieve, but you could use a private backing field that is encrypted, then decrypt/encrypt in the property settor. When writing to the file, write the backing field, not the property.

 private string encryptedProperty2;
 public string MyProperty2
 {
      get { return this.Decrypt( this.encryptedProperty2 ); }
      set { this.encryptedProperty2 = this.Encrypt( value ); }
 }

 private void Init()
 {
     ...
     this.encryptedProperty2 = ... read from file ...
     ...
 }

 public void Save()
 {
      ...
      writer.Write( this.encryptedProperty2 );
      ...
 }

Alternatively, you could do the encryption at the time that you read/write to the file. If it's sensitive, though, you may want to keep it encrypted in memory.

tvanfosson
I like this idea. The only downside is the potential for a large number of conversions when I really just want a way (via attribute or something) to tag a property with what is essentially an override of ToString. Of course, this gets even more problematic when working with types that are already strings...but this approach would handle that.
JHubSharp