Some My Experiences

Header Ads

Thursday 17 March 2016

How To Use MailChimp API V3.0 in C#

 To use MailChimp API V3.0 in C# language, do the steps below:
  1. Create C# Web Form Project called 'MailChimpV3'.
  2. Add Json.NET Framework to project Reference. Here I use  Json 8.0.2 version from Newtonsoft.
  3. Create folder called `MailChimp` on the project.
  4. Add C# class called `MailChimpManager.cs` in the `MailChimp` folder, location would be like `\MailChimpV3\MailChimp\MailChimpManager.cs`. Then copy the code below.
    using System;
    using System.IO;
    using System.Net;
    using System.Text;
    using MailChimpV3.MailChimp.Lists;
    using MailChimpV3.MailChimp.Lists.Members;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    namespace MailChimpV3.MailChimp
    {
        public class MailChimpManager
        {
            #region Fields
            private string _dataCenter;
            private const string Url = "api.mailchimp.com/3.0/";
            private const string Get = "GET";
            private const string Post = "POST";
            private const string Patch = "PATCH";
            private const string Delete = "DELETE";
            private string _apiKey;
            #endregion
    
            #region Properties
            public Error Error { get; private set; }
            public string ApiKey
            {
                get { return _apiKey; }
                private set
                {
                    _apiKey = value;
                    _dataCenter = value.Split('-')[1];
                }
            }
            #endregion
    
            #region Constructor
            public MailChimpManager(string apiKey)
            {
                ApiKey = apiKey;
            }
            #endregion
    
            #region Method
            private T DoRequests<T>(string endPoint, string httpMethod, string payload = null)
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(endPoint);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Headers.Add("Authorization", string.Format("{0} {1}", "whatever", ApiKey));
                if (httpMethod != Patch)
                {
                    httpWebRequest.Method = httpMethod;
                }
                else
                {
                    httpWebRequest.Method = WebRequestMethods.Http.Post;
                    httpWebRequest.Headers.Add("X-Http-Method-Override", Patch);
                }
    
                if (!string.IsNullOrEmpty(payload) && (httpMethod == Post || httpMethod == Patch))
                {
                    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        streamWriter.Write(payload);
                    }
                }
    
                string result;
                try
                {
                    using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                    {
                        var statusCode = (int)httpWebResponse.StatusCode;
                        using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                        {
                            result = streamReader.ReadToEnd();
                        }
                        if (statusCode == 200) { return JsonConvert.DeserializeObject<T>(result); }
                        if (statusCode == 204) { return (T)Convert.ChangeType(true, typeof(T)); }
                    }
                }
                catch (WebException we)
                {
                    using (var httpWebResponse = (HttpWebResponse)we.Response)
                    {
                        if (httpWebResponse == null)
                        {
                            Error = new Error { Type = we.Status.ToString(), Detail = we.Message };
                            return default(T);
                        }
                        using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                        {
                            result = streamReader.ReadToEnd();
                        }
                        Error = JsonConvert.DeserializeObject<Error>(result);
                    }
                }
                return default(T);
            }
            private string GetQueryParams(string payload)
            {
                if (payload == null) { return ""; }
                var jObject = JObject.Parse(payload);
                var sbQueryString = new StringBuilder();
                foreach (var obj in jObject)
                {
                    if (obj.Value.Type == JTokenType.Array)
                    {
                        sbQueryString.AppendFormat("{0}=", obj.Key);
                        foreach (var arrayValue in obj.Value)
                        {
                            sbQueryString.AppendFormat("{0}{1}", arrayValue, arrayValue.Next != null ? "," : "&");
                        }
                        continue;
                    }
                    sbQueryString.AppendFormat("{0}={1}&", obj.Key, obj.Value);
                }
                if (sbQueryString.Length > 0)
                {
                    sbQueryString.Insert(0, "?");
                    sbQueryString.Remove(sbQueryString.Length - 1, 1);
                }
                return sbQueryString.ToString();
            }
            #endregion
    
            #region List:
            public List ReadList(string listId, ListQuery listQuery = null)
            {
                string queryString = null;
                if (listQuery != null)
                {
                    var payload = JsonConvert.SerializeObject(listQuery, Formatting.None, new JsonSerializerSettings
                    {
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    });
                    queryString = GetQueryParams(payload);
                }
                var endPoint = string.Format("https://{0}.{1}lists/{2}/{3}", _dataCenter, Url, listId, queryString);
                return DoRequests<List>(endPoint, Get);
            }
            public List EditList(string listId, List list)
            {
                var payload = JsonConvert.SerializeObject(list, Formatting.None, new JsonSerializerSettings
                {
                    DefaultValueHandling = DefaultValueHandling.Ignore
                });
                var endPoint = string.Format("https://{0}.{1}lists/{2}", _dataCenter, Url, listId);
                return DoRequests<List>(endPoint, Patch, payload);
            }
            public List CreateList(List list)
            {
                var payload = JsonConvert.SerializeObject(list, Formatting.None, new JsonSerializerSettings
                {
                    DefaultValueHandling = DefaultValueHandling.Ignore
                });
                var endPoint = string.Format("https://{0}.{1}lists/", _dataCenter, Url);
                return DoRequests<List>(endPoint, Post, payload);
            }
            public bool DeleteList(string listId)
            {
                var endPoint = string.Format("https://{0}.{1}lists/{2}/", _dataCenter, Url, listId);
                return DoRequests<bool>(endPoint, Delete);
            }
            public CollectionList ReadLists(CollectionListQuery listListsQuery = null)
            {
                string queryString = null;
                if (listListsQuery != null)
                {
                    var payload = JsonConvert.SerializeObject(listListsQuery, Formatting.None, new JsonSerializerSettings
                    {
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    });
                    queryString = GetQueryParams(payload);
                }
                var endPoint = string.Format("https://{0}.{1}lists/{2}", _dataCenter, Url, queryString);
                return DoRequests<CollectionList>(endPoint, Get);
            }
            #endregion
    
            #region Member
            public Member ReadMember(string listId, string subscriberHash, MemberQuery memberQuery = null)
            {
                string queryString = null;
                if (memberQuery != null)
                {
                    var payload = JsonConvert.SerializeObject(memberQuery, Formatting.None, new JsonSerializerSettings
                    {
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    });
                    queryString = GetQueryParams(payload);
                }
                var endPoint = string.Format("https://{0}.{1}lists/{2}/members/{3}/{4}", _dataCenter, Url, listId, subscriberHash, queryString);
                return DoRequests<Member>(endPoint, Get);
            }
            public bool DeleteMember(string listId, string subscriberHash)
            {
                var endPoint = string.Format("https://{0}.{1}lists/{2}/members/{3}", _dataCenter, Url, listId, subscriberHash);
                return DoRequests<bool>(endPoint, Delete);
            }
            public Member CreateMember(string listId, Member member)
            {
                var payload = JsonConvert.SerializeObject(member, Formatting.None, new JsonSerializerSettings
                {
                    DefaultValueHandling = DefaultValueHandling.Ignore
                });
                var endPoint = string.Format("https://{0}.{1}lists/{2}/members/", _dataCenter, Url, listId);
                return DoRequests<Member>(endPoint, Post, payload);
            }
            public Member EditMember(string listId, string subscriberHash, Member member)
            {
                var payload = JsonConvert.SerializeObject(member, Formatting.None, new JsonSerializerSettings
                {
                    DefaultValueHandling = DefaultValueHandling.Ignore
                });
                var endPoint = string.Format("https://{0}.{1}lists/{2}/members/{3}", _dataCenter, Url, listId, subscriberHash);
                return DoRequests<Member>(endPoint, Patch, payload);
            }
            public Member CreateOrEditMember(string listId, Member member, bool isForce = false)
            {
                var memberNew = CreateMember(listId, member);
                if (memberNew == null && Error.Status == 400 && Error.Title == "Member Exists")
                {
                    memberNew = EditMember(listId, member.GetSubscriberHash(), member);
                    if (memberNew != null)
                    {
                        return memberNew;
                    }
                }
                return null;
            }
            public CollectionMember ReadMembers(string listId, CollectionMemberQuery memberListsQuery = null)
            {
                string queryString = null;
                if (memberListsQuery != null)
                {
                    var payload = JsonConvert.SerializeObject(memberListsQuery, Formatting.None, new JsonSerializerSettings
                    {
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    });
                    queryString = GetQueryParams(payload);
                }
                var endPoint = string.Format("https://{0}.{1}lists/{2}/members/{3}", _dataCenter, Url, listId, queryString);
                return DoRequests<CollectionMember>(endPoint, Get);
            }
            public CollectionMember GetAllSubscribedMembers(string listId)
            {
                var memberListQuery = new CollectionMemberQuery();
                memberListQuery.Status = "subscribed";
    
                return ReadMembers(listId, memberListQuery);
            }
            public CollectionMember CollectionMemberQuery(string listId)
            {
                var memberListQuery = new CollectionMemberQuery();
                memberListQuery.Status = "unsubscribed";
    
                return ReadMembers(listId, memberListQuery);
            }
            public CollectionMember GetAllCleanedMembers(string listId)
            {
                var memberListQuery = new CollectionMemberQuery();
                memberListQuery.Status = "cleaned";
    
                return ReadMembers(listId, memberListQuery);
            }
            #endregion
        }
    }
  5.  Add C# class called `Error.cs` in the `MailChimp` folder, location would be like `\MailChimpV3\MailChimp\Error.cs`. Then copy the code below.

    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp
    {
        public class Error
        {
            [JsonProperty("type")]
            public string Type { get; set; }
            [JsonProperty("title")]
            public string Title { get; set; }
            [JsonProperty("status")]
            public int Status { get; set; }
            [JsonProperty("detail")]
            public string Detail { get; set; }
            [JsonProperty("instance")]
            public string Instance { get; set; }
            [JsonProperty("errors")]
            public string Errors { get; set; }
        }
    }
    
  6.  Add C# class called `Link.cs` in the `MailChimp` folder, location would be like `\MailChimpV3\MailChimp\Link.cs`. Then copy the code below.

    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp
    {
        public class Link
        {
            [JsonProperty("rel")]
            public string Rel { get; set; }
            [JsonProperty("href")]
            public string Href { get; set; }
            [JsonProperty("method")]
            public string Method { get; set; }
            [JsonProperty("targetSchema")]
            public string TargetSchema { get; set; }
            [JsonProperty("schema")]
            public string Schema { get; set; }
        }
    }
  7. Add a new folder called `Lists` to the `MailChimp` folder, location would be like `\MailChimpV3\MailChimp\Lists`.
  8. Add C# class called `CampaignDefault.cs` in the `Lists` folder, location would be like `\MailChimpV3\MailChimp\Lists\CampaignDefault.cs`. Then copy the code below.
    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp.Lists
    {
        public class CampaignDefault
        {
            [JsonProperty("from_name")]
            public string FromName { get; set; }
            [JsonProperty("from_email")]
            public string FromEmail { get; set; }
            [JsonProperty("subject")]
            public string Subject { get; set; }
            [JsonProperty("language")]
            public string Language { get; set; }
        }
    }
  9. Add C# class called `Contact.cs` in the `Lists` folder, location would be like `\MailChimpV3\MailChimp\Lists\Contact.cs`. Then copy the code below.
    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp.Lists
    {
        public class Contact
        {
            [JsonProperty("company")]
            public string Company { get; set; }
            [JsonProperty("address1")]
            public string Address1 { get; set; }
            [JsonProperty("address2")]
            public string Address2 { get; set; }
            [JsonProperty("city")]
            public string City { get; set; }
            [JsonProperty("state")]
            public string State { get; set; }
            [JsonProperty("zip")]
            public string Zip { get; set; }
            [JsonProperty("country")]
            public string Country { get; set; }
            [JsonProperty("phone")]
            public string Phone { get; set; }
        }
    }
  10. Add C# class called `List.cs` in the `Lists` folder, location would be like `\MailChimpV3\MailChimp\Lists\List.cs`. Then copy the code below.
    using System.Collections.Generic;
    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp.Lists
    {
        public class List
        {
            [JsonProperty("id")]
            public string Id { get; set; }
            [JsonProperty("name")]
            public string Name { get; set; }
            [JsonProperty("contact")]
            public Contact Contact { get; set; }
            [JsonProperty("permission_reminder")]
            public string PermissionReminder { get; set; }
            [JsonProperty("use_archive_bar")]
            public bool? UseArchiveBar { get; set; }
            [JsonProperty("campaign_defaults")]
            public CampaignDefault CampaignDefaults { get; set; }
            [JsonProperty("notify_on_subscribe")]
            public string NotifyOnSubscribe { get; set; }
            [JsonProperty("notify_on_unsubscribe")]
            public string NotifyOnUnsubscribe { get; set; }
            [JsonProperty("date_created")]
            public string DateCreated { get; set; }
            [JsonProperty("list_rating")]
            public int? ListRating { get; set; }
            [JsonProperty("email_type_option")]
            public bool? EmailTypeOption { get; set; }
            [JsonProperty("subscribe_url_short")]
            public string SubscribeUrlShort { get; set; }
            [JsonProperty("subscribe_url_long")]
            public string SubscribeUrlLong { get; set; }
            [JsonProperty("beamer_address")]
            public string BeamerAddress { get; set; }
            [JsonProperty("visibility")]
            public string Visibility { get; set; }
            [JsonProperty("modules")]
            public string[] Modules { get; set; }
            [JsonProperty("stats")]
            public Stat Stats { get; set; }
            [JsonProperty("_links")]
            public List<Link> Links { get; set; }
        }
        public class ListQuery
        {
            [JsonProperty("fields")]
            public string[] Fields { get; set; }
            [JsonProperty("exclude_fields")]
            public string[] ExcludeFields { get; set; }
        }
        public class CollectionList
        {
            [JsonProperty("lists")]
            public List<List> Lists { get; set; }
            [JsonProperty("total_items")]
            public int TotalItems { get; set; }
        }
        public class CollectionListQuery
        {
            [JsonProperty("fields")]
            public string[] Fields { get; set; }
            [JsonProperty("exclude_fields")]
            public string[] ExcludeFields { get; set; }
            [JsonProperty("count")]
            public int Count { get; set; }
            [JsonProperty("offset")]
            public int Offset { get; set; }
            [JsonProperty("before_date_created")]
            public string BeforeDateCreated { get; set; }
            [JsonProperty("since_date_created")]
            public string SinceDateCreated { get; set; }
            [JsonProperty("before_campaign_last_sent")]
            public string BeforeCampaignLastSent { get; set; }
            [JsonProperty("since_campaign_last_sent")]
            public string SinceCampaignLastSent { get; set; }
        }
    }
    
  11. Add C# class called `Stat.cs` in the `Lists` folder, location would be like `\MailChimpV3\MailChimp\Lists\Stat.cs`. Then copy the code below.
    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp.Lists
    {
        public class Stat
        {
            [JsonProperty("member_count")]
            public int MemberCount { get; set; }
            [JsonProperty("unsubscribe_count")]
            public int UnsubscribeCount { get; set; }
            [JsonProperty("cleaned_count")]
            public int CleanedCount { get; set; }
            [JsonProperty("member_count_since_send")]
            public int MemberCountSinceSend { get; set; }
            [JsonProperty("unsubscribe_count_since_send")]
            public int UnsubscribeCountSinceSend { get; set; }
            [JsonProperty("cleaned_count_since_send")]
            public int CleanedCountSinceSend { get; set; }
            [JsonProperty("campaign_count")]
            public int CampaignCount { get; set; }
            [JsonProperty("campaign_last_sent")]
            public string CampaignLastSent { get; set; }
            [JsonProperty("merge_field_count")]
            public int MergeFieldCount { get; set; }
            [JsonProperty("avg_sub_rate")]
            public byte AvgSubRate { get; set; }
            [JsonProperty("avg_unsub_rate")]
            public byte AvgUnsubRate { get; set; }
            [JsonProperty("target_sub_rate")]
            public byte TargetSubRate { get; set; }
            [JsonProperty("open_rate")]
            public byte OpenRate { get; set; }
            [JsonProperty("click_rate")]
            public byte ClickRate { get; set; }
            [JsonProperty("last_sub_date")]
            public string LastSubDate { get; set; }
            [JsonProperty("last_unsub_date")]
            public string LastUnsubDate { get; set; }
        }
    }
    
  12. Add a new folder called `Members` to the `Lists` folder, location would be like `\MailChimpV3\MailChimp\Lists\Members`.
  13. Add C# class called `Member.cs` in the `Members` folder, location would be like `\MailChimpV3\MailChimp\Lists\Members\Member.cs`. Then copy the code below.
    using System.Collections.Generic;
    using System.Security.Cryptography;
    using System.Text;
    using MailChimpV3.MailChimp.Lists.Interests;
    using MailChimpV3.MailChimp.Lists.Members.Notes;
    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp.Lists.Members
    {
        public class Member
        {
            [JsonProperty("id")]
            public string Id { get; set; }
            [JsonProperty("email_address")]
            public string EmailAddress { get; set; }
            [JsonProperty("unique_email_id")]
            public string UniqueEmailId { get; set; }
            [JsonProperty("email_type")]
            public string EmailType { get; set; }
            [JsonProperty("status")]
            public string Status { get; set; }
            [JsonProperty("merge_fields")]
            public Dictionary<string, string> MergeFields { get; set; }
            [JsonProperty("interests")]
            public Interest Interests { get; set; }
            [JsonProperty("stats")]
            public Stat Stats { get; set; }
            [JsonProperty("ip_signup")]
            public string IpSignup { get; set; }
            [JsonProperty("timestamp_signup")]
            public string TimestampSignup { get; set; }
            [JsonProperty("ip_opt")]
            public string IpOpt { get; set; }
            [JsonProperty("timestamp_opt")]
            public string TimestampOpt { get; set; }
            [JsonProperty("member_rating")]
            public byte? MemberRating { get; set; }
            [JsonProperty("last_changed")]
            public string LastChanged { get; set; }
            [JsonProperty("language")]
            public string Language { get; set; }
            [JsonProperty("vip")]
            public bool? Vip { get; set; }
            [JsonProperty("email_client")]
            public string EmailClient { get; set; }
            [JsonProperty("location")]
            public Location Location { get; set; }
            [JsonProperty("last_note")]
            public Note LastNote { get; set; }
            [JsonProperty("list_id")]
            public string ListId { get; set; }
            [JsonProperty("_links")]
            public List<Link> Links { get; set; }
    
            public string GetSubscriberHash()
            {
                using (var md5Hash = MD5.Create())
                {
                    var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(EmailAddress));
                    var sb = new StringBuilder();
                    for (var i = 0; i < data.Length; i++)
                    {
                        sb.Append(data[i].ToString("x2"));
                    }
                    return sb.ToString();
                }
            }
        }
        public class MemberQuery
        {
            [JsonProperty("fields")]
            public string[] Fields { get; set; }
            [JsonProperty("exclude_fields")]
            public string[] ExcludeFields { get; set; }
        }
        public class CollectionMemberParent
        {
            [JsonProperty("list_id")]
            public string ListId { get; set; }
        }
        public class CollectionMember : CollectionMemberParent
        {
            [JsonProperty("members")]
            public List<Member> Members { get; set; }
            [JsonProperty("total_items")]
            public int TotalItems { get; set; }
        }
        public class CollectionMemberQuery : CollectionMemberParent
        {
            [JsonProperty("fields")]
            public string[] Fields { get; set; }
            [JsonProperty("exclude_fields")]
            public string[] ExcludeFields { get; set; }
            [JsonProperty("count")]
            public int Count { get; set; }
            [JsonProperty("offset")]
            public int Offset { get; set; }
            [JsonProperty("email_type")]
            public string EmailType { get; set; }
            [JsonProperty("status")]
            public string Status { get; set; }
            [JsonProperty("since_timestamp_opt")]
            public string SinceTimestampOpt { get; set; }
            [JsonProperty("before_timestamp_opt")]
            public string BeforeTimestampOpt { get; set; }
            [JsonProperty("since_last_changed")]
            public string SinceLastChanged { get; set; }
            [JsonProperty("before_last_changed")]
            public string BeforeLastChanged { get; set; }
        }
    }
    
  14. Add C# class called `Location.cs` in the `Members` folder, location would be like `\MailChimpV3\MailChimp\Lists\Members\Location.cs`. Then copy the code below.
    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp.Lists.Members
    {
        public class Location
        {
            [JsonProperty("latitude")]
            public double Latitude { get; set; }
            [JsonProperty("longitude")]
            public double Longitude { get; set; }
            [JsonProperty("gmtoff")]
            public int Gmtoff { get; set; }
            [JsonProperty("dstoff")]
            public int Dstoff { get; set; }
            [JsonProperty("country_code")]
            public string CountryCode { get; set; }
            [JsonProperty("timezone")]
            public string Timezone { get; set; }
        }
    }
    
  15. Add C# class called `Stat.cs` in the `Members` folder, location would be like `\MailChimpV3\MailChimp\Lists\Members\Stat.cs`. Then copy the code below.
    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp.Lists.Members
    {
        public class Stat
        {
            [JsonProperty("avg_open_rate")]
            public double AvgOpenRate { get; set; }
            [JsonProperty("avg_click_rate")]
            public double AvgClickRate { get; set; }
        }
    }
    
  16. Add a new folder called `Notes` to the `Members` folder, location would be like `\MailChimpV3\MailChimp\Lists\Members\Notes`.
  17. Add C# class called `Note.cs` in the `Notes` folder, location would be like `\MailChimpV3\MailChimp\Lists\Members\Notes\Note.cs`. Then copy the code below.
    using System.Collections.Generic;
    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp.Lists.Members.Notes
    {
        public class Note
        {
            [JsonProperty("id")]
            public int Id { get; set; }
            [JsonProperty("note_id")]
            public int NoteId { get; set; }
            [JsonProperty("created_at")]
            public string CreatedAt { get; set; }
            [JsonProperty("created_by")]
            public string CreatedBy { get; set; }
            [JsonProperty("updated_at")]
            public string UpdatedAt { get; set; }
            [JsonProperty("note")]
            public string Content { get; set; }
            [JsonProperty("list_id")]
            public string ListId { get; set; }
            [JsonProperty("email_id")]
            public string EmailId { get; set; }
            [JsonProperty("_links")]
            public List<Link> Link { get; set; }
        }
    }
    
  18. Add a new folder called `Interests` to the `Lists` folder, location would be like `\MailChimpV3\MailChimp\Lists\Interests`.
  19. Add C# class called `Interest.cs` in the `Interests` folder, location would be like `\MailChimpV3\MailChimp\Lists\Interests\Interest.cs`. Then copy the code below.
    using Newtonsoft.Json;
    
    namespace MailChimpV3.MailChimp.Lists.Interests
    {
        public class Interest
        {
            [JsonProperty("list_id")]
            public string ListId { get; set; }
            [JsonProperty("id")]
            public string Id { get; set; }
            [JsonProperty("title")]
            public string Title { get; set; }
            [JsonProperty("display_order")]
            public string DisplayOrder { get; set; }
            [JsonProperty("type")]
            public string Type { get; set; }
        }
    }

Simple examples of usage the code is as follows:

  1. Code for `Default.aspx`.
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MailChimpV3.Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
        </div>
        </form>
    </body>
    </html>
    
  2. Code for `Default.aspx.cs`.
    using System;
    using System.Collections.Generic;
    using System.Web.UI;
    using MailChimpV3.MailChimp;
    using MailChimpV3.MailChimp.Lists;
    using MailChimpV3.MailChimp.Lists.Members;
    
    namespace MailChimpV3
    {
        public partial class Default : Page
        {
            private const string Key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us12"; //your api key
            private const string ListId = "aa95213739";
    
            protected void Page_Load(object sender, EventArgs e)
            {
                var mailChimp = new MailChimpManager(Key); //create mailchimpmanager with api key
    
                CreateMember(mailChimp);
                GetMember(mailChimp);
                EditMember(mailChimp);
                DeleteMember(mailChimp);
    
                CreateList(mailChimp);
                GetList(mailChimp);
                EditList(mailChimp);
                DeleteList(mailChimp);
            }
    
            private void CreateMember(MailChimpManager mailChimpManager)
            {
                var member = new Member();
                member.EmailAddress = "mail@mail.com";
                member.Status = "unsubscribed";
                member.MergeFields = new Dictionary<string, string>();
                member.MergeFields.Add("FNAME", "First Name");
                member.MergeFields.Add("LNAME", "Last Name");
    
                var memberNew = mailChimpManager.CreateMember(ListId, member);
                if (memberNew != null)
                {
                    DisplayMember(memberNew);
                }
                else
                {
                    DisplayError(mailChimpManager.Error);
                }
            }
            private void GetMember(MailChimpManager mailChimpManager)
            {
                const string subscriberHash = "7905d373cfab2e0fda04b9e7acc8c879";
    
                var memberQueryParams = new MemberQuery();
                memberQueryParams.Fields = new[] { "id", "email_address", "merge_fields" }; //field return
    
                var member = mailChimpManager.ReadMember(ListId, subscriberHash, memberQueryParams);
                if (member == null)
                {
                    DisplayError(mailChimpManager.Error);
                }
                else
                {
                    DisplayMember(member);
                }
            }
            private void EditMember(MailChimpManager mailChimpManager)
            {
                const string param = "7905d373cfab2e0fda04b9e7acc8c879";
    
                var member = new Member();
                member.EmailType = "html";
                member.Status = "subscribed";
                member.Vip = false;
                member.Language = "id";
                member.MergeFields = new Dictionary<string, string>();
                member.MergeFields.Add("FNAME", "Alexson");
                member.MergeFields.Add("LNAME", "Triwan");
                var memberNew = mailChimpManager.EditMember(ListId, param, member);
                if (memberNew == null)
                {
                    DisplayError(mailChimpManager.Error);
                }
                else
                {
                    DisplayMember(memberNew);
                }
            }
            private void DeleteMember(MailChimpManager mailChimpManager)
            {
                var memberDel = new Member
                {
                    EmailAddress = "mail@mail.com"
                }.GetSubscriberHash();
                if (mailChimpManager.DeleteMember(ListId, memberDel))
                {
                    Response.Write("mail@mail.com has ben deleted.");
                }
                else
                {
                    DisplayError(mailChimpManager.Error);
                }
            }
    
            private void CreateList(MailChimpManager mailChimpManager)
            {
                var list = new List();
                list.Name = "My List";
                list.Contact = new Contact
                {
                    Company = "My Company",
                    Address1 = "Address1",
                    Address2 = "Address2",
                    City = "City",
                    State = "State",
                    Zip = "Zip",
                    Country = "ID"
                };
                list.PermissionReminder = "This is permission reminder";
                list.CampaignDefaults = new CampaignDefault
                {
                    FromName = "My Name",
                    FromEmail = "mymail@mail.com",
                    Subject = "Subject Email",
                    Language = "ID"
                };
                list.EmailTypeOption = false;
                var listNew = mailChimpManager.CreateList(list);
                if (listNew != null)
                {
                    DisplayList(listNew);
                }
                else
                {
                    DisplayError(mailChimpManager.Error);
                }
            }
            private void GetList(MailChimpManager mailChimpManager)
            {
                var list = mailChimpManager.ReadList(ListId);
                if (list == null)
                {
                    DisplayError(mailChimpManager.Error);
                }
                else
                {
                    DisplayList(list);
                }
            }
            private void EditList(MailChimpManager mailChimpManager)
            {
                var list = new List();
                list.Name = "My List Updated";
                list.PermissionReminder = "You are receiving this email because you signed up for our websites.";
                var listNew = mailChimpManager.EditList(ListId, list);
                if (listNew == null)
                {
                    DisplayError(mailChimpManager.Error);
                }
                else
                {
                    DisplayList(listNew);
                }
            }
            private void DeleteList(MailChimpManager mailChimpManager)
            {
                if (mailChimpManager.DeleteList(ListId))
                {
                    Response.Write("List has been deleted.");
                }
                else
                {
                    DisplayError(mailChimpManager.Error);
                }
            }
    
            private void DisplayMember(Member member)
            {
                Response.Write(string.Format("id : {0}<br>", member.Id));
                Response.Write(string.Format("EmailAddress : {0}<br>", member.EmailAddress));
                Response.Write(string.Format("UniqueEmailId : {0}<br>", member.UniqueEmailId));
                Response.Write(string.Format("EmailType : {0}<br>", member.EmailType));
                Response.Write(string.Format("Status : {0}<br>", member.Status));
                Response.Write(string.Format("Interests : {0}<br>", member.Interests));
                Response.Write(string.Format("Stats :<br>"));
                if (member.Stats != null)
                {
                    Response.Write(string.Format("- AvgClickRate : {0}<br>", member.Stats.AvgClickRate));
                    Response.Write(string.Format("- AvgOpenRate : {0}<br>", member.Stats.AvgOpenRate));
                }
                Response.Write(string.Format("IpSignup : {0}<br>", member.IpSignup));
                Response.Write(string.Format("TimestampSignup : {0}<br>", member.TimestampSignup));
                Response.Write(string.Format("IpOpt : {0}<br>", member.IpOpt));
                Response.Write(string.Format("TimestampOpt : {0}<br>", member.TimestampOpt));
                Response.Write(string.Format("MemberRating : {0}<br>", member.MemberRating));
                Response.Write(string.Format("LastChanged : {0}<br>", member.LastChanged));
                Response.Write(string.Format("Language  :{0}<br>", member.Language));
                Response.Write(string.Format("Vip : {0}<br>", member.Vip));
                Response.Write(string.Format("EmailClient : {0}<br>", member.EmailClient));
                Response.Write(string.Format("Location :<br>"));
                if (member.Location != null)
                {
                    Response.Write(string.Format("- Latitude : {0}<br>", member.Location.Latitude));
                    Response.Write(string.Format("- Longitude : {0}<br>", member.Location.Longitude));
                    Response.Write(string.Format("- Gmtoff : {0}<br>", member.Location.Gmtoff));
                    Response.Write(string.Format("- Dstoff : {0}<br>", member.Location.Dstoff));
                    Response.Write(string.Format("- Timezone : {0}<br>", member.Location.Timezone));
                    Response.Write(string.Format("- CountryCode : {0}<br>", member.Location.CountryCode));
                }
                Response.Write(string.Format("ListId : {0}<br>", member.ListId));
                for (int i = 0; member.Links != null && i < member.Links.Count; i++)
                {
                    Response.Write(string.Format("Links #{0}<br>", i + 1));
                    Response.Write(string.Format("- Rel : {0}<br>", member.Links[i].Rel));
                    Response.Write(string.Format("- Href : {0}<br>", member.Links[i].Href));
                    Response.Write(string.Format("- Method : {0}<br>", member.Links[i].Method));
                    Response.Write(string.Format("- TargetSchema : {0}<br>", member.Links[i].TargetSchema));
                }
                if (member.MergeFields != null)
                {
                    foreach (var tes in member.MergeFields)
                    {
                        Response.Write(string.Format("{0} : {1}<br>", tes.Key, tes.Value));
                    }
                }
            }
            private void DisplayError(Error error)
            {
                Response.Write(string.Format("Type:{0}<br>", error.Type));
                Response.Write(string.Format("Title:{0}<br>", error.Title));
                Response.Write(string.Format("Status:{0}<br>", error.Status));
                Response.Write(string.Format("Detail:{0}<br>", error.Detail));
                Response.Write(string.Format("Instance:{0}<br>", error.Instance));
                Response.Write(string.Format("Errors:{0}<br>", error.Errors));
            }
            private void DisplayList(List list)
            {
                Response.Write(string.Format("id : {0}<br>", list.Id));
                Response.Write(string.Format("name : {0}<br>", list.Name));
                Response.Write(string.Format("contact :<br>"));
                if (list.Contact != null)
                {
                    Response.Write(string.Format("- company : {0}<br>", list.Contact.Company));
                    Response.Write(string.Format("- address1 : {0}<br>", list.Contact.Address1));
                    Response.Write(string.Format("- address2 : {0}<br>", list.Contact.Address2));
                    Response.Write(string.Format("- city : {0}<br>", list.Contact.City));
                    Response.Write(string.Format("- state : {0}<br>", list.Contact.State));
                    Response.Write(string.Format("- zip : {0}<br>", list.Contact.Zip));
                }
                Response.Write(string.Format("permission_reminder : {0}<br>", list.PermissionReminder));
                Response.Write(string.Format("use_archive_bar : {0}<br>", list.UseArchiveBar));
                Response.Write(string.Format("campaign_defaults :<br>"));
                if (list.CampaignDefaults != null)
                {
                    Response.Write(string.Format("- from_name : {0}<br>", list.CampaignDefaults.FromName));
                    Response.Write(string.Format("- from_email : {0}<br>", list.CampaignDefaults.FromEmail));
                    Response.Write(string.Format("- subject : {0}<br>", list.CampaignDefaults.Subject));
                    Response.Write(string.Format("- language : {0}<br>", list.CampaignDefaults.Language));
                }
                Response.Write(string.Format("notify_on_subscribe : {0}<br>", list.NotifyOnSubscribe));
                Response.Write(string.Format("notify_on_unsubscribe : {0}<br>", list.NotifyOnUnsubscribe));
                Response.Write(string.Format("list_rating : {0}<br>", list.ListRating));
                Response.Write(string.Format("email_type_option : {0}<br>", list.EmailTypeOption));
                Response.Write(string.Format("subscribe_url_short : {0}<br>", list.SubscribeUrlShort));
                Response.Write(string.Format("subscribe_url_long : {0}<br>", list.SubscribeUrlLong));
                Response.Write(string.Format("beamer_address : {0}<br>", list.BeamerAddress));
                Response.Write(string.Format("visibility : {0}<br>", list.Visibility));
                Response.Write(string.Format("modules : <br>"));
                for (var i = 0; list.Modules != null && i < list.Modules.Length; i++)
                {
                    Response.Write(string.Format("- Rel : {0}<br>", list.Modules[i]));
                }
                Response.Write(string.Format("campaign_defaults :<br>"));
                if (list.Stats != null)
                {
                    Response.Write(string.Format("- member_count : {0}<br>", list.Stats.MemberCount));
                    Response.Write(string.Format("- unsubscribe_count : {0}<br>", list.Stats.UnsubscribeCount));
                    Response.Write(string.Format("- cleaned_count : {0}<br>", list.Stats.CleanedCount));
                    Response.Write(string.Format("- member_count_since_send : {0}<br>", list.Stats.MemberCountSinceSend));
                    Response.Write(string.Format("- unsubscribe_count_since_send : {0}<br>", list.Stats.UnsubscribeCountSinceSend));
                    Response.Write(string.Format("- cleaned_count_since_send : {0}<br>", list.Stats.CleanedCountSinceSend));
                    Response.Write(string.Format("- campaign_count : {0}<br>", list.Stats.CampaignCount));
                    Response.Write(string.Format("- campaign_last_sent : {0}<br>", list.Stats.CampaignLastSent));
                    Response.Write(string.Format("- merge_field_count : {0}<br>", list.Stats.MergeFieldCount));
                    Response.Write(string.Format("- avg_sub_rate : {0}<br>", list.Stats.AvgSubRate));
                    Response.Write(string.Format("- avg_unsub_rate : {0}<br>", list.Stats.AvgUnsubRate));
                    Response.Write(string.Format("- target_sub_rate : {0}<br>", list.Stats.TargetSubRate));
                    Response.Write(string.Format("- open_rate : {0}<br>", list.Stats.OpenRate));
                    Response.Write(string.Format("- click_rate : {0}<br>", list.Stats.ClickRate));
                    Response.Write(string.Format("- last_sub_date : {0}<br>", list.Stats.LastSubDate));
                    Response.Write(string.Format("- last_unsub_date : {0}<br>", list.Stats.LastUnsubDate));
                }
                for (int i = 0; list.Links != null && i < list.Links.Count; i++)
                {
                    Response.Write(string.Format("Links #{0}<br>", i + 1));
                    Response.Write(string.Format("- Rel : {0}<br>", list.Links[i].Rel));
                    Response.Write(string.Format("- Href : {0}<br>", list.Links[i].Href));
                    Response.Write(string.Format("- Method : {0}<br>", list.Links[i].Method));
                    Response.Write(string.Format("- TargetSchema : {0}<br>", list.Links[i].TargetSchema));
                    Response.Write(string.Format("- Schema : {0}", list.Links[i].Schema));
                }
            }
        }
    }
    


9 comments:

  1. Hi,
    Your code looks interesting but it is missing class definition for members and list. Is there any way to get them?

    ReplyDelete
  2. Too much for nothing. Good Bye.

    ReplyDelete
  3. Seems like a good opportunity to make available a zip file of the entire project... :(

    ReplyDelete
  4. did you tried https://github.com/brandonseydel/MailChimp.Net ? real world samples ?

    ReplyDelete
  5. Good Article But How to send Email to members ?

    Can you share the code

    How to send mail using your article can you share with me?

    ReplyDelete
  6. How to Create Campaign in runtime C# code
    then send members corresponding template to users
    in c# Code?

    ReplyDelete
  7. wihh nice info
    kunjung balik, di web kami banyak penawaran dan tips tentang kesehatan |
    | http://bit.ly/2KF5PhV |
    | http://bit.ly/2IsKafG |
    | http://bit.ly/2rTjt9J |

    ReplyDelete
  8. This value is not a valid datetime.
    Issue
    timestamp_opt

    ReplyDelete
  9. Great stuff, just what i was looking for. I hate blindly downloading bloated plugins from nuget, as my project is a highly secure one and we don't allow any plugins that we can't easily check ALL the code for. And we just simply needed something that had already been through the pain of building all of the correct references to the schema.. nice one.

    ReplyDelete