PageRenderTime 68ms CodeModel.GetById 29ms RepoModel.GetById 0ms 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

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

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