PageRenderTime 68ms CodeModel.GetById 3ms app.highlight 53ms RepoModel.GetById 2ms app.codeStats 1ms

/FuelSDK-CSharp/ET_Client.cs

https://github.com/deg-core/FuelSDK-CSharp
C# | 1961 lines | 1709 code | 219 blank | 33 comment | 259 complexity | d8752cfd5357d8b1dc17739b38f7c327 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1using System;
   2using System.Collections.Generic;
   3using System.Linq;
   4using System.Text;
   5using System.Reflection;
   6using System.ServiceModel;
   7using System.Collections.Specialized;
   8using Newtonsoft.Json;
   9using Newtonsoft.Json.Linq;
  10using System.Net;
  11using System.IO;
  12using System.Xml.Linq;
  13using System.ServiceModel.Channels;
  14
  15
  16
  17namespace FuelSDK
  18{
  19    public class ET_Client
  20    {
  21        //Variables
  22        public string authToken;
  23        public SoapClient soapclient;
  24        private string appSignature = string.Empty;
  25        private string clientId = string.Empty;
  26        private string clientSecret = string.Empty;
  27        private string soapEndPoint = string.Empty;
  28        public string internalAuthToken = string.Empty;
  29        private string refreshKey = string.Empty;
  30        private DateTime authTokenExpiration = DateTime.Now;
  31        public string SDKVersion = "FuelSDX-C#-V.8";
  32
  33        //Constructor
  34        public ET_Client(NameValueCollection parameters = null)
  35        {
  36            //Get configuration file and set variables
  37            System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(@"FuelSDK_config.xml");
  38            foreach (System.Xml.XPath.XPathNavigator child in doc.CreateNavigator().Select("configuration"))
  39            {
  40                appSignature = child.SelectSingleNode("appSignature").Value.ToString().Trim();
  41                clientId = child.SelectSingleNode("clientId").Value.ToString().Trim();
  42                clientSecret = child.SelectSingleNode("clientSecret").Value.ToString().Trim();
  43                soapEndPoint = child.SelectSingleNode("soapEndPoint").Value.ToString().Trim();
  44            }         
  45
  46            //If JWT URL Parameter Used
  47            if (parameters != null && parameters.AllKeys.Contains("jwt"))
  48            {
  49                string encodedJWT = parameters["jwt"].ToString().Trim();
  50                String decodedJWT = JsonWebToken.Decode(encodedJWT, appSignature);
  51                JObject parsedJWT = JObject.Parse(decodedJWT);
  52                authToken = parsedJWT["request"]["user"]["oauthToken"].Value<string>().Trim();
  53                authTokenExpiration = DateTime.Now.AddSeconds(int.Parse(parsedJWT["request"]["user"]["expiresIn"].Value<string>().Trim()));
  54                internalAuthToken = parsedJWT["request"]["user"]["internalOauthToken"].Value<string>().Trim();
  55                refreshKey = parsedJWT["request"]["user"]["refreshToken"].Value<string>().Trim();
  56            }          
  57            else
  58            {
  59                refreshToken();
  60            }
  61
  62            // Find the appropriate endpoint for the acccount
  63            ET_Endpoint getSingleEndpoint = new ET_Endpoint();
  64            getSingleEndpoint.AuthStub = this;
  65            getSingleEndpoint.Type = "soap";
  66            GetReturn grSingleEndpoint = getSingleEndpoint.Get();
  67
  68            if (grSingleEndpoint.Status && grSingleEndpoint.Results.Length == 1){
  69                soapEndPoint =  ((ET_Endpoint)grSingleEndpoint.Results[0]).URL;
  70            } else {
  71                throw new Exception("Unable to determine stack using /platform/v1/endpoints: " + grSingleEndpoint.Message);
  72            }
  73
  74            //Create the SOAP binding for call with Oauth.
  75            BasicHttpBinding binding = new BasicHttpBinding();
  76            binding.Name = "UserNameSoapBinding";
  77            binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
  78            binding.MaxReceivedMessageSize = 2147483647;
  79            soapclient = new SoapClient(binding, new EndpointAddress(new Uri(soapEndPoint)));
  80            soapclient.ClientCredentials.UserName.UserName = "*";
  81            soapclient.ClientCredentials.UserName.Password = "*";
  82
  83        }
  84
  85        public void refreshToken(bool force = false)
  86        {
  87            //RefreshToken
  88            if ((authToken == null || authToken.Length == 0 || DateTime.Now.AddSeconds(300) > authTokenExpiration) || force)
  89            {
  90                //Get an internalAuthToken using clientId and clientSecret
  91                string strURL = "https://auth.exacttargetapis.com/v1/requestToken?legacy=1";
  92
  93                //Build the request
  94                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL.Trim());
  95                request.Method = "POST";
  96                request.ContentType = "application/json";
  97                request.UserAgent = this.SDKVersion;
  98
  99                string json;
 100                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
 101                {
 102
 103                    if (refreshKey.Length > 0)
 104                        json = @"{""clientId"": """ + clientId + @""", ""clientSecret"": """ + clientSecret + @""", ""refreshToken"": """ + refreshKey + @""", ""scope"": ""cas:" + internalAuthToken + @""" , ""accessType"": ""offline""}";
 105                    else
 106                        json = @"{""clientId"": """ + clientId + @""", ""clientSecret"": """ + clientSecret + @""", ""accessType"": ""offline""}";
 107                    streamWriter.Write(json);
 108                }
 109
 110                //Get the response
 111                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 112                Stream dataStream = response.GetResponseStream();
 113                StreamReader reader = new StreamReader(dataStream);
 114                string responseFromServer = reader.ReadToEnd();
 115                reader.Close();
 116                dataStream.Close();
 117                response.Close();
 118
 119                //Parse the response
 120                JObject parsedResponse = JObject.Parse(responseFromServer);
 121                internalAuthToken = parsedResponse["legacyToken"].Value<string>().Trim();
 122                authToken = parsedResponse["accessToken"].Value<string>().Trim();
 123                authTokenExpiration = DateTime.Now.AddSeconds(int.Parse(parsedResponse["expiresIn"].Value<string>().Trim()));
 124                refreshKey = parsedResponse["refreshToken"].Value<string>().Trim();
 125            }
 126        }
 127
 128        public FuelReturn AddSubscribersToList(string EmailAddress, string SubscriberKey, List<int> ListIDs)
 129        {
 130            return this.ProcessAddSubscriberToList(EmailAddress, SubscriberKey, ListIDs);
 131        }
 132
 133        public FuelReturn AddSubscribersToList(string EmailAddress, List<int> ListIDs)
 134        {
 135            return this.ProcessAddSubscriberToList(EmailAddress, null, ListIDs);
 136        }
 137
 138        protected FuelReturn ProcessAddSubscriberToList(string EmailAddress, string SubscriberKey, List<int> ListIDs)
 139        {
 140            ET_Subscriber sub = new ET_Subscriber();
 141            sub.EmailAddress = EmailAddress;
 142            if (SubscriberKey != null)
 143                sub.SubscriberKey = SubscriberKey;
 144            List<ET_SubscriberList> lLists = new List<ET_SubscriberList>();
 145            foreach (int listID in ListIDs)
 146            {
 147                ET_SubscriberList feList = new ET_SubscriberList();
 148                feList.ID = listID;
 149                lLists.Add(feList);
 150            }
 151            sub.AuthStub = this;
 152            sub.Lists = lLists.ToArray();
 153            PostReturn prAddSub = sub.Post();
 154            if (!prAddSub.Status && prAddSub.Results.Length > 0 && prAddSub.Results[0].ErrorCode == 12014)
 155            {
 156                return sub.Patch();
 157            }
 158            else
 159            {
 160                return prAddSub;
 161            }
 162        }
 163
 164        public FuelReturn CreateDataExtensions(ET_DataExtension[] ArrayOfET_DataExtension)
 165        {
 166
 167            List<ET_DataExtension> cleanedArray = new List<ET_DataExtension>();
 168
 169            foreach (ET_DataExtension de in ArrayOfET_DataExtension)
 170            {
 171                de.Fields = de.Columns;
 172                de.Columns = null;
 173                cleanedArray.Add(de);
 174            }
 175            return new PostReturn(cleanedArray.ToArray(), this);
 176        }
 177
 178    }
 179
 180    public class ResultDetail
 181    {
 182        public string StatusCode { get; set; }
 183        public string StatusMessage { get; set; }
 184        public int OrdinalID { get; set; }
 185        public int ErrorCode { get; set; }
 186        public int NewID { get; set; }
 187        public string NewObjectID { get; set; }
 188        public APIObject Object { get; set; }
 189    }
 190
 191    public class PostReturn : FuelReturn
 192    {
 193        public ResultDetail[] Results { get; set; }
 194
 195        public PostReturn(APIObject[] theObjects, ET_Client theClient)
 196        {
 197            this.Message = "";
 198            this.Status = true;
 199            this.MoreResults = false;
 200            string OverallStatus = string.Empty, RequestID = string.Empty;
 201            Result[] requestResults = new Result[0];
 202
 203            theClient.refreshToken();
 204            using (var scope = new OperationContextScope(theClient.soapclient.InnerChannel))
 205            {
 206                //Add oAuth token to SOAP header.
 207                XNamespace ns = "http://exacttarget.com";
 208                var oauthElement = new XElement(ns + "oAuthToken", theClient.internalAuthToken);
 209                var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
 210                OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);
 211
 212                var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
 213                OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
 214                httpRequest.Headers.Add(HttpRequestHeader.UserAgent, theClient.SDKVersion);
 215
 216                List<APIObject> lObjects = new List<APIObject>();
 217                foreach (APIObject ao in theObjects)
 218                {
 219                    lObjects.Add(this.TranslateObject(ao));
 220                }
 221
 222                requestResults = theClient.soapclient.Create(new CreateOptions(), lObjects.ToArray(), out RequestID, out OverallStatus);
 223
 224                this.Status = true;
 225                this.Code = 200;
 226                this.MoreResults = false;
 227                this.Message = "";
 228
 229                if (OverallStatus != "OK")
 230                {
 231                    this.Status = false;
 232                }
 233
 234                if (requestResults.GetType() == typeof(CreateResult[]) && requestResults.Length > 0)
 235                {
 236                    List<ResultDetail> results = new List<ResultDetail>();
 237                    foreach (CreateResult cr in requestResults)
 238                    {
 239                        ResultDetail detail = new ResultDetail();
 240                        if (cr.StatusCode != null)
 241                            detail.StatusCode = cr.StatusCode;
 242                        if (cr.StatusMessage != null)
 243                            detail.StatusMessage = cr.StatusMessage;
 244                        if (cr.NewObjectID != null)
 245                            detail.NewObjectID = cr.NewObjectID;
 246                        if (cr.Object != null)
 247                            detail.Object = this.TranslateObject(cr.Object);
 248                        detail.OrdinalID = cr.OrdinalID;
 249                        detail.ErrorCode = cr.ErrorCode;
 250                        detail.NewID = cr.NewID;
 251                        results.Add(detail);
 252                    }
 253                    this.Results = results.ToArray();
 254                }
 255            }
 256        }
 257
 258        public PostReturn(APIObject theObject)
 259        {
 260            this.Message = "";
 261            this.Status = true;
 262            this.MoreResults = false;
 263            string OverallStatus = string.Empty, RequestID = string.Empty;
 264            Result[] requestResults = new Result[0];
 265
 266            theObject.AuthStub.refreshToken();
 267            using (var scope = new OperationContextScope(theObject.AuthStub.soapclient.InnerChannel))
 268            {
 269                //Add oAuth token to SOAP header.
 270                XNamespace ns = "http://exacttarget.com";
 271                var oauthElement = new XElement(ns + "oAuthToken", theObject.AuthStub.internalAuthToken);
 272                var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
 273                OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);
 274
 275                var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
 276                OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
 277                httpRequest.Headers.Add(HttpRequestHeader.UserAgent, theObject.AuthStub.SDKVersion);
 278
 279                theObject = this.TranslateObject(theObject);
 280
 281                requestResults = theObject.AuthStub.soapclient.Create(new CreateOptions(), new APIObject[] { theObject }, out RequestID, out OverallStatus);
 282
 283                this.Status = true;
 284                this.Code = 200;
 285                this.MoreResults = false;
 286                this.Message = "";
 287
 288                if (OverallStatus != "OK")
 289                {
 290                    this.Status = false;
 291                }
 292
 293                if (requestResults.GetType() == typeof(CreateResult[]) && requestResults.Length > 0)
 294                {
 295                    List<ResultDetail> results = new List<ResultDetail>();
 296                    foreach (CreateResult cr in requestResults)
 297                    {
 298                        ResultDetail detail = new ResultDetail();
 299                        if (cr.StatusCode != null)
 300                            detail.StatusCode = cr.StatusCode;
 301                        if (cr.StatusMessage != null)
 302                            detail.StatusMessage = cr.StatusMessage;
 303                        if (cr.NewObjectID != null)
 304                            detail.NewObjectID = cr.NewObjectID;
 305                        if (cr.Object != null)
 306                            detail.Object = this.TranslateObject(cr.Object);
 307                        detail.OrdinalID = cr.OrdinalID;
 308                        detail.ErrorCode = cr.ErrorCode;
 309                        detail.NewID = cr.NewID;
 310                        results.Add(detail);
 311                    }
 312                    this.Results = results.ToArray();
 313                }
 314            }
 315        }
 316
 317        public PostReturn(FuelObject theObject)
 318        {
 319            this.Message = "";
 320            this.Status = true;
 321            this.MoreResults = false;
 322            string completeURL = theObject.Endpoint;
 323            string additionalQS;
 324
 325            theObject.AuthStub.refreshToken();
 326
 327            foreach (PropertyInfo prop in theObject.GetType().GetProperties())
 328            {
 329                if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
 330                    if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
 331                        completeURL = completeURL.Replace("{" + prop.Name + "}", prop.GetValue(theObject, null).ToString());
 332            }
 333
 334            bool match;
 335            if (theObject.RequiredURLProperties != null)
 336            {
 337                foreach (string urlProp in theObject.RequiredURLProperties)
 338                {
 339                    match = false;
 340
 341                    foreach (PropertyInfo prop in theObject.GetType().GetProperties())
 342                    {
 343                        if (theObject.URLProperties.Contains(prop.Name))
 344                            if (prop.GetValue(theObject, null) != null)
 345                            {
 346                                if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
 347                                    match = true;
 348                            }
 349                    }
 350                    if (match == false)
 351                        throw new Exception("Unable to process request due to missing required property: " + urlProp);
 352
 353                }
 354            }
 355
 356            // Clean up not required URL parameters
 357            int j = 0;
 358            if (theObject.URLProperties != null)
 359            {
 360                foreach (string urlProp in theObject.URLProperties)
 361                {
 362                    completeURL = completeURL.Replace("{" + urlProp + "}", "");
 363                    j++;
 364                }
 365            }
 366
 367            additionalQS = "access_token=" + theObject.AuthStub.authToken;
 368            completeURL = completeURL + "?" + additionalQS;
 369
 370            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(completeURL.Trim());
 371            request.Method = "POST";
 372            request.ContentType = "application/json";
 373            request.UserAgent = theObject.AuthStub.SDKVersion;
 374
 375            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
 376            {
 377                string jsonPayload = JsonConvert.SerializeObject(theObject);
 378                streamWriter.Write(jsonPayload);
 379            }
 380
 381            try
 382            {
 383                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 384                Stream dataStream = response.GetResponseStream();
 385                StreamReader reader = new StreamReader(dataStream);
 386                string responseFromServer = reader.ReadToEnd();
 387                reader.Close();
 388                dataStream.Close();
 389
 390                if (response != null)
 391                    this.Code = (int)response.StatusCode;
 392                {
 393                    if (response.StatusCode == HttpStatusCode.OK)
 394                    {
 395                        this.Status = true;
 396                        List<ResultDetail> AllResults = new List<ResultDetail>();
 397
 398                        if (responseFromServer.ToString().StartsWith("["))
 399                        {
 400                            JArray jsonArray = JArray.Parse(responseFromServer.ToString());
 401                            foreach (JObject obj in jsonArray)
 402                            {
 403                                APIObject currentObject = (APIObject)Activator.CreateInstance(theObject.GetType(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new object[] { obj }, null);
 404                                ResultDetail result = new ResultDetail();
 405                                result.Object = currentObject;
 406                                AllResults.Add(result);
 407                            }
 408
 409                            this.Results = AllResults.ToArray();
 410                        }
 411                        else
 412                        {
 413                            JObject jsonObject = JObject.Parse(responseFromServer.ToString());
 414                            ResultDetail result = new ResultDetail();
 415                            APIObject currentObject = (APIObject)Activator.CreateInstance(theObject.GetType(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new object[] { jsonObject }, null);
 416                            result.Object = currentObject;
 417                            AllResults.Add(result);
 418                            this.Results = AllResults.ToArray();
 419                        }
 420
 421
 422                    }
 423                    else
 424                    {
 425                        this.Status = false;
 426                        this.Message = response.ToString();
 427                    }
 428                }
 429
 430                response.Close();
 431            }
 432            catch (WebException we)
 433            {
 434                this.Code = (int)((HttpWebResponse)we.Response).StatusCode;
 435                this.Status = false;
 436                this.Results = new ResultDetail[] { };
 437                using (var stream = we.Response.GetResponseStream())
 438                using (var reader = new StreamReader(stream))
 439                {
 440                    Message = reader.ReadToEnd();
 441                }
 442            }
 443
 444
 445        }
 446
 447    }
 448
 449    public class SendReturn : PostReturn
 450    {
 451        public SendReturn(APIObject theObject)
 452            : base(theObject)
 453        {
 454
 455        }
 456    }
 457
 458    public class HelperReturn : PostReturn
 459    {
 460        public HelperReturn(APIObject theObject)
 461            : base(theObject)
 462        {
 463
 464        }
 465    }
 466
 467    public class PatchReturn : FuelReturn
 468    {
 469        public ResultDetail[] Results { get; set; }
 470
 471        public PatchReturn(APIObject theObject)
 472        {
 473            string OverallStatus = string.Empty, RequestID = string.Empty;
 474            Result[] requestResults = new Result[0];
 475
 476            theObject.AuthStub.refreshToken();
 477            using (var scope = new OperationContextScope(theObject.AuthStub.soapclient.InnerChannel))
 478            {
 479                //Add oAuth token to SOAP header.
 480                XNamespace ns = "http://exacttarget.com";
 481                var oauthElement = new XElement(ns + "oAuthToken", theObject.AuthStub.internalAuthToken);
 482                var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
 483                OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);
 484
 485                var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
 486                OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
 487                httpRequest.Headers.Add(HttpRequestHeader.UserAgent, theObject.AuthStub.SDKVersion);
 488
 489                theObject = this.TranslateObject(theObject);
 490                requestResults = theObject.AuthStub.soapclient.Update(new UpdateOptions(), new APIObject[] { theObject }, out RequestID, out OverallStatus);
 491
 492                this.Status = true;
 493                this.Code = 200;
 494                this.MoreResults = false;
 495                this.Message = "";
 496
 497                if (OverallStatus != "OK")
 498                {
 499                    this.Status = false;
 500                }
 501
 502                if (requestResults.GetType() == typeof(UpdateResult[]) && requestResults.Length > 0)
 503                {
 504                    List<ResultDetail> results = new List<ResultDetail>();
 505                    foreach (UpdateResult cr in requestResults)
 506                    {
 507                        ResultDetail detail = new ResultDetail();
 508                        if (cr.StatusCode != null)
 509                            detail.StatusCode = cr.StatusCode;
 510                        if (cr.StatusMessage != null)
 511                            detail.StatusMessage = cr.StatusMessage;
 512                        if (cr.Object != null)
 513                            detail.Object = this.TranslateObject(cr.Object);
 514                        detail.OrdinalID = cr.OrdinalID;
 515                        detail.ErrorCode = cr.ErrorCode;
 516                        results.Add(detail);
 517                    }
 518                    this.Results = results.ToArray();
 519                }
 520            }
 521        }
 522    }
 523
 524    public class DeleteReturn : FuelReturn
 525    {
 526        public ResultDetail[] Results { get; set; }
 527
 528        public DeleteReturn(APIObject theObject)
 529        {
 530            string OverallStatus = string.Empty, RequestID = string.Empty;
 531            Result[] requestResults = new Result[0];
 532
 533            theObject.AuthStub.refreshToken();
 534            using (var scope = new OperationContextScope(theObject.AuthStub.soapclient.InnerChannel))
 535            {
 536                //Add oAuth token to SOAP header.
 537                XNamespace ns = "http://exacttarget.com";
 538                var oauthElement = new XElement(ns + "oAuthToken", theObject.AuthStub.internalAuthToken);
 539                var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
 540                OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);
 541
 542                var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
 543                OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
 544                httpRequest.Headers.Add(HttpRequestHeader.UserAgent, theObject.AuthStub.SDKVersion);
 545                theObject = this.TranslateObject(theObject);
 546                requestResults = theObject.AuthStub.soapclient.Delete(new DeleteOptions(), new APIObject[] { theObject }, out RequestID, out OverallStatus);
 547
 548                this.Status = true;
 549                this.Code = 200;
 550                this.MoreResults = false;
 551                this.Message = "";
 552
 553                if (OverallStatus != "OK")
 554                {
 555                    this.Status = false;
 556                }
 557
 558                if (requestResults.GetType() == typeof(DeleteResult[]) && requestResults.Length > 0)
 559                {
 560                    List<ResultDetail> results = new List<ResultDetail>();
 561                    foreach (DeleteResult cr in requestResults)
 562                    {
 563                        ResultDetail detail = new ResultDetail();
 564                        if (cr.StatusCode != null)
 565                            detail.StatusCode = cr.StatusCode;
 566                        if (cr.StatusMessage != null)
 567                            detail.StatusMessage = cr.StatusMessage;
 568                        if (cr.Object != null)
 569                            detail.Object = this.TranslateObject(cr.Object);
 570                        detail.OrdinalID = cr.OrdinalID;
 571                        detail.ErrorCode = cr.ErrorCode;
 572                        results.Add(detail);
 573                    }
 574                    this.Results = results.ToArray();
 575                }
 576            }
 577        }
 578
 579        public DeleteReturn(FuelObject theObject)
 580        {
 581
 582            this.Message = "";
 583            this.Status = true;
 584            this.MoreResults = false;
 585            this.Results = new ResultDetail[] { };
 586
 587            
 588            theObject.AuthStub.refreshToken();
 589
 590            string completeURL = theObject.Endpoint;
 591            string additionalQS;
 592
 593            // All URL Props are required when doing Delete	
 594            bool match;
 595            if (theObject.URLProperties != null)
 596            {
 597                foreach (string urlProp in theObject.URLProperties)
 598                {
 599                    match = false;
 600                    if (theObject != null)
 601                    {
 602                        foreach (PropertyInfo prop in theObject.GetType().GetProperties())
 603                        {
 604                            if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
 605                                if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
 606                                    match = true;
 607                        }
 608                        if (match == false)
 609                            throw new Exception("Unable to process request due to missing required prop: " + urlProp);
 610                    }
 611                    else
 612                        throw new Exception("Unable to process request due to missing required prop: " + urlProp);
 613                }
 614            }
 615
 616            if (theObject != null)
 617            {
 618                foreach (PropertyInfo prop in theObject.GetType().GetProperties())
 619                {
 620                    if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
 621                        if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
 622                            completeURL = completeURL.Replace("{" + prop.Name + "}", prop.GetValue(theObject, null).ToString());
 623                }
 624            }
 625
 626            additionalQS = "access_token=" + theObject.AuthStub.authToken;
 627            completeURL = completeURL + "?" + additionalQS;
 628            restDelete(theObject, completeURL);
 629        }
 630
 631        private void restDelete(FuelObject theObject, string url)
 632        {
 633            //Build the request
 634            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.Trim());
 635            request.Method = "DELETE";
 636            request.ContentType = "application/json";
 637            request.UserAgent = theObject.AuthStub.SDKVersion;
 638
 639            //Get the response
 640            try
 641            {
 642                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 643                Stream dataStream = response.GetResponseStream();
 644                StreamReader reader = new StreamReader(dataStream);
 645                string responseFromServer = reader.ReadToEnd();
 646                reader.Close();
 647                dataStream.Close();
 648
 649                if (response != null)
 650                    this.Code = (int)response.StatusCode;
 651                {
 652                    if (response.StatusCode == HttpStatusCode.OK)
 653                    {
 654                        this.Status = true;
 655                    }
 656                    else
 657                    {
 658                        this.Status = false;
 659                        this.Message = response.ToString();
 660                    }
 661                }
 662
 663                response.Close();
 664            }
 665            catch (WebException we)
 666            {
 667                this.Code = (int)((HttpWebResponse)we.Response).StatusCode;
 668                this.Status = false;
 669                using (var stream = we.Response.GetResponseStream())
 670                using (var reader = new StreamReader(stream))
 671                {
 672                    this.Message = reader.ReadToEnd();
 673                }
 674            }
 675        }
 676    }
 677
 678    public class GetReturn : FuelReturn
 679    {
 680        public int LastPageNumber { get; set; }
 681
 682        public APIObject[] Results { get; set; }
 683
 684        public GetReturn(APIObject theObject) : this(theObject, false, null) { }
 685        public GetReturn(APIObject theObject, Boolean Continue, String OverrideObjectType)
 686        {
 687            string OverallStatus = string.Empty, RequestID = string.Empty;
 688            APIObject[] objectResults = new APIObject[0];
 689            theObject.AuthStub.refreshToken();
 690            this.Results = new APIObject[0];
 691            using (var scope = new OperationContextScope(theObject.AuthStub.soapclient.InnerChannel))
 692            {
 693                //Add oAuth token to SOAP header.
 694                XNamespace ns = "http://exacttarget.com";
 695                var oauthElement = new XElement(ns + "oAuthToken", theObject.AuthStub.internalAuthToken);
 696                var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
 697                OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);
 698
 699                var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
 700                OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
 701                httpRequest.Headers.Add(HttpRequestHeader.UserAgent, theObject.AuthStub.SDKVersion);
 702
 703                RetrieveRequest rr = new RetrieveRequest();
 704                if (Continue)
 705                {
 706                    if (theObject.LastRequestID == null)
 707                    {
 708                        throw new Exception("Unable to call GetMoreResults without first making successful Get() request");
 709                    }
 710                    rr.ContinueRequest = theObject.LastRequestID;
 711                }
 712                else
 713                {
 714                    if (theObject.SearchFilter != null)
 715                    {
 716                        rr.Filter = theObject.SearchFilter;
 717                    }
 718
 719                    // Use the name from the object passed in unless an override is passed (Used for DataExtensionObject)
 720                    if (OverrideObjectType == null)
 721                        rr.ObjectType = this.TranslateObject(theObject).GetType().ToString().Replace("FuelSDK.", "");
 722                    else
 723                        rr.ObjectType = OverrideObjectType;
 724
 725                    //If they didn't specify Props then we look them up using Info()
 726                    if (theObject.Props == null && theObject.GetType().GetMethod("Info") != null)
 727                    {
 728                        InfoReturn ir = new InfoReturn(theObject);
 729                        List<string> lProps = new List<string>();
 730                        if (ir.Status)
 731                        {
 732                            foreach (ET_PropertyDefinition pd in ir.Results)
 733                            {
 734                                if (pd.IsRetrievable)
 735                                    lProps.Add(pd.Name);
 736                            }
 737                        }
 738                        else
 739                        {
 740                            throw new Exception("Unable to find properties for object in order to perform Get() request");
 741                        }
 742                        rr.Properties = lProps.ToArray();
 743                    }
 744                    else
 745                        rr.Properties = theObject.Props;
 746                }
 747                OverallStatus = theObject.AuthStub.soapclient.Retrieve(rr, out RequestID, out objectResults);
 748
 749                this.RequestID = RequestID;
 750
 751                if (objectResults.Length > 0)
 752                {
 753                    List<APIObject> cleanedObjectResults = new List<APIObject>();
 754                    foreach (APIObject obj in objectResults)
 755                    {
 756                        cleanedObjectResults.Add(this.TranslateObject(obj));
 757                    }
 758                    this.Results = cleanedObjectResults.ToArray();
 759                }
 760
 761                this.Status = true;
 762                this.Code = 200;
 763                this.MoreResults = false;
 764                this.Message = "";
 765
 766                if (OverallStatus != "OK" && OverallStatus != "MoreDataAvailable")
 767                {
 768                    this.Status = false;
 769                    this.Message = OverallStatus;
 770                }
 771                else if (OverallStatus == "MoreDataAvailable")
 772                {
 773                    this.MoreResults = true;
 774                }
 775            }
 776        }
 777
 778        public GetReturn(FuelObject theObject)
 779        {
 780            this.Message = "";
 781            this.Status = true;
 782            this.MoreResults = false;
 783            this.Results = new APIObject[] { };
 784
 785            theObject.AuthStub.refreshToken();
 786
 787            string completeURL = theObject.Endpoint;
 788            string additionalQS = "";
 789            bool boolAdditionalQS = false;
 790
 791            if (theObject != null)
 792            {
 793                foreach (PropertyInfo prop in theObject.GetType().GetProperties())
 794                {
 795                    if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
 796                        if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
 797                            completeURL = completeURL.Replace("{" + prop.Name + "}", prop.GetValue(theObject, null).ToString());
 798                }
 799            }
 800
 801            ////props code for paging
 802            if (theObject.Page != 0)
 803            {
 804                additionalQS += "$page=" + theObject.Page;
 805                boolAdditionalQS = true;
 806            }
 807
 808            bool match;
 809            if (theObject.RequiredURLProperties != null)
 810            {
 811                foreach (string urlProp in theObject.RequiredURLProperties)
 812                {
 813                    match = false;
 814                    if (theObject != null)
 815                    {
 816                        foreach (PropertyInfo prop in theObject.GetType().GetProperties())
 817                        {
 818                            if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
 819                                if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
 820                                    match = true;
 821                        }
 822
 823                        if (match == false)
 824                            throw new Exception("Unable to process request due to missing required prop: " + urlProp);
 825                    }
 826                    else
 827                        throw new Exception("Unable to process request due to missing required prop: " + urlProp);
 828                }
 829            }
 830
 831            //Clean up not required URL parameters
 832            int j = 0;
 833            if (theObject.URLProperties != null)
 834            {
 835                foreach (string urlProp in theObject.URLProperties)
 836                {
 837                    completeURL = completeURL.Replace("{" + urlProp + "}", "");
 838                    j++;
 839                }
 840            }
 841
 842            if (!boolAdditionalQS)
 843                additionalQS += "access_token=" + theObject.AuthStub.authToken;
 844            else
 845                additionalQS += "&access_token=" + theObject.AuthStub.authToken;
 846
 847            completeURL = completeURL + "?" + additionalQS;
 848            restGet(ref theObject, completeURL);
 849        }
 850
 851        private void restGet(ref FuelObject theObject, string url)
 852        {
 853            //Build the request
 854            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.Trim());
 855            request.Method = "GET";
 856            request.ContentType = "application/json";
 857            request.UserAgent = theObject.AuthStub.SDKVersion;
 858
 859            //Get the response
 860            try
 861            {
 862                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 863                Stream dataStream = response.GetResponseStream();
 864                StreamReader reader = new StreamReader(dataStream);
 865                string responseFromServer = reader.ReadToEnd();
 866                reader.Close();
 867                dataStream.Close();
 868
 869                if (response != null)
 870                    this.Code = (int)response.StatusCode;
 871                {
 872                    if (response.StatusCode == HttpStatusCode.OK)
 873                    {
 874                        this.Status = true;                        
 875                        if (responseFromServer != null)
 876                        {
 877                            JObject parsedResponse = JObject.Parse(responseFromServer);
 878                            //Check on the paging information from response
 879                            if (parsedResponse["page"] != null)
 880                            {
 881                                this.LastPageNumber = int.Parse(parsedResponse["page"].Value<string>().Trim());
 882                                int pageSize = int.Parse(parsedResponse["pageSize"].Value<string>().Trim());
 883
 884                                int count = -1;
 885                                if (parsedResponse["count"] != null)
 886                                {
 887                                    count = int.Parse(parsedResponse["count"].Value<string>().Trim());
 888                                }
 889                                else if (parsedResponse["totalCount"] != null)
 890                                {
 891                                    count = int.Parse(parsedResponse["totalCount"].Value<string>().Trim());
 892                                }
 893
 894                                if (count != -1 && (count > (this.LastPageNumber * pageSize)))
 895                                {
 896                                    this.MoreResults = true;
 897                                }
 898                            }
 899
 900                            APIObject[] getResults = new APIObject[] { };
 901
 902                            if (parsedResponse["items"] != null)
 903                                getResults = processResults(parsedResponse["items"].ToString().Trim(), theObject.GetType());
 904                            else if (parsedResponse["entities"] != null)
 905                                getResults = processResults(parsedResponse["entities"].ToString().Trim(), theObject.GetType());
 906                            else
 907                                getResults = processResults(responseFromServer.Trim(), theObject.GetType());
 908
 909                            this.Results = getResults.ToArray();
 910                        }
 911                    }
 912                    else
 913                    {
 914                        this.Status = false;
 915                        this.Message = response.ToString();
 916                    }
 917                }
 918                response.Close();
 919            }
 920            catch (WebException we)
 921            {
 922                this.Code = (int)((HttpWebResponse)we.Response).StatusCode;
 923                this.Status = false;
 924                using (var stream = we.Response.GetResponseStream())
 925                using (var reader = new StreamReader(stream))
 926                {
 927                    this.Message = reader.ReadToEnd();
 928                }
 929            }
 930        }
 931
 932        protected APIObject[] processResults(string restResponse, Type fuelType)
 933        {
 934            List<APIObject> allObjects = new System.Collections.Generic.List<APIObject>();
 935
 936            if (restResponse != null)
 937            {
 938                if (JsonConvert.DeserializeObject(restResponse.ToString()) != null && JsonConvert.DeserializeObject(restResponse.ToString()).ToString() != "")
 939                {
 940                    if (restResponse.ToString().StartsWith("["))
 941                    {
 942                        JArray jsonArray = JArray.Parse(restResponse.ToString());
 943                        foreach (JObject obj in jsonArray)
 944                        {
 945                            APIObject currentObject = (APIObject)Activator.CreateInstance(fuelType, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new object[] { obj }, null);
 946                            allObjects.Add(currentObject);
 947                        }
 948
 949                        return allObjects.ToArray();
 950                    }
 951                    else
 952                    {
 953                        JObject jsonObject = JObject.Parse(restResponse.ToString());
 954                        ResultDetail result = new ResultDetail();
 955                        APIObject currentObject = (APIObject)Activator.CreateInstance(fuelType, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new object[] { jsonObject }, null);
 956                        allObjects.Add(currentObject);
 957                        return allObjects.ToArray();
 958                    }
 959                }
 960                else
 961                    return allObjects.ToArray();
 962            }
 963            else
 964                return allObjects.ToArray();
 965        }
 966    }
 967
 968    public class InfoReturn : FuelReturn
 969    {
 970        public ET_PropertyDefinition[] Results { get; set; }
 971        public InfoReturn(APIObject theObject)
 972        {
 973            string RequestID = string.Empty;
 974            theObject.AuthStub.refreshToken();
 975            this.Results = new ET_PropertyDefinition[0];
 976            using (var scope = new OperationContextScope(theObject.AuthStub.soapclient.InnerChannel))
 977            {
 978                //Add oAuth token to SOAP header.
 979                XNamespace ns = "http://exacttarget.com";
 980                var oauthElement = new XElement(ns + "oAuthToken", theObject.AuthStub.internalAuthToken);
 981                var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
 982                OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);
 983
 984                var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
 985                OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
 986                httpRequest.Headers.Add(HttpRequestHeader.UserAgent, theObject.AuthStub.SDKVersion);
 987
 988                ObjectDefinitionRequest odr = new ObjectDefinitionRequest();
 989                odr.ObjectType = this.TranslateObject(theObject).GetType().ToString().Replace("FuelSDK.", "");
 990                ObjectDefinition[] definitionResults = theObject.AuthStub.soapclient.Describe(new ObjectDefinitionRequest[] { odr }, out RequestID);
 991
 992                this.RequestID = RequestID;
 993                this.Status = true;
 994                this.Code = 200;
 995                this.MoreResults = false;
 996                this.Message = "";
 997
 998
 999                if (definitionResults.Length > 0)
1000                {
1001
1002                    List<ET_PropertyDefinition> cleanedObjectResults = new List<ET_PropertyDefinition>();
1003                    foreach (PropertyDefinition obj in definitionResults[0].Properties)
1004                    {
1005                        cleanedObjectResults.Add((ET_PropertyDefinition)(this.TranslateObject(obj)));
1006                    }
1007                    this.Results = cleanedObjectResults.ToArray();
1008                }
1009                else
1010                {
1011                    this.Status = false;
1012                }
1013            }
1014        }
1015    }
1016
1017    public abstract class FuelReturn
1018    {
1019        public Boolean Status { get; set; }
1020        public String Message { get; set; }
1021        public Boolean MoreResults { get; set; }
1022        public int Code { get; set; }
1023        public string RequestID { get; set; }
1024
1025        private Dictionary<Type, Type> translator = new Dictionary<Type, Type>();
1026
1027        public FuelReturn()
1028        {
1029            translator.Add(typeof(ET_Folder), typeof(DataFolder));
1030            translator.Add(typeof(DataFolder), typeof(ET_Folder));
1031
1032            translator.Add(typeof(ET_List), typeof(List));
1033            translator.Add(typeof(List), typeof(ET_List));
1034
1035            translator.Add(typeof(ET_ContentArea), typeof(ContentArea));
1036            translator.Add(typeof(ContentArea), typeof(ET_ContentArea));
1037
1038            translator.Add(typeof(ET_ObjectDefinition), typeof(ObjectDefinition));
1039            translator.Add(typeof(ObjectDefinition), typeof(ET_ObjectDefinition));
1040
1041            translator.Add(typeof(ET_PropertyDefinition), typeof(PropertyDefinition));
1042            translator.Add(typeof(PropertyDefinition), typeof(ET_PropertyDefinition));
1043
1044            translator.Add(typeof(Subscriber), typeof(ET_Subscriber));
1045            translator.Add(typeof(ET_Subscriber), typeof(Subscriber));
1046
1047            translator.Add(typeof(ET_ProfileAttribute), typeof(FuelSDK.Attribute));
1048            translator.Add(typeof(FuelSDK.Attribute), typeof(ET_ProfileAttribute));
1049
1050            translator.Add(typeof(ET_Email), typeof(FuelSDK.Email));
1051            translator.Add(typeof(FuelSDK.Email), typeof(ET_Email));
1052
1053            translator.Add(typeof(ET_SubscriberList), typeof(FuelSDK.SubscriberList));
1054            translator.Add(typeof(FuelSDK.SubscriberList), typeof(ET_SubscriberList));
1055
1056            translator.Add(typeof(ET_List_Subscriber), typeof(FuelSDK.ListSubscriber));
1057            translator.Add(typeof(FuelSDK.ListSubscriber), typeof(ET_List_Subscriber));
1058
1059            translator.Add(typeof(ET_DataExtension), typeof(FuelSDK.DataExtension));
1060            translator.Add(typeof(FuelSDK.DataExtension), typeof(ET_DataExtension));
1061
1062            translator.Add(typeof(ET_DataExtensionColumn), typeof(FuelSDK.DataExtensionField));
1063            translator.Add(typeof(FuelSDK.DataExtensionField), typeof(ET_DataExtensionColumn));
1064
1065            translator.Add(typeof(ET_DataExtensionRow), typeof(FuelSDK.DataExtensionObject));
1066            translator.Add(typeof(FuelSDK.DataExtensionObject), typeof(ET_DataExtensionRow));
1067
1068            translator.Add(typeof(ET_SendClassification), typeof(FuelSDK.SendClassification));
1069            translator.Add(typeof(FuelSDK.SendClassification), typeof(ET_SendClassification));
1070
1071            translator.Add(typeof(ET_SenderProfile), typeof(FuelSDK.SenderProfile));
1072            translator.Add(typeof(FuelSDK.SenderProfile), typeof(ET_SenderProfile));
1073
1074            translator.Add(typeof(ET_DeliveryProfile), typeof(FuelSDK.DeliveryProfile));
1075            translator.Add(typeof(FuelSDK.DeliveryProfile), typeof(ET_DeliveryProfile));
1076
1077            translator.Add(typeof(ET_TriggeredSend), typeof(FuelSDK.TriggeredSendDefinition));
1078            translator.Add(typeof(FuelSDK.TriggeredSendDefinition), typeof(ET_TriggeredSend));
1079
1080            // The translation for this is handled in the Get() method for DataExtensionObject so no need to translate it
1081            translator.Add(typeof(APIProperty), typeof(APIProperty));
1082
1083            translator.Add(typeof(ET_Trigger), typeof(FuelSDK.TriggeredSend));
1084            translator.Add(typeof(FuelSDK.TriggeredSend), typeof(ET_Trigger));
1085
1086            // Tracking Events
1087            translator.Add(typeof(ET_BounceEvent), typeof(BounceEvent));
1088            translator.Add(typeof(BounceEvent), typeof(ET_BounceEvent));
1089            translator.Add(typeof(OpenEvent), typeof(ET_OpenEvent));
1090            translator.Add(typeof(ET_OpenEvent), typeof(OpenEvent));
1091            translator.Add(typeof(ET_ClickEvent), typeof(ClickEvent));
1092            translator.Add(typeof(ClickEvent), typeof(ET_ClickEvent));
1093            translator.Add(typeof(ET_UnsubEvent), typeof(UnsubEvent));
1094            translator.Add(typeof(UnsubEvent), typeof(ET_UnsubEvent));
1095            translator.Add(typeof(ET_SentEvent), typeof(SentEvent));
1096            translator.Add(typeof(SentEvent), typeof(ET_SentEvent));
1097
1098        }
1099
1100
1101        public APIObject TranslateObject(APIObject inputObject)
1102        {
1103
1104            if (this.translator.ContainsKey(inputObject.GetType()))
1105            {
1106                APIObject returnObject = (APIObject)Activator.CreateInstance(translator[inputObject.GetType()]);
1107
1108                foreach (PropertyInfo prop in inputObject.GetType().GetProperties())
1109                {
1110                    if (prop.PropertyType.IsSubclassOf(typeof(APIObject)) && prop.GetValue(inputObject, null) != null)
1111                    {
1112                        prop.SetValue(returnObject, this.TranslateObject(prop.GetValue(inputObject, null)), null);
1113                    }
1114                    else if (translator.ContainsKey(prop.PropertyType) && prop.GetValue(inputObject, null) != null)
1115                    {
1116                        prop.SetValue(returnObject, this.TranslateObject(prop.GetValue(inp

Large files files are truncated, but you can click here to view the full file