Skip to content

Commit

Permalink
Changed the way request bodies are converted.
Browse files Browse the repository at this point in the history
This resolves #4 AddJsonBody was needed when dealing with Contact Properties.
  • Loading branch information
AshleyMedway committed Apr 12, 2016
1 parent 950d8f0 commit b4f9d94
Show file tree
Hide file tree
Showing 9 changed files with 212 additions and 12 deletions.
9 changes: 6 additions & 3 deletions MailJet.Client.Tests/AccountTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,14 @@ public void MetaSender_GetSingleByEmail()
[Test]
public void MetaSender_Update()
{
var sender = _client.GetMetaSender().Data.FirstOrDefault(x => x.Description.Equals("[TEST]"));
var sender = _client.GetMetaSender().Data.FirstOrDefault();
if (sender == null)
Assert.Inconclusive("Test ran in wrong order and no update could be preformed.");
{
MetaSender_Create();
sender = _client.GetMetaSender().Data.FirstOrDefault();
}

var result = _client.UpdateMetaSender(sender.ID, Description: "[TEST2]", IsEnabled: false);
var result = _client.UpdateMetaSender(sender.ID, Description: Guid.NewGuid().ToString(), IsEnabled: false);

Assert.IsNotNull(result);
Assert.AreEqual(result.Data.Single().ID, sender.ID);
Expand Down
27 changes: 27 additions & 0 deletions MailJet.Client.Tests/ContactListTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using MailJet.Client.Response.Data;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MailJet.Client.Tests
Expand Down Expand Up @@ -343,6 +344,32 @@ public void ListRecipient_ByUnSub_True()
Assert.AreEqual(result.Count, result.Data.Count);
Assert.IsTrue(result.Data.All(x => x.IsUnsubscribed));
}

[TestCase(true)]
public void ContactDataUpdate_ById(bool firstrun)
{
try
{
var result = _client.GetListRecipient();
var item = result.Data.First();
var data = _client.UpdateContactData(item.ContactID, new Dictionary<string, string>()
{
{ "Blah", String.Format("Updated: {0:ddMMyy hhmmss}", DateTime.UtcNow) }
});
}
catch (InvalidOperationException)
{
if (firstrun)
{
CreateContactForList();
ContactDataUpdate_ById(false);
}
else
{
throw;
}
}
}
}
}

68 changes: 68 additions & 0 deletions MailJetClient/Converters/NewtonsoftJsonSerializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using Newtonsoft.Json;
using RestSharp.Serializers;
using System.IO;

namespace MailJet.Client.Converters
{
public class NewtonsoftJsonSerializer : ISerializer
{
private Newtonsoft.Json.JsonSerializer serializer;

public NewtonsoftJsonSerializer(Newtonsoft.Json.JsonSerializer serializer)
{
this.serializer = serializer;
}

public string ContentType
{
get { return "application/json"; } // Probably used for Serialization?
set { }
}

public string DateFormat { get; set; }

public string Namespace { get; set; }

public string RootElement { get; set; }

public string Serialize(object obj)
{
using (var stringWriter = new StringWriter())
{
using (var jsonTextWriter = new JsonTextWriter(stringWriter))
{
serializer.Serialize(jsonTextWriter, obj);

return stringWriter.ToString();
}
}
}

public T Deserialize<T>(RestSharp.IRestResponse response)
{
var content = response.Content;

using (var stringReader = new StringReader(content))
{
using (var jsonTextReader = new JsonTextReader(stringReader))
{
return serializer.Deserialize<T>(jsonTextReader);
}
}
}

public static NewtonsoftJsonSerializer Default
{
get
{
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer()
{
NullValueHandling = NullValueHandling.Ignore,
};
json.Converters.Insert(0, new TKEYVALUELISTConverter());
NewtonsoftJsonSerializer serializer = new NewtonsoftJsonSerializer(json);
return serializer;
}
}
}
}
33 changes: 33 additions & 0 deletions MailJetClient/Converters/TKEYVALUELISTConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using MailJet.Client.Request;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace MailJet.Client.Converters
{
public class TKEYVALUELISTConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(List<TKEYVALUELIST>) == objectType;
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var data = (List<TKEYVALUELIST>)value;

writer.WriteStartObject();
foreach (TKEYVALUELIST item in data)
{
writer.WritePropertyName(item.Name);
writer.WriteValue(item.Value);
}
writer.WriteEndObject();
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
4 changes: 4 additions & 0 deletions MailJetClient/MailJet.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,17 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\TKEYVALUELISTConverter.cs" />
<Compile Include="Converters\NewtonsoftJsonSerializer.cs" />
<Compile Include="Enum\ContactMetadataNameSpace.cs" />
<Compile Include="Enum\ContactMetadataDataType.cs" />
<Compile Include="Enum\CreateContactAction.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="MailJetClient.cs" />
<Compile Include="Request\Contact.cs" />
<Compile Include="Request\TKEYVALUELIST.cs" />
<Compile Include="Response\Data\ContactData.cs" />
<Compile Include="Response\Data\ContactDataUpdate.cs" />
<Compile Include="Response\Data\ContactListData.cs" />
<Compile Include="Response\Data\ContactMetadata.cs" />
<Compile Include="Response\Data\DataItem.cs" />
Expand Down
50 changes: 44 additions & 6 deletions MailJetClient/MailJetClient.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using MailJet.Client.Enum;
using MailJet.Client.Converters;
using MailJet.Client.Enum;
using MailJet.Client.Request;
using MailJet.Client.Response;
using MailJet.Client.Response.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
Expand Down Expand Up @@ -64,14 +67,47 @@ public void DeleteContactList(long ID)
ExecuteRequest(request);
}

public Response<ContactDataUpdate> UpdateContactData(long ContactID, Dictionary<string, string> Data)
{
var request = new RestRequest("REST/contactdata/{id}", Method.PUT);
request.AddParameter("id", ContactID, ParameterType.UrlSegment);

var TData = TKEYVALUELIST.FromDictionary(Data);
var d = new { Data = TData };
request.AddJsonBody(d);
return ExecuteRequest<ContactDataUpdate>(request);
}

public Response<ContactDataUpdate> UpdateContactData(string Email, Dictionary<string, string> Data)
{
var request = new RestRequest("REST/contactdata/{email}", Method.PUT);
request.AddParameter("email", Email, ParameterType.UrlSegment);

var TData = TKEYVALUELIST.FromDictionary(Data);
var d = new { Data = TData };
request.AddJsonBody(d);
return ExecuteRequest<ContactDataUpdate>(request);
}


public Response<ContactData> CreateContactForList(long ID, Contact contact)
{
var request = new RestRequest("REST/contactslist/{id}/managecontact", Method.POST);
request.AddParameter("id", ID, ParameterType.UrlSegment);
request.AddParameter("name", contact.Name, ParameterType.GetOrPost);
request.AddParameter("email", contact.Email, ParameterType.GetOrPost);
request.AddParameter("properties", contact.Properties, ParameterType.GetOrPost);
request.AddParameter("action", System.Enum.GetName(typeof(CreateContactAction), contact.Action), ParameterType.GetOrPost);
request.JsonSerializer = NewtonsoftJsonSerializer.Default;
JObject o = new JObject();
o.Add("name", contact.Name);
o.Add("email", contact.Email);
o.Add("action", System.Enum.GetName(typeof(CreateContactAction), contact.Action));

JObject p = new JObject();
foreach (var i in contact.Properties)
{
p.Add(i.Name, i.Value);
}
o.Add("properties", p);

request.AddJsonBody(o);

return ExecuteRequest<ContactData>(request);
}
Expand Down Expand Up @@ -437,9 +473,10 @@ public Response<ListRecipient> GetListRecipient(
private Response<T> ExecuteRequest<T>(RestRequest request) where T : DataItem
{
request.RequestFormat = DataFormat.Json;
request.JsonSerializer = NewtonsoftJsonSerializer.Default;
var result = WebClient.Execute(request);

if (result.ResponseStatus == ResponseStatus.Completed && result.StatusCode == HttpStatusCode.NoContent)
if (result.ResponseStatus == ResponseStatus.Completed && (result.StatusCode == HttpStatusCode.NoContent))
return null;

var error = JsonConvert.DeserializeObject<ErrorResponse>(result.Content);
Expand All @@ -453,6 +490,7 @@ private Response<T> ExecuteRequest<T>(RestRequest request) where T : DataItem
private void ExecuteRequest(RestRequest request)
{
request.RequestFormat = DataFormat.Json;
request.JsonSerializer = NewtonsoftJsonSerializer.Default;
var result = WebClient.Execute(request);

if (result.ResponseStatus == ResponseStatus.Completed && result.StatusCode == HttpStatusCode.NoContent)
Expand Down
6 changes: 3 additions & 3 deletions MailJetClient/Request/Contact.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ public class Contact
public string Email { get; set; }
public string Name { get; set; }
public CreateContactAction Action { get; set; }
public Dictionary<string, string> Properties { get; set; }
public List<TKEYVALUELIST> Properties { get; set; }

public Contact()
{
Properties = new Dictionary<string, string>();
Properties = new List<TKEYVALUELIST>();
}

public void AddProperty(string key, string value)
{
Properties.Add(key, value);
Properties.Add(new TKEYVALUELIST { Name = key, Value = value });
}
}
}
16 changes: 16 additions & 0 deletions MailJetClient/Request/TKEYVALUELIST.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Collections.Generic;
using System.Linq;

namespace MailJet.Client.Request
{
public struct TKEYVALUELIST
{
public string Name { get; set; }
public string Value { get; set; }

public static List<TKEYVALUELIST> FromDictionary(Dictionary<string, string> dictionary)
{
return dictionary.Select(x => new TKEYVALUELIST { Name = x.Key, Value = x.Value }).ToList();
}
}
}
11 changes: 11 additions & 0 deletions MailJetClient/Response/Data/ContactDataUpdate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using MailJet.Client.Request;
using System.Collections.Generic;

namespace MailJet.Client.Response.Data
{
public class ContactDataUpdate : DataItem
{
public long ContactID { get; set; }
public List<TKEYVALUELIST> Data { get; set; }
}
}

0 comments on commit b4f9d94

Please sign in to comment.