Beispiel #1
0
 /// <summary>
 /// Retrieve all blocks.
 /// </summary>
 /// <param name="startDate">The start date.</param>
 /// <param name="endDate">The end date.</param>
 /// <param name="limit">The limit.</param>
 /// <param name="offset">The offset.</param>
 /// <param name="onBehalfOf">The user to impersonate.</param>
 /// <param name="cancellationToken">Cancellation token.</param>
 /// <returns>
 /// An array of <see cref="Block">Blocks</see>.
 /// </returns>
 public Task <Block[]> GetAllAsync(DateTime?startDate = null, DateTime?endDate = null, int limit = 25, int offset = 0, string onBehalfOf = null, CancellationToken cancellationToken = default)
 {
     return(_client
            .GetAsync(_endpoint)
            .OnBehalfOf(onBehalfOf)
            .WithArgument("start_time", startDate?.ToUnixTime())
            .WithArgument("end_time", endDate?.ToUnixTime())
            .WithArgument("limit", limit)
            .WithArgument("offset", offset)
            .WithCancellationToken(cancellationToken)
            .AsSendGridObject <Block[]>());
 }
Beispiel #2
0
 /// <summary>
 /// Get all globally unsubscribed email addresses.
 /// </summary>
 /// <param name="startDate">The start date.</param>
 /// <param name="endDate">The end date.</param>
 /// <param name="searchTerm">The search term.</param>
 /// <param name="limit">The limit.</param>
 /// <param name="offset">The offset.</param>
 /// <param name="onBehalfOf">The user to impersonate.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// An array of <see cref="GlobalSuppression"/>.
 /// </returns>
 /// <remarks>
 /// After much trial and error, we came to the conclusion that SendGrid allows you to search
 /// for addresses that "begin with" your search term. So, if you have two email addresses on
 /// your global suppression list such as [email protected] and [email protected] for example,
 /// you will be able to search for 'user1', or 'user2' or even 'user' but you cannot search
 /// for 'hotmail' or 'gmail'.
 ///
 /// Also note that SendGrid requires that your search term contain at least three characters.
 /// </remarks>
 public Task <GlobalSuppression[]> GetAllAsync(DateTime?startDate = null, DateTime?endDate = null, string searchTerm = null, int limit = 50, int offset = 0, string onBehalfOf = null, CancellationToken cancellationToken = default)
 {
     return(_client
            .GetAsync("suppression/unsubscribes")
            .OnBehalfOf(onBehalfOf)
            .WithArgument("email", searchTerm)
            .WithArgument("start_time", startDate?.ToUnixTime())
            .WithArgument("end_time", endDate?.ToUnixTime())
            .WithArgument("limit", limit)
            .WithArgument("offset", offset)
            .WithCancellationToken(cancellationToken)
            .AsObject <GlobalSuppression[]>());
 }
Beispiel #3
0
        /// <summary>
        /// List absentees of a webinar that occured in the past.
        /// </summary>
        /// <param name="uuid">The webinar UUID.</param>
        /// <param name="recordsPerPage">The number of records to return.</param>
        /// <param name="pagingToken">The paging token.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// An array of <see cref="Participant" />.
        /// </returns>
        public Task <PaginatedResponseWithToken <Participant> > GetAbsenteesAsync(string uuid, int recordsPerPage = 30, string pagingToken = null, CancellationToken cancellationToken = default)
        {
            if (recordsPerPage < 1 || recordsPerPage > 300)
            {
                throw new ArgumentOutOfRangeException(nameof(recordsPerPage), "Records per page must be between 1 and 300");
            }

            return(_client
                   .GetAsync($"past_webinars/{uuid}/absentees")
                   .WithArgument("page_size", recordsPerPage)
                   .WithArgument("next_page_token", pagingToken)
                   .WithCancellationToken(cancellationToken)
                   .AsPaginatedResponseWithToken <Participant>("registrants"));
        }
Beispiel #4
0
        /// <summary>
        /// Retrieve the names of all IP pools.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The names of all existing IP pools.
        /// </returns>
        public async Task <string[]> GetAllNamesAsync(CancellationToken cancellationToken = default)
        {
            var result = await _client
                         .GetAsync(_endpoint)
                         .WithCancellationToken(cancellationToken)
                         .AsRawJsonDocument()
                         .ConfigureAwait(false);

            var allNames = result.RootElement.EnumerateArray()
                           .Select(o => o.GetProperty("name").GetString())
                           .ToArray();

            return(allNames);
        }
Beispiel #5
0
        public Task <PaginatedResponse <Webinar> > GetAllAsync(string userId, int recordsPerPage = 30, int page = 1, CancellationToken cancellationToken = default)
        {
            if (recordsPerPage < 1 || recordsPerPage > 300)
            {
                throw new ArgumentOutOfRangeException(nameof(recordsPerPage), "Records per page must be between 1 and 300");
            }

            return(_client
                   .GetAsync($"users/{userId}/webinars")
                   .WithArgument("page_size", recordsPerPage)
                   .WithArgument("page", page)
                   .WithCancellationToken(cancellationToken)
                   .AsPaginatedResponse <Webinar>("webinars", new WebinarConverter()));
        }
Beispiel #6
0
        /// <summary>
        /// Retrieve a user's chat channels.
        /// </summary>
        /// <param name="userId">The user Id or email address.</param>
        /// <param name="recordsPerPage">The number of records returned within a single API call.</param>
        /// <param name="pagingToken">The paging token.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// An array of <see cref="ChatChannel">channels</see>.
        /// </returns>
        public Task <PaginatedResponseWithToken <ChatChannel> > GetAccountChannelsForUserAsync(string userId, int recordsPerPage = 30, string pagingToken = null, CancellationToken cancellationToken = default)
        {
            if (recordsPerPage < 1 || recordsPerPage > 300)
            {
                throw new ArgumentOutOfRangeException(nameof(recordsPerPage), "Records per page must be between 1 and 300");
            }

            return(_client
                   .GetAsync($"chat/users/{userId}/channels")
                   .WithArgument("page_size", recordsPerPage)
                   .WithArgument("next_page_token", pagingToken)
                   .WithCancellationToken(cancellationToken)
                   .AsPaginatedResponseWithToken <ChatChannel>("channels"));
        }
Beispiel #7
0
        /// <summary>
        /// Retrieve the current user's contacts.
        /// </summary>
        /// <param name="type">The type of contacts.</param>
        /// <param name="recordsPerPage">The number of records returned within a single API call.</param>
        /// <param name="pagingToken">The paging token.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// An array of <see cref="Contact">contacts</see>.
        /// </returns>
        public Task <PaginatedResponseWithToken <Contact> > GetAllAsync(ContactType type = ContactType.Internal, int recordsPerPage = 30, string pagingToken = null, CancellationToken cancellationToken = default)
        {
            if (recordsPerPage < 1 || recordsPerPage > 50)
            {
                throw new ArgumentOutOfRangeException(nameof(recordsPerPage), "Records per page must be between 1 and 50");
            }

            return(_client
                   .GetAsync($"chat/users/me/contacts")
                   .WithArgument("type", JToken.Parse(JsonConvert.SerializeObject(type)).ToString())
                   .WithArgument("page_size", recordsPerPage)
                   .WithArgument("next_page_token", pagingToken)
                   .WithCancellationToken(cancellationToken)
                   .AsPaginatedResponseWithToken <Contact>("contacts"));
        }
Beispiel #8
0
        public Task <PaginatedResponse <Meeting> > GetAllAsync(string userId, MeetingListType type = MeetingListType.Scheduled, int recordsPerPage = 30, int page = 1, CancellationToken cancellationToken = default)
        {
            if (recordsPerPage < 1 || recordsPerPage > 300)
            {
                throw new ArgumentOutOfRangeException(nameof(recordsPerPage), "Records per page must be between 1 and 300");
            }

            return(_client
                   .GetAsync($"users/{userId}/meetings")
                   .WithArgument("type", JToken.Parse(JsonConvert.SerializeObject(type)).ToString())
                   .WithArgument("page_size", recordsPerPage)
                   .WithArgument("page", page)
                   .WithCancellationToken(cancellationToken)
                   .AsPaginatedResponse <Meeting>("meetings", new MeetingConverter()));
        }
Beispiel #9
0
        /// <summary>
        /// Retrieve the names of all IP pools.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The names of all existing IP pools.
        /// </returns>
        public async Task <string[]> GetAllNamesAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            var responseContent = await _client
                                  .GetAsync(_endpoint)
                                  .WithCancellationToken(cancellationToken)
                                  .AsString(null)
                                  .ConfigureAwait(false);

            var allNames = JArray
                           .Parse(responseContent)
                           .Select(o => o.GetPropertyValue <string>("name"))
                           .ToArray();

            return(allNames);
        }
Beispiel #10
0
 /// <summary>
 /// Get all domain whitelabels
 /// </summary>
 /// <param name="limit">The limit.</param>
 /// <param name="offset">The offset.</param>
 /// <param name="excludeSubusers">if set to <c>true</c> [exclude subusers].</param>
 /// <param name="username">The username.</param>
 /// <param name="domain">The domain.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// An array of <see cref="WhitelabelDomain" />.
 /// </returns>
 /// <remarks>
 /// A domain whitelabel consists of a subdomain and domain that will be used to set the
 /// appropriate DKIM, SPF, and Return-Path. There is an option to allow SendGrid to manage
 /// security or the customers may manage their own DNS records. For customers using the
 /// manual security option, they will need to create the appropriate MX, DKIM, and SPF records
 /// with their hosting provider. With automatic security, the customer will just need to create a
 /// few CNAMEs to SendGrid, and SendGrid will manage the MX, DKIM and SPF records.
 /// </remarks>
 public Task <WhitelabelDomain[]> GetAllDomainsAsync(int limit = 50, int offset = 0, bool excludeSubusers = false, string username = null, string domain = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_client
            .GetAsync($"{_endpoint}/domains")
            .WithArgument("exclude_subusers", excludeSubusers ? "true" : "false")
            .WithArgument("limit", limit)
            .WithArgument("offset", offset)
            .WithArgument("username", username)
            .WithArgument("domain", domain)
            .WithCancellationToken(cancellationToken)
            .AsSendGridObject <WhitelabelDomain[]>());
 }
Beispiel #11
0
 /// <summary>
 /// Get suppressed addresses for a given group.
 /// </summary>
 /// <param name="groupId">ID of the suppression group</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// An array of string representing the email addresses
 /// </returns>
 public Task <string[]> GetUnsubscribedAddressesAsync(int groupId, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_client
            .GetAsync($"{_endpoint}/{groupId}/suppressions")
            .WithCancellationToken(cancellationToken)
            .AsSendGridObject <string[]>());
 }
Beispiel #12
0
        /// <summary>
        /// Retrieve all users on your account.
        /// </summary>
        /// <param name="status">The user status. Allowed values: Active, Inactive, pending.</param>
        /// <param name="roleId">Unique identifier for the role. Provide this parameter if you would like to filter the response by a specific role.</param>
        /// <param name="recordsPerPage">The number of records returned within a single API call.</param>
        /// <param name="page">The current page number of returned records.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// An array of <see cref="User">users</see>.
        /// </returns>
        public Task <PaginatedResponse <User> > GetAllAsync(UserStatus status = UserStatus.Active, string roleId = null, int recordsPerPage = 30, int page = 1, CancellationToken cancellationToken = default)
        {
            if (recordsPerPage < 1 || recordsPerPage > 300)
            {
                throw new ArgumentOutOfRangeException(nameof(recordsPerPage), "Records per page must be between 1 and 300");
            }

            return(_client
                   .GetAsync($"users")
                   .WithArgument("status", JToken.Parse(JsonConvert.SerializeObject(status)).ToString())
                   .WithArgument("role_id", roleId)
                   .WithArgument("page_size", recordsPerPage)
                   .WithArgument("page", page)
                   .WithCancellationToken(cancellationToken)
                   .AsPaginatedResponse <User>("users"));
        }
Beispiel #13
0
 /// <summary>
 /// Get the current Event Webhook settings.
 /// </summary>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// The <see cref="EventWebhookSettings" />.
 /// </returns>
 public Task <EventWebhookSettings> GetAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_client
            .GetAsync(_endpoint)
            .WithCancellationToken(cancellationToken)
            .AsSendGridObject <EventWebhookSettings>());
 }
Beispiel #14
0
        /// <summary>
        /// Retrieve a list of your categories.
        /// </summary>
        /// <param name="searchPrefix">Performs a prefix search on this value.</param>
        /// <param name="limit">Optional field to limit the number of results returned.</param>
        /// <param name="offset">Optional beginning point in the list to retrieve from.</param>
        /// <param name="onBehalfOf">The user to impersonate.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        /// An array of strings representing the catgories.
        /// </returns>
        public async Task <string[]> GetAsync(string searchPrefix = null, int limit = 50, int offset = 0, string onBehalfOf = null, CancellationToken cancellationToken = default)
        {
            var responseContent = await _client
                                  .GetAsync(_endpoint)
                                  .OnBehalfOf(onBehalfOf)
                                  .WithArgument("category", searchPrefix)
                                  .WithArgument("limit", limit)
                                  .WithArgument("offset", offset)
                                  .WithCancellationToken(cancellationToken)
                                  .AsString(null)
                                  .ConfigureAwait(false);

            // Response looks like this:
            // [
            //  {"category": "cat1"},
            //  {"category": "cat2"},
            //  {"category": "cat3"},
            //  {"category": "cat4"},
            //  {"category": "cat5"}
            // ]
            // We use a dynamic object to get rid of the 'category' property and simply return an array of strings
            var jArray     = JArray.Parse(responseContent);
            var categories = jArray.Select(x => x["category"].ToString()).ToArray();

            return(categories);
        }
Beispiel #15
0
 /// <summary>
 /// Get all the authenticated domains.
 /// </summary>
 /// <param name="limit">The limit.</param>
 /// <param name="offset">The offset.</param>
 /// <param name="excludeSubusers">if set to <c>true</c> [exclude subusers].</param>
 /// <param name="username">The username.</param>
 /// <param name="domain">The domain.</param>
 /// <param name="onBehalfOf">The user to impersonate.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// An array of <see cref="AuthenticatedDomain" />.
 /// </returns>
 public Task <AuthenticatedDomain[]> GetAllDomainsAsync(int limit = 50, int offset = 0, bool excludeSubusers = false, string username = null, string domain = null, string onBehalfOf = null, CancellationToken cancellationToken = default)
 {
     return(_client
            .GetAsync($"{_endpoint}/domains")
            .OnBehalfOf(onBehalfOf)
            .WithArgument("exclude_subusers", excludeSubusers ? "true" : "false")
            .WithArgument("limit", limit)
            .WithArgument("offset", offset)
            .WithArgument("username", username)
            .WithArgument("domain", domain)
            .WithCancellationToken(cancellationToken)
            .AsObject <AuthenticatedDomain[]>());
 }
Beispiel #16
0
 /// <summary>
 /// Get your user profile
 /// </summary>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// The <see cref="UserProfile" />.
 /// </returns>
 public Task <UserProfile> GetProfileAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_client
            .GetAsync(_endpoint)
            .WithCancellationToken(cancellationToken)
            .AsSendGridObject <UserProfile>());
 }
        /// <summary>
        /// Get all of the details about the messages matching the filtering conditions.
        /// </summary>
        /// <param name="filterConditions">Filtering conditions.</param>
        /// <param name="limit">Number of IP activity entries to return.</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>
        /// An array of <see cref="EmailMessageActivity" />.
        /// </returns>
        public Task <EmailMessageActivity[]> SearchAsync(IEnumerable <KeyValuePair <SearchLogicalOperator, IEnumerable <SearchCriteria> > > filterConditions, int limit = 20, CancellationToken cancellationToken = default(CancellationToken))
        {
            var conditions = new List <string>(filterConditions?.Count() ?? 0);

            if (filterConditions != null)
            {
                foreach (var criteria in filterConditions)
                {
                    var enumMemberValue = criteria.Key.GetAttributeOfType <EnumMemberAttribute>().Value;
                    conditions.Add(string.Join($" {enumMemberValue} ", criteria.Value.Select(criteriaValue => criteriaValue.ToString())));
                }
            }

            var query = string.Join(" AND ", conditions);

            return(_client
                   .GetAsync(_endpoint)
                   .WithArgument("limit", limit)
                   .WithArgument("query", query.ToString())
                   .WithCancellationToken(cancellationToken)
                   .AsSendGridObject <EmailMessageActivity[]>("messages"));
        }
Beispiel #18
0
 /// <summary>
 /// Get your user profile.
 /// </summary>
 /// <param name="onBehalfOf">The user to impersonate.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// The <see cref="UserProfile" />.
 /// </returns>
 public Task <UserProfile> GetProfileAsync(string onBehalfOf = null, CancellationToken cancellationToken = default)
 {
     return(_client
            .GetAsync(_endpoint)
            .OnBehalfOf(onBehalfOf)
            .WithCancellationToken(cancellationToken)
            .AsObject <UserProfile>());
 }
Beispiel #19
0
        /// <summary>
        /// Get all of the details about the messages matching the filtering conditions.
        /// </summary>
        /// <param name="filterConditions">Filtering conditions.</param>
        /// <param name="limit">Number of IP activity entries to return.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        /// An array of <see cref="EmailMessageActivity" />.
        /// </returns>
        public Task <EmailMessageActivity[]> SearchAsync(IEnumerable <KeyValuePair <SearchLogicalOperator, IEnumerable <Models.Search.Legacy.ISearchCriteria> > > filterConditions, int limit = 20, CancellationToken cancellationToken = default)
        {
            var conditions = new List <string>(filterConditions?.Count() ?? 0);

            if (filterConditions != null)
            {
                foreach (var criteria in filterConditions)
                {
                    var logicalOperator = criteria.Key.ToEnumString();
                    var values          = criteria.Value.Select(criteriaValue => criteriaValue.ToString());
                    conditions.Add(string.Join($" {logicalOperator} ", values));
                }
            }

            var query = string.Join(" AND ", conditions);

            return(_client
                   .GetAsync(_endpoint)
                   .WithArgument("limit", limit)
                   .WithArgument("query", query)
                   .WithCancellationToken(cancellationToken)
                   .AsObject <EmailMessageActivity[]>("messages"));
        }
Beispiel #20
0
        /// <summary>
        /// Validate whether or not a batch id is valid
        /// </summary>
        /// <param name="batchId">The batch identifier.</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>
        ///   <c>true</c> if the batch id is valid; otherwise, <c>false</c>.
        /// </returns>
        public async Task <bool> ValidateBatchIdAsync(string batchId, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var batch_id = await _client
                               .GetAsync($"{_endpoint}/{batchId}")
                               .WithCancellationToken(cancellationToken)
                               .AsSendGridObject <string>("batch_id")
                               .ConfigureAwait(false);

                return(!string.IsNullOrEmpty(batch_id));
            }
            catch (Exception e)
            {
                if (e.Message == "invalid batch id")
                {
                    return(false);
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #21
0
        /// <summary>
        /// Get how many IP Addresses can still be created during a given period and the price of those IPs.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The information about <see cref="IpAddressesRemaining">remaining IP addresses</see>.</returns>
        public async Task <IpAddressesRemaining> GetRemainingCountAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            var remainingInfo = await _client
                                .GetAsync($"{_endpoint}/remaining")
                                .WithCancellationToken(cancellationToken)
                                .AsSendGridObject <JArray>("results")
                                .ConfigureAwait(false);

            return(remainingInfo.First().ToObject <IpAddressesRemaining>());
        }
Beispiel #22
0
        public Task <PaginatedResponse <Account> > GetAllAsync(int recordsPerPage = 30, int page = 1, CancellationToken cancellationToken = default)
        {
            if (recordsPerPage < 1 || recordsPerPage > 300)
            {
                throw new ArgumentOutOfRangeException(nameof(recordsPerPage), "Records per page must be between 1 and 300");
            }

            return(_client
                   .GetAsync($"accounts")
                   .WithArgument("page_size", recordsPerPage)
                   .WithArgument("page", page)
                   .WithCancellationToken(cancellationToken)
                   .AsPaginatedResponse <Account>("accounts"));
        }
Beispiel #23
0
        /// <summary>
        /// Get all global email statistics for a given date range.
        /// See: https://sendgrid.com/docs/API_Reference/Web_API_v3/Stats/global.html
        /// </summary>
        /// <param name="startDate">The starting date of the statistics to retrieve.</param>
        /// <param name="endDate">The end date of the statistics to retrieve. Defaults to today.</param>
        /// <param name="aggregatedBy">How to group the statistics, must be day|week|month</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// An array of <see cref="Statistic" />.
        /// </returns>
        public Task <Statistic[]> GetGlobalStatisticsAsync(DateTime startDate, DateTime?endDate = null, AggregateBy aggregatedBy = AggregateBy.None, CancellationToken cancellationToken = default(CancellationToken))
        {
            var request = _client
                          .GetAsync(_endpoint)
                          .WithArgument("start_date", startDate.ToString("yyyy-MM-dd"))
                          .WithCancellationToken(cancellationToken);

            if (endDate.HasValue)
            {
                request.WithArgument("end_date", endDate.Value.ToString("yyyy-MM-dd"));
            }
            if (aggregatedBy != AggregateBy.None)
            {
                request.WithArgument("aggregated_by", JToken.Parse(JsonConvert.SerializeObject(aggregatedBy)).ToString());
            }

            return(request.AsSendGridObject <Statistic[]>());
        }
Beispiel #24
0
        /// <summary>
        /// Retrieve all custom and reserved fields.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// An array of <see cref="FieldMetadata">metadata</see> about the fields.
        /// </returns>
        public async Task <FieldMetadata[]> GetAllAsync(CancellationToken cancellationToken = default)
        {
            var response = await _client
                           .GetAsync(_endpoint)
                           .WithCancellationToken(cancellationToken)
                           .AsResponse()
                           .ConfigureAwait(false);

            var reservedFields = await response.AsSendGridObject <FieldMetadata[]>("reserved_fields").ConfigureAwait(false);

            // The 'custom_fields' property is omitted when there are no custom fields.
            // Therefore it's important NOT to throw an exception if this property is missing.
            // That's why the `throwIfPropertyIsMissing' parameter is set to false
            var customFields = await response.AsSendGridObject <FieldMetadata[]>("custom_fields", false).ConfigureAwait(false);

            return(reservedFields.Union(customFields ?? Array.Empty <FieldMetadata>()).ToArray());
        }
Beispiel #25
0
        /// <summary>
        /// Get how many IP Addresses can still be created during a given period and the price of those IPs.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The information about <see cref="IpAddressesRemaining">remaining IP addresses</see>.</returns>
        public async Task <IpAddressesRemaining> GetRemainingCountAsync(CancellationToken cancellationToken = default)
        {
            var result = await _client
                         .GetAsync($"{_endpoint}/remaining")
                         .WithCancellationToken(cancellationToken)
                         .AsRawJsonDocument("results")
                         .ConfigureAwait(false);

            return(result.RootElement.EnumerateArray()
                   .First()
                   .ToObject <IpAddressesRemaining>());
        }
Beispiel #26
0
        /// <summary>
        /// Get all global email statistics for a given date range.
        /// See: https://sendgrid.com/docs/API_Reference/Web_API_v3/Stats/global.html.
        /// </summary>
        /// <param name="startDate">The starting date of the statistics to retrieve.</param>
        /// <param name="endDate">The end date of the statistics to retrieve. Defaults to today.</param>
        /// <param name="aggregatedBy">How to group the statistics, must be day|week|month.</param>
        /// <param name="onBehalfOf">The user to impersonate.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// An array of <see cref="Statistic" />.
        /// </returns>
        public Task <Statistic[]> GetGlobalStatisticsAsync(DateTime startDate, DateTime?endDate = null, AggregateBy aggregatedBy = AggregateBy.None, string onBehalfOf = null, CancellationToken cancellationToken = default)
        {
            var request = _client
                          .GetAsync(_endpoint)
                          .OnBehalfOf(onBehalfOf)
                          .WithArgument("start_date", startDate.ToString("yyyy-MM-dd"))
                          .WithCancellationToken(cancellationToken);

            if (endDate.HasValue)
            {
                request.WithArgument("end_date", endDate.Value.ToString("yyyy-MM-dd"));
            }
            if (aggregatedBy != AggregateBy.None)
            {
                request.WithArgument("aggregated_by", aggregatedBy.ToEnumString());
            }

            return(request.AsObject <Statistic[]>());
        }
Beispiel #27
0
        /// <summary>
        /// Gets the total number of contacts as well as the number of billable contacts.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The total number and the number of billable contacts.
        /// </returns>
        public async Task <(long TotalCount, long BillableCount)> GetCountAsync(CancellationToken cancellationToken = default)
        {
            var response = await _client
                           .GetAsync($"{_endpoint}/count")
                           .WithCancellationToken(cancellationToken)
                           .AsRawJsonDocument()
                           .ConfigureAwait(false);

            var totalCount    = response.RootElement.GetProperty("contact_count").GetInt64();
            var billableCount = response.RootElement.GetProperty("billable_count").GetInt64();

            return(totalCount, billableCount);
        }
Beispiel #28
0
        public Task <PaginatedResponse <Recording> > GetRecordingsForUserAsync(string userId, bool queryTrash = false, DateTime?from = null, DateTime?to = null, int recordsPerPage = 30, int page = 1, CancellationToken cancellationToken = default)
        {
            if (recordsPerPage < 1 || recordsPerPage > 300)
            {
                throw new ArgumentOutOfRangeException(nameof(recordsPerPage), "Records per page must be between 1 and 300");
            }

            return(_client
                   .GetAsync($"users/{userId}/recordings")
                   .WithArgument("trash", queryTrash.ToString().ToLower())
                   .WithArgument("from", from?.ToString("yyyy-mm-dd"))
                   .WithArgument("to", to?.ToString("yyyy-mm-dd"))
                   .WithArgument("page_size", recordsPerPage)
                   .WithArgument("page", page)
                   .WithCancellationToken(cancellationToken)
                   .AsPaginatedResponse <Recording>("meetings", null));
        }
Beispiel #29
0
        /// <summary>
        /// Gets the total number of contacts as well as the number of billable contacts.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The total number and the number of billable contacts.
        /// </returns>
        public async Task <(long TotalCount, long BillableCount)> GetCountAsync(CancellationToken cancellationToken = default)
        {
            var response = await _client
                           .GetAsync($"{_endpoint}/count")
                           .WithCancellationToken(cancellationToken)
                           .AsResponse()
                           .ConfigureAwait(false);

            var totalCount = await response.AsSendGridObject <long>("contact_count").ConfigureAwait(false);

            var billableCount = await response.AsSendGridObject <long>("billable_count").ConfigureAwait(false);

            return(totalCount, billableCount);
        }
Beispiel #30
0
        /// <summary>
        /// Retrieve the permissions (AKA "scopes") assigned to the current user
        /// </summary>
        /// <param name="client">The client</param>
        /// <param name="excludeBillingScopes">Indicates if billing permissions should be excluded from the result</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>An array of permisisons assigned to the current user</returns>
        public static async Task <string[]> GetCurrentScopes(this Pathoschild.Http.Client.IClient client, bool excludeBillingScopes, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get the current user's permissions
            var scopes = await client
                         .GetAsync("scopes")
                         .WithCancellationToken(cancellationToken)
                         .AsSendGridObject <string[]>("scopes")
                         .ConfigureAwait(false);

            if (excludeBillingScopes)
            {
                // In most cases it's important to exclude billing scopes
                // because they are mutually exclusive from all others.
                scopes = scopes
                         .Where(p => !p.StartsWith("billing.", StringComparison.OrdinalIgnoreCase))
                         .ToArray();
            }

            return(scopes);
        }