Beispiel #1
0
        public async Task SendRows <T>(string DataExtensionExternalKey, List <T> list)
        {
            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            await InsertRows(DataExtensionExternalKey, list);
        }
Beispiel #2
0
        public async Task <ContentCategories> GetContentFolders(string parentFolderId = null)
        {
            ContentCategories categories = null;
            string            serviceURL = this.ContentURL + FolderResource + "?$pagesize=" + PageSize;

            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            ServiceHandler serviceHandler = new ServiceHandler();
            string         result         = await serviceHandler.InvokeRESTServiceNoBody(serviceURL, accessToken);

            categories = ParseContentFolderServiceOutput(result);

            //Checking if more calls are required because the paging
            if (categories != null && categories.Items != null && categories.Items.Count < categories.Count)
            {
                ContentCategories overallCategories = new ContentCategories();
                overallCategories.Items = new System.Collections.Generic.List <Category>();

                overallCategories.Items.AddRange(categories.Items);
                overallCategories.Count = categories.Count;

                //The last call should have zero items, this indicates no more pages are available
                while (categories.Items.Count != 0)
                {
                    int pageToRequest = (int)(categories.Page + 1);
                    serviceURL += "&$page=" + pageToRequest;

                    //Because we are iterating, it's better to check if the token is still valid, with OAuth 2.0 the token only lasts 1079 seconds
                    if (accessToken == null || !accessToken.IsValid)
                    {
                        BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                        accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
                    }

                    result = await serviceHandler.InvokeRESTServiceNoBody(serviceURL, accessToken);

                    categories = ParseContentFolderServiceOutput(result);

                    if (categories == null)
                    {
                        break;
                    }

                    overallCategories.Items.AddRange(categories.Items);
                }

                categories = overallCategories;
            }

            return(categories);
        }
Beispiel #3
0
        public async Task <string> CreateFolder(string parentId, string name)
        {
            string resultId   = string.Empty;
            string serviceURL = this.ContentURL + FolderResource;

            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            RestClient  client  = new RestClient(serviceURL);
            RestRequest request = new RestRequest(Method.POST);

            request.AddHeader("Accept", "application/json");
            request.AddParameter("Authorization", "Bearer " + accessToken.Token, ParameterType.HttpHeader);

            StringBuilder message = new StringBuilder();

            message.Append("{\"Name\":\"" + name + "\",\"ParentId\":" + parentId + "}");

            request.AddParameter("application/json", message.ToString(), ParameterType.RequestBody);

            //Using Polly Retry policy
            var policy = Policy.Handle <WebException>()
                         .Or <HttpRequestException>()
                         .OrResult <IRestResponse>(r => r.StatusCode != HttpStatusCode.Created)
                         .RetryAsync(3);

            var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteTaskAsync(request));

            string serviceResult;

            if (policyResult.Outcome == OutcomeType.Successful)
            {
                IRestResponse webResponse = policyResult.Result;
                serviceResult = webResponse.Content;

                Dictionary <string, string> responseObj = JsonConvert.DeserializeObject <Dictionary <string, string> >(serviceResult);

                if (responseObj != null)
                {
                    resultId = responseObj["id"];
                }
            }
            else
            {
                throw new System.Exception($"{policyResult.FinalHandledResult.Content}");
            }

            return(resultId);
        }
Beispiel #4
0
        private async Task <string> GetStartAutomationRequestMessage(AutomationInfo automationInfo)
        {
            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            StringBuilder builder = new StringBuilder();

            builder.Append($"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><fueloauth xmlns=\"http://exacttarget.com\">{accessToken.Token}</fueloauth></s:Header>");
            builder.Append("<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><PerformRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\">");
            builder.Append($"<Options/><Action>start</Action><Definitions><Definition xsi:type=\"Automation\"><PartnerKey xsi:nil=\"true\"/><ObjectID>{automationInfo.ObjectID}</ObjectID></Definition></Definitions>");

            builder.Append("</PerformRequestMsg></s:Body></s:Envelope>");

            return(builder.ToString());
        }
Beispiel #5
0
        public async Task <string> TriggerEvent(Event customEvent)
        {
            string instanceId = string.Empty;

            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            //Setting up the request
            RestRequest request = new RestRequest(Method.POST);

            request.AddHeader("Accept", "application/json");
            request.AddParameter("Authorization", "Bearer " + accessToken.Token, ParameterType.HttpHeader);

            RestClient client = new RestClient(EventsURL);

            request.AddParameter("application/json", customEvent.ToJson(), ParameterType.RequestBody);

            //Using Polly Retry policy
            var policy = Policy.Handle <WebException>()
                         .Or <HttpRequestException>()
                         .OrResult <IRestResponse>(r => r.StatusCode != HttpStatusCode.Created)
                         .RetryAsync(3);

            var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteTaskAsync(request));

            Dictionary <string, string> result;

            if (policyResult.Outcome == OutcomeType.Successful)
            {
                IRestResponse webResponse = policyResult.Result;
                result = JsonConvert.DeserializeObject <Dictionary <string, string> >(webResponse.Content);
            }
            else
            {
                throw new System.Exception($"{policyResult.FinalHandledResult.Content}");
            }

            instanceId = result["eventInstanceId"];

            return(instanceId);
        }
Beispiel #6
0
        private async Task <string> GetScheduleAutomationRequestMessage(AutomationInfo automationInfo)
        {
            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            StringBuilder builder = new StringBuilder();

            builder.Append($"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><fueloauth xmlns=\"http://exacttarget.com\">{accessToken.Token}</fueloauth></s:Header>");
            builder.Append("<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><ScheduleRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\">");
            builder.Append($"<Options/><Action>start</Action><Interactions><Interaction xsi:type=\"Automation\"><PartnerKey xsi:nil=\"true\"/><ObjectID>{automationInfo.ObjectID}</ObjectID></Interaction></Interactions>");
            builder.Append($"<Schedule><StartDateTime>{DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")}</StartDateTime><RecurrenceType>Hourly</RecurrenceType><RecurrenceRangeType>EndOn</RecurrenceRangeType><Occurrences>2</Occurrences></Schedule>");
            builder.Append($"<ScheduleOptions>{DateTime.Now.AddDays(1).ToString("yyyy-MM-ddTHH:mm:ss")}</ScheduleOptions>");
            builder.Append("</ScheduleRequestMsg></s:Body></s:Envelope>");

            return(builder.ToString());
        }
Beispiel #7
0
        public async Task <string> CreateAsset(Asset asset)
        {
            string serviceURL = this.BaseRESTURL + AssetsResource;
            string result     = string.Empty;
            string url        = string.Empty;

            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            RestClient  client  = new RestClient(serviceURL);
            RestRequest request = new RestRequest(Method.POST);

            request.AddHeader("Accept", "application/json");
            request.AddParameter("Authorization", "Bearer " + accessToken.Token, ParameterType.HttpHeader);

            request.AddJsonBody(asset);

            var policy = Policy.Handle <WebException>()
                         .Or <HttpRequestException>()
                         .OrResult <IRestResponse>(r => r.StatusCode != HttpStatusCode.Created)
                         .RetryAsync(3);

            var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteTaskAsync(request));

            if (policyResult.Outcome == OutcomeType.Successful)
            {
                IRestResponse webResponse = policyResult.Result;
                result = webResponse.Content;

                //extracting url from response
                JObject jObject = JObject.Parse(result);
                url = (string)jObject.SelectToken("$['fileProperties']['publishedURL']");
            }
            else
            {
                throw new System.Exception($"{policyResult.FinalHandledResult.Content}");
            }

            return(url);
        }
Beispiel #8
0
        public async Task <AutomationInfo> GetAutomationInfo(string automationExternalKey)
        {
            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            StringBuilder builder = new StringBuilder();

            builder.Append($"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><fueloauth xmlns=\"http://exacttarget.com\">{accessToken.Token}</fueloauth></s:Header>");
            builder.Append("<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"><RetrieveRequest>");
            builder.Append($"<ObjectType>Automation</ObjectType><Properties>ProgramID</Properties><Properties>Status</Properties><Properties>Name</Properties><Properties>CustomerKey</Properties><Filter xsi:type=\"SimpleFilterPart\"><Property>CustomerKey</Property><SimpleOperator>equals</SimpleOperator><Value>{automationExternalKey}</Value></Filter>");

            builder.Append("</RetrieveRequest></RetrieveRequestMsg></s:Body></s:Envelope>");

            ServiceHandler client   = new ServiceHandler();
            string         response = await client.InvokeSOAPService(builder.ToString(), this.serviceURL);

            return(GetAutomationInfoFromResponse(response));
        }
Beispiel #9
0
        private async Task <string> CreateDataExtensionRequestMessage(DataExtension dataExtension)
        {
            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            StringBuilder builder = new StringBuilder();

            builder.Append($"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><fueloauth xmlns=\"http://exacttarget.com\">{accessToken.Token}</fueloauth></s:Header>");
            builder.Append("<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><CreateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\">");
            builder.Append($"<Options></Options><Objects xmlns:ns1=\"http://exacttarget.com/wsdl/partnerAPI\" xsi:type=\"ns1:DataExtension\"><CustomerKey>{dataExtension.CustomerKey}</CustomerKey>");

            if (dataExtension.FolderId != 0)
            {
                builder.Append($"<CategoryID>{dataExtension.FolderId}</CategoryID>");
            }

            builder.Append($"<Name>{dataExtension.Name}</Name><IsSendable>false</IsSendable><Fields>");

            foreach (DataExtensionColumn column in dataExtension.Columns)
            {
                builder.Append($"<Field><CustomerKey>{column.Name}</CustomerKey>");
                builder.Append($"<Name>{column.Name}</Name><FieldType>{column.InferedType}</FieldType><IsRequired>{(!column.IsNullable).ToString().ToLower()}</IsRequired>");

                if (column.InferedType == DataType.Text)
                {
                    builder.Append($"<MaxLength>{column.MaxLength}</MaxLength>");
                }

                builder.Append($"</Field>");
            }

            builder.Append("</Fields></Objects></CreateRequest></s:Body></s:Envelope>");

            return(builder.ToString());
        }
Beispiel #10
0
        public async Task <bool> DoesFolderExist(string id)
        {
            bool   exists     = false;
            string serviceURL = this.ContentURL + FolderResource + $"/{id}";

            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            ServiceHandler serviceHandler = new ServiceHandler();
            string         result         = await serviceHandler.InvokeRESTServiceNoBody(serviceURL, accessToken);

            if (!string.IsNullOrEmpty(result))
            {
                if (result.Contains(id))
                {
                    exists = true;
                }
            }

            return(exists);
        }
Beispiel #11
0
        /// <summary>
        /// Generates the request message to be send in the SOAP call
        /// </summary>
        /// <returns>The generated request message</returns>
        private async Task <string> GetRequestMessage <T>(string DataExtensionExternalKey, RequestParameters parameter = null)
        {
            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            StringBuilder builder = new StringBuilder();

            builder.Append($"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><fueloauth xmlns=\"http://exacttarget.com\">{accessToken.Token}</fueloauth></s:Header>");
            builder.Append("<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\">");
            builder.Append($"<RetrieveRequest><ObjectType>DataExtensionObject[{DataExtensionExternalKey}]</ObjectType>");

            if (parameter != null && !string.IsNullOrEmpty(parameter.RequestId))
            {
                builder.Append($"<ContinueRequest>{parameter.RequestId}</ContinueRequest>");
            }

            //Let's get all the properties
            PropertiesManager propertiesManager = new PropertiesManager();

            foreach (string prop in propertiesManager.GetDataExtensionFields <T>())
            {
                builder.Append($"<Properties>{prop}</Properties>");
            }

            if (parameter != null && !string.IsNullOrEmpty(parameter.Filter))
            {
                builder.Append(parameter.Filter);
            }

            builder.Append("</RetrieveRequest></RetrieveRequestMsg></s:Body></s:Envelope>");

            return(builder.ToString());
        }