How to add deserialize method to abstract class - c#

I have an idea, but I don't understand how to do it.
I've created an abstract class AJsonSerializer. And there I want to Serialize and Deserialize classes.
public abstract class AJsonSerializer {
public string ToJson() {
return JsonConvert.SerializeObject(this);
}
public T FromJson<T>(string jsonString) where T : class {
return JsonConvert.DeserializeObject<T>(jsonString);
}
}
I have a class User where I inherited from my abstract class:
public class User : AJsonSerializer {
public string PublicKey { get; set; }
public int User_ID { get; set; }
}
And now I can do like that
internal static void Get_UserData(string username, ref User user) {
if (ReadFromCache(username, out string value)) {
user = user.FromJson<User>(value);
} else {
DataAccess.Get_UserData(username, out string user_public_key, out int id_user);
user.PublicKey = user_public_key;
user.User_ID = id_user;
value = user.ToJson();
SaveToCashe(username, value);
}
}
This row looks ugly: user = user.FromJson<User>(value);
I want to do it like that: user.FromJson(value);
I know how I can do it in class User (example below), but I want to do it in abstract class and then this method will work for all my classes
Bad method how to solve it, just add initializer to class User like there:
public User(string jsonString) {
User user = JsonConvert.DeserializeObject<ApiUser>(jsonString);
PublicKey = user.PublicKey;
User_ID = user.User_ID;
}

Similar to Jerries answer, another option is just an extension method. You can have a constraint for T to be a AJsonSerializer to have it limited only to the subtypes of it. You can't override the extension method, but in your code you don't have it as virtual in the first place.
public static class SerializerExtensions {
public static T FromJson<T>(this T obj, string json) where T:AJsonSerializer {
JsonConvert.PopulateObject(json, obj);
return obj;
}
}
This way you won't need to implement passing of generic type throughout the inheritance chain.
But you need to initialize the value to access, so it would be:
var user = new User();
user.FromJson(jsonSTring);
or
var user = SerializerExtensions.FromJson(new User(), jsonString);
It's your decision what fits your use case better.

You could declare the generic type in your class definition
public class User : AJsonSerializer<User>
{
public string PublicKey { get; set; }
public int User_ID { get; set; }
}
public abstract class AJsonSerializer<T>
where T : class
{
public string ToJson() {
return JsonConvert.SerializeObject(this);
}
public static T FromJson(string jsonString) {
return JsonConvert.DeserializeObject<T>(jsonString);
}
}
Edit: and as Kara stated in his comment, your FromJson method can be static. So you can call it like
var user = User.FromJson(jsonString);

Related

How to change the same properties of different objects in one method?

I have a method that performs the same function on different objects passed in:
public ??? DoThings(??? inputObject)
{
//do things
if(condition)
inputObject.Status = "error";
}
Objects are of the following class:
public class BaseResponse<T>
{
public string Status { get; set; }
public T Data { get; set; }
public static BaseResponse<T> FromJson(string data)
{
return JsonConvert.DeserializeObject<BaseResponse<T>>(data, JsonHelper.JsonSettings);
}
}
At the end of the method I may need to change the object's Status to an error. How can this be achieved? I have tried to pass in object inputObject. but that of course doesn't work.
Make the method generic:
public void DoThings<T>(BaseResponse<T> inputObject)
{
// do things
if (condition) inputObject.Status = "error";
}
Then you can pass any BaseResponse<T> object:
var baseResponse = BaseResponse<SomeDataType>.FromJson(jsonString);
DoThings(baseResponse); // T can be inferred from baseResponse

Returning a generic object without knowing the type?

I'm still fairly new to programming and have been tasked with creating a WebHook consumer that takes in a raw JSON string, parses the JSON into an object, which will be passed into a handler for processing. The JSON is coming in like this:
{
"id":"1",
"created_at":"2017-09-19T20:41:23.093Z",
"type":"person.created",
"object":{
"id":"person1",
"created_at":"2017-09-19T20:41:23.076Z",
"updated_at":"2017-09-19T20:41:23.076Z",
"firstname":"First",
...
}
}
The inner object can be any object so I thought this would be a great opportunity to use generics and built my class as follows:
public class WebHookModel<T> where T : class, new()
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "created_at")]
public DateTime CreatedAt { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "object")]
public T Object { get; set; }
[JsonIgnore]
public string WebHookAction
{
get
{
return string.IsNullOrEmpty(Type) ? string.Empty : Type.Split('.').Last();
}
}
}
Then created the following interface:
public interface IWebHookModelFactory<T> where T : class, new()
{
WebHookModel<T> GetWebHookModel(string type, string jsonPayload);
}
What I'm failing to understand is how am I supposed to implement the Factory class without knowing what the type is at compile time?
Playing around with the Model a bit, I changed it to an abstract class with an abstract T object so that it could be defined by a derived class.
public abstract class WebHookModel<T> where T : class, new()
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "created_at")]
public DateTime CreatedAt { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "object")]
public abstract T Object { get; set; }
[JsonIgnore]
public string WebHookAction
{
get
{
return string.IsNullOrEmpty(Type) ? string.Empty : Type.Split('.').Last();
}
}
}
public PersonWebHookModel : WebHookModel<Person>
{
public override Person Object { get; set; }
}
But I still run into the same issue of trying to implement an interface in which I don't know the type at runtime. From what I've found online, this is an example of covariance, but I haven't found any articles that explain how to resolve this issue. Is it best to skip generics and create a massive
case statement?
public interface IWebHookFactory<TModel, TJsonObject>
where TJsonObject : class, new()
where TModel : WebHookModel<TJsonObject>
{
TModel GetWebHookModel(string type, string jsonPayload);
}
I'm a bit partial to using the abstract class approach because it lets me define individual handlers based on which model I'm passing into my Service.
public interface IWebHookService<TModel, TJsonObject>
where TJsonObject : class, new()
where TModel : WebHookModel<TJsonObject>
{
void CompleteAction(TModel webHookModel);
}
public abstract class BaseWebhookService<TModel, TJsonObject> : IWebHookService<TModel, TJsonObject>
where TJsonObject : class, new()
where TModel : WebHookModel<TJsonObject>
{
public void CompleteAction(TModel webHookModel)
{
var self = this.GetType();
var bitWise = System.Reflection.BindingFlags.IgnoreCase
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.NonPublic;
var methodToCall = self.GetMethod(jsonObject.WebHookAction, bitWise);
methodToCall.Invoke(this, new[] { jsonObject });
}
protected abstract void Created(TModel webHookObject);
protected abstract void Updated(TModel webHookObject);
protected abstract void Destroyed(TModel webHookObject);
}
public class PersonWebHookService : BaseWebHookService<PersonWebHookModel, Person>
{
protected override void Created(PersonWebHookModel webHookModel)
{
throw new NotImplementedException();
}
protected override void Updated(PersonWebHookModel webHookModel)
{
throw new NotImplementedException();
}
protected override void Destroyed(PersonWebHookModel webHookModel)
{
throw new NotImplementedException();
}
}
Key points for the solution:
1. There needs to be some virtual call in there somewhere.
2. Somehow you need to map from your type tag in your JSON payload to your actual C# class.
IE, "person.created"," --> 'Person'.
If you control the serialization format, JSON.Net can inject its own type tag and do this for you. Assuming you can't go that route ...
So you'll need something like a Dictionary to contain the mapping.
Assuming your definitions is like:
abstract class WebhookPayload // Note this base class is not generic!
{
// Common base properties here
public abstract void DoWork();
}
abstract class PersonPayload : WebhookPayload
{
public override void DoWork()
{
// your derived impl here
}
}
And then you can deserialize like:
static Dictionary<string, Type> _map = new Dictionary<string, Type>
{
{ "person.created", typeof(PersonPayload)}
}; // Add more entries here
public static WebhookPayload Deserialize(string json)
{
// 1. only parse once!
var jobj = JObject.Parse(json);
// 2. get the c# type
var strType = jobj["type"].ToString();
Type type;
if (!_map.TryGetValue(strType, out type))
{
// Error! Unrecognized type
}
// 3. Now deserialize
var obj = (WebhookPayload) jobj.ToObject(type);
return obj;
}

Implement interface and use code from existing implementation of the interface

I'm trying to implement the ITableEntity interface so that I can add [DataContract] attribute on it. But if I implement this interface myself, I'll have to give the ReadEntity and WriteEntity methods a body.
But there is a class that already implements the ITableEntity interface and gave ReadEntity and WriteEntity methods a body, which is the TableEntity.cs.
How can I make my implementation of the interface use the methods in the TableEntity class?
[Edit]
[DataContract]
public class SerializableTableEntity : ITableEntity
{
private TableEntity tableEntity;
public string ETag { get; set; }
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public DateTimeOffset Timestamp { get; set; }
public SerializableTableEntity()
{
tableEntity = new TableEntity();
}
public void ReadEntity(IDictionary<string, EntityProperty> properties, Microsoft.WindowsAzure.Storage.OperationContext operationContext)
{
tableEntity.ReadEntity(properties, operationContext);
}
public IDictionary<string, EntityProperty> WriteEntity(Microsoft.WindowsAzure.Storage.OperationContext operationContext)
{
return tableEntity.WriteEntity(operationContext);
}
}
The reason that every property in your stored table is blank is because WriteEntity and ReadEntity use the blank object to store and write the data.
You're delegating serialization of your object to 'tableEntity' but none of your properties are there.
Suggestion: you will need to implement all of your SerializableTableEntity's properties inside a class that derives from TableEntity, contain a variable of that type inside the SerializableTableEntity entity, and delegate every member's property get/set from SerializableTableEntity to this new object.
Does this make sense?
EDIT: Code sample as requested (you're not going to enjoy it though)
[DataContract]
public class SerializableTableEntity : ITableEntity
{
private CustomEntity tableEntity;
public string ETag {
{
get
{
return tableEntity.ETag;
}
set
{
tableEntity.Etag = value;
}
}
public string PartitionKey
{
get
{
return tableEntity.PartitionKey;
}
set
{
tableEntity.PartitionKey = value;
}
}
public string RowKey
{
get
{
return tableEntity.RowKey;
}
set
{
tableEntity.RowKey = value;
}
}
public DateTimeOffset Timestamp
{
get
{
return tableEntity.Timestamp;
}
set
{
tableEntity.Timestamp = value;
}
}
public string PropertyOne
{
get
{
return tableEntity.PropertyOne;
}
set
{
tableEntity.PropertyOne = value;
}
}
public SerializableTableEntity()
{
tableEntity = new CustomEntity();
}
public void ReadEntity(IDictionary<string, EntityProperty> properties, Microsoft.WindowsAzure.Storage.OperationContext operationContext)
{
tableEntity.ReadEntity(properties, operationContext);
}
public IDictionary<string, EntityProperty> WriteEntity(Microsoft.WindowsAzure.Storage.OperationContext operationContext)
{
return tableEntity.WriteEntity(operationContext);
}
}
public class CustomEntity : TableEntity
{
public string PropertyOne { get; set; }
}
I ended up creating exact copy of these classes and made them Serializable. But being able to do some complex queries seems to be a challenge as well. So we moved to SQL Database.
Either delegate the "uninteresting" methods (a more realistic example is here):
class YourClass : Interface {
public void ReadEntity()
{
delegateTo.ReadEntity();
}
TableEntity delegateTo = new TableEntity();
}
or just throw an exception inside them (like NotImplementedException) - the latter will only work for you if those methods are not called.
You can create a class that contains the implementation of the TableEntity class, but also adds the functionality that you want. This is similar to the Decorator Pattern.
[Attributes...]
public class MyTableEntity : ITableEntity {
private TableEntity decoratedTableEntity;
public void ReadEntity(args...) {
decoratedTableEntity.ReadEntity(args...);
}
}
To make the solution more generic, change decoratedTableEntity to be an ITableEntity.

How to make these n methods to a single generic method?

I have a base class like this:
public class BaseResponse
{
public string ErrorMessage { set;get;}
}
And some child classes which inherit from this:
public class Person:BaseResponse
{
public string FirstNAme { set;get;}
}
public class Phone:BaseResponse
{
public string SerialNumber { set;get;}
}
public class Car :BaseResponse
{
public string Year{ set;get;}
}
Now I want to set the ErrorMessage property of each instance of this class to a different value. Currently this is what I am doing:
public Phone GetPhoneError(Phone objPhone)
{
objPhone.ErrorMessage="Err msg related to Phone";
return objPhone;
}
public Person GetPersonError(Person objPerson )
{
objPerson .ErrorMessage="Err msg related to Person";
return objPerson ;
}
... another similar method for Car also
Is there any way I can make this method a generic format so that I don't need 3 separate methods for setting the error message?
public T GetError<T>(T obj) where T: BaseResponse
{
obj.ErrorMessage= string.Format("Err msg related to {0}", typeof(T).Name);
return obj;
}
I don't know if the error message is this generic thing or something custom. If so, then pass the message as an argument.
Why do you need a method for this? Is it because you have simplified the question?
So in your base class you should create a virtual method called SetError (your GetError but with the correct notation).
public abstract string GetErrorMessage(); //In Base Class so that why each implementation will set the correct error message
Then in your base class - also why do you need to return the same object that you are modifying?
public virtual void SetErrorMessage()
{
this.ErrorMessage = GetErrorMessage();
}
You should be able to have a generic method like so:
public object GetError(BaseResponse response)
{
response.ErrorMessage = "whatever";
return response;
}
Why not make property virtual and no need for set in that case ? :
public class BaseResponse
{
public virtual string ErrorMessage { get;}
}
public class Person:BaseResponse
{
.....
public override string ErrorMessage {get { return "Err msg related to Person";}}
}
public class Phone:BaseResponse
{
......
public override string ErrorMessage {get { return "Err msg related to Phone";}}
}
and so on for others....

How can I apply a common extension method to multiple unrelated types in a third party SDK?

I'm beginning to fall in love with Extension Methods, but I just don't know how to create an EM only for a determinate Object type.
I have for example:
public static void AddPhoneNumberToContact(this Contact contact, PhoneType type, String number)
{
lock (contact)
{
PhoneRow pr = PhoneRow.CreateNew();
pr.SetDefaults();
pr.PtypeIdx = type;
pr.PhoneNumber = number;
contact.Phones.Add(pr);
pr = null;
}
}
My problem is that I want to also Have this method in the Person object, and that is why I named
AddPhoneNumberToContact
AddPhoneNumberToPerson
Is there a way to have AddPhoneNumber and deal with the object that is provided?
or the solution is to have
public static void AddPhoneNumber(this object contact, ...
{
...
if(typeof(Contact) == contact)
((Contact)contact).Phones.Add(pr);
else if(typeof(Person) == contact)
((Person)contact).Phones.Add(pr);
}
Thank you.
How about writing two extension methods:
public static void AddPhoneNumber(this Contact contact, PhoneType type);
and
public static void AddPhoneNumber(this Person person, PhoneType type);
Looks cleaner to me.
If there's some common code between the two, extract that into a separate method.
Make Contact and Person implement common interface - say IContactWithPhoneNumbers - and then write an extension method "for this interface".
public interface IContactWithPhoneNumbers {}
public class Contact : IContactWithPhoneNumbers {}
public class Person : IContactWithPhoneNumbers {}
public static void AddPhoneNumber(this IContactWithPhoneNumbers obj) {}
Reading your comments (objects are from an SDK and are not editable). I would probably do something like this:
public class Util
{
//common util method
public static void AddPhoneNumber(object obj, string phoneNumber)
{
if(obj is Contact)
((Contact)contact).Phones.Add(phoneNumber);
else if(obj is Person)
((Person)contact).Phones.Add(phoneNumber);
}
//extension method for Person
public static void AddPhoneNumber(this Person p, string phoneNumber)
{
AddPhoneNumber((object)p, phoneNumber);
}
//extension method for Contact
public static void AddPhoneNumber(this Contact c, string phoneNumber)
{
AddPhoneNumber((object)c, phoneNumber);
}
}
I do think the best practice though when you have control of the underlying objects would be to implement a common interface.
You might make your extension method generic, e.g.:
public static void AddPhoneNumberToContact<T>(
this T contact,
PhoneType type,
String number
)
{
PhoneRow pr = PhoneRow.CreateNew();
pr.SetDefaults();
pr.PtypeIdx = type;
pr.PhoneNumber = number;
((T)contact).Phones.Add(pr);
pr = null;
}
You won't be able to use lock because "'T' is not a reference type as required by the lock statement", so you might have to return some value.
If it complains about not being able to resolve the Phones method on type T, you could:
Pass in some function delegate that would take type T, return nothing, and perform the action ((T)contact).Phones.Add(pr);.
Or you could create an interface like the following:
public interface IPhoneable
{
IList<Phone> Phones();
}
Then, once you have that interface, you can add the following to your generic extension method:
public static void AddPhoneNumberToContact<T>(
this T contact,
PhoneType type,
String number
) where T : IPhoneable {...}
Here, T is still a generic type, but now your AddPhoneNumberToContact method has the requirement that, whatever T is, it inherits from the IPhoneable interface, which you just defined to have the Phones() method.
See also C# Extension Method for Generic Collections.
If you can not change Person and Contact you can create a subclass of them and let them implement the common interface.
In the extension method you declare the common interface as parameter:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var p = new MyPerson();
p.Name = "test";
p.AddPhonenumber("555-2356");
Console.WriteLine(string.Join(", ", p.Phonenumber));
var c = new MyContact();
c.Name = "contact";
c.AddPhonenumber("222-235");
Console.WriteLine(string.Join(", ", c.Phonenumber));
}
}
public class Contact
{
public Contact() {
this.Phonenumber = new List<string>();
}
public string Name { get; set; }
public List<string> Phonenumber { get; set; }
public string Foo { get; set; }
}
public class Person
{
public Person() {
this.Phonenumber = new List<string>();
}
public string Name { get; set; }
public List<string> Phonenumber { get; set; }
public string Bar { get; set; }
}
public class MyContact: Contact, IType {
}
public class MyPerson: Person, IType {
}
public static class Extensions {
public static void AddPhonenumber(this IType type, string number){
type.Phonenumber.Add(number);
}
}
public interface IType {
string Name {get; set; }
List<string> Phonenumber {get; set;}
}

Categories