ToString() public method

public ToString ( ) : string
return string
Example #1
0
        public void Constructors()
        {
            QueryParameters query01 = new QueryParameters();

            Console.WriteLine($"query01                 = {query01}");
            Console.WriteLine($"query01.ToString()      = {query01.ToString()}");
            Console.WriteLine($"query01.ToString(\"D\") = {query01.ToString("D")}");
            Console.WriteLine($"query01.ToString(\"F\") = {query01.ToString("F")}");
            Console.WriteLine($"query01.ToString(\"Q\") = {query01.ToString("Q")}");

            Dictionary <string, string> oauth_authorization = new Dictionary <string, string>()
            {
                { "client_id", "client_id_obtained_string" },
                { "response_type", "code" },
                { "redirect_uri", "http://localhost" },
                { "scope", "" },
                { "state", "" },
            };

            QueryParameters query02 = new QueryParameters(oauth_authorization);

            Console.WriteLine($"query02                 = {query02}");
            Console.WriteLine($"query02.ToString()      = {query02.ToString()}");
            Console.WriteLine($"query02.ToString(\"D\") = {query02.ToString("D")}");
            Console.WriteLine($"query02.ToString(\"F\") = {query02.ToString("F")}");
            Console.WriteLine($"query02.ToString(\"Q\") = {query02.ToString("Q")}");

            return;
        }
Example #2
0
        public void Merge()
        {
            Dictionary <string, string> d01 = new Dictionary <string, string>()
            {
                { "client_id", "client_id_obtained_string" },
                { "response_type", "code-old" },
                { "redirect_uri", "http://someotherhost" },
            };

            QueryParameters qp01 = new QueryParameters(d01);

            Console.WriteLine($"query01.ToString(\"D\") = {qp01.ToString("D")}");

            Dictionary <string, string> d02 = new Dictionary <string, string>()
            {
                { "response_type", "code" },
                { "redirect_uri", "http://localhost" },
                { "scope", "" },
                { "state", "" },
            };

            // Merge
            // adds new parameters from qp02
            // and
            // overwrites existing ones in qp01 with values from qp02
            Dictionary <string, string> d03 = qp01.Merge(d02);

            Console.WriteLine($"query01.ToString(\"D\") = {qp01.ToString("D")}");


            Dictionary <string, Func <string, string> > parameter_encoding_map_01;

            parameter_encoding_map_01 = new Dictionary <string, Func <string, string> >()
            {
                { "response_type", qp01.DoNotEncode },
                { "redirect_uri", qp01.UrlEncode },
                { "scope", qp01.UrlEncode },
                { "state", qp01.UrlEncode },
            };

            QueryParameters qp03 = new QueryParameters(d02)
            {
                DefaultParameterEncodings = parameter_encoding_map_01
            };

            qp03.ToString("D");
            qp03.Encode().ToString("D");

            return;
        }
Example #3
0
        public Task <LoanPipelineCursor> CreateCursorAsync(PipelineParameters parameters, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNull(parameters, nameof(parameters));

            var queryParameters = new QueryParameters(
                new QueryParameter("limit", "1"),
                new QueryParameter("cursorType", "randomAccess"));

            return(PostAsync(null, queryParameters.ToString(), JsonStreamContent.Create(parameters), nameof(CreateCursorAsync), null, cancellationToken, async response =>
            {
                var headers = response.Headers;
                const string countHeaderName = "x-total-count";
                if (!headers.TryGetValues(countHeaderName, out var counts))
                {
                    throw await EncompassRestException.CreateAsync($"{nameof(CreateCursorAsync)} missing {countHeaderName} header", response).ConfigureAwait(false);
                }
                var countString = counts.First();
                if (!int.TryParse(countString, out var count) || count < 0)
                {
                    throw await EncompassRestException.CreateAsync($"{nameof(CreateCursorAsync)} invalid {countHeaderName} header value", response).ConfigureAwait(false);
                }
                if (count == 0)
                {
                    return null;
                }
                const string cursorIdHeaderName = "x-cursor";
                if (!headers.TryGetValues(cursorIdHeaderName, out var cursorIds))
                {
                    throw await EncompassRestException.CreateAsync($"{nameof(CreateCursorAsync)} missing {cursorIdHeaderName} header", response).ConfigureAwait(false);
                }
                var cursorId = cursorIds.First();
                return new LoanPipelineCursor(Client, cursorId, count, parameters.Fields);
            }));
        }
Example #4
0
        /// <summary>
        /// Preview calculations for a loan. This API calculates fields similar to the calculations performed in Update Loan, however, the transient calculations provide a preview and do not save to the loan file.
        /// </summary>
        /// <param name="loan">The loan to recalculate.</param>
        /// <param name="entities">The list of loan entities to populate for the loan.</param>
        /// <param name="calcAllOnly">Indicates whether calculations will be executed for all fields. The default is <c>true</c>.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public Task CalculateLoanAsync(Loan loan, IEnumerable <string> entities, bool?calcAllOnly, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNull(loan, nameof(loan));
            Preconditions.NotNullOrEmpty(loan.EncompassId, $"{nameof(loan)}.{nameof(loan.EncompassId)}");

            var queryParameters = new QueryParameters();

            if (calcAllOnly.HasValue)
            {
                queryParameters.Add(nameof(calcAllOnly), calcAllOnly.ToString().ToLower());
            }
            var body = new CalculateLoanBody {
                LoanData = loan, Entities = entities
            };

            loan.Initialize(Client, loan.EncompassId);
            return(PostAsync("loan", queryParameters.ToString(), JsonStreamContent.Create(body), nameof(CalculateLoanAsync), loan.EncompassId, cancellationToken, async(HttpResponseMessage response) =>
            {
                var loanAsJson = loan.ToString(SerializationOptions.Dirty);
                await response.Content.PopulateAsync(loan).ConfigureAwait(false);
                loan.Dirty = false;
                // Repopulate with original dirty loan to maintain loan dirtiness.
                // This may overwrite calculated values but they shouldn't have been dirty to begin with if they're calculated values.
                JsonHelper.PopulateFromJson(loanAsJson, loan);
                return string.Empty;
            }));
        }
Example #5
0
        public static async Task <List <Alumno> > Consultar(Dictionary <string, string> filtros = null)
        {
            var endpoint = new UriBuilder(Endpoint);

            if (filtros != null)
            {
                var endpointParams = new QueryParameters(endpoint.Query);
                endpointParams.Append(filtros);
                endpoint.Query = endpointParams.ToString();
            }

            var client   = new HttpClient();
            var response = await client.GetAsync(endpoint.Uri);

            var content = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                return(JsonConvert.DeserializeObject <List <Alumno> >(content));
            }
            else
            {
                var result = JsonConvert.DeserializeObject <RestError>(content);
                throw new Exception(result.Error);
            }
        }
Example #6
0
        public Task AssignDocumentAttachmentsRawAsync(string documentId, string attachmentEntities, AssignmentAction action, CancellationToken cancellationToken = default)
        {
            action.Validate(nameof(action));

            var queryParameters = new QueryParameters(new QueryParameter(nameof(action), action.AsString(EnumJsonConverter.CamelCaseNameFormat)));

            return(AssignDocumentAttachmentsRawAsync(documentId, attachmentEntities, queryParameters.ToString(), cancellationToken));
        }
 public static string AccessTokenRequestError(string url, QueryParameters collection)
 {
     string message = "An error occurred while requesting Access Token at " + url;
     if (collection != null)
         if (collection.Count > 0)
             message += Environment.NewLine + "with parameters " + collection.ToString();
     return message;
 }
Example #8
0
        public void TestNegateSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("arid", "1", true);

            Assert.AreEqual("NOT arid:1", query.ToString());
        }
Example #9
0
        public void TestAlreadyQuotedSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "\"rolling stones\"");

            Assert.AreEqual("artist:\"rolling stones\"", query.ToString());
        }
Example #10
0
        public void TestQuoteSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "bob dylan");

            Assert.AreEqual("artist:\"bob dylan\"", query.ToString());
        }
        public void TestNegateSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("arid", "1", true);

            Assert.AreEqual("NOT arid:1", query.ToString());
        }
Example #12
0
        public void TestInlineBracketsSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "(\"rolling stones\" OR jagger)");

            Assert.AreEqual("artist:(\"rolling stones\" OR jagger)", query.ToString());
        }
        public void TestInlineSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "\"rolling stones\" OR jagger");

            Assert.AreEqual("artist:(\"rolling stones\" OR jagger)", query.ToString());
        }
        public void TestAlreadyQuotedSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "\"rolling stones\"");

            Assert.AreEqual("artist:\"rolling stones\"", query.ToString());
        }
Example #15
0
        public void TestQuoteMultiQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "rolling stones");
            query.Add("tag", "rock");

            Assert.AreEqual("artist:\"rolling stones\" AND tag:rock", query.ToString());
        }
        public void TestNegateMultiQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "stones");
            query.Add("tag", "rock", true);

            Assert.AreEqual("artist:stones AND NOT tag:rock", query.ToString());
        }
        public void TestInlineMultiQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "\"rolling stones\" OR jagger");
            query.Add("tag", "rock", true);

            Assert.AreEqual("artist:(\"rolling stones\" OR jagger) AND NOT tag:rock", query.ToString());
        }
Example #18
0
        public void TestNegateMultiQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "stones");
            query.Add("tag", "rock", true);

            Assert.AreEqual("artist:stones AND NOT tag:rock", query.ToString());
        }
Example #19
0
        /// <inheritdoc/>
        public Task <List <EntityReference> > GetTemplateFilesAsync(string path, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(path, nameof(path));

            var queryParameters = new QueryParameters(
                new QueryParameter("path", path));

            return(GetAsync <List <EntityReference> >("items", queryParameters.ToString(), nameof(GetTemplateFilesAsync), null, cancellationToken));
        }
Example #20
0
        /// <summary>
        /// Adds or removes contacts in a contact group.
        /// </summary>
        /// <param name="groupId">The unique identifier of the contact group to update.</param>
        /// <param name="action">Whether to add or remove the contact.</param>
        /// <param name="contacts">The contacts to add or remove.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public Task AssignGroupContactsAsync(string groupId, string action, IEnumerable <EntityReference> contacts, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(groupId, nameof(groupId));
            Preconditions.NotNullOrEmpty(action, nameof(action));
            Preconditions.NotNullOrEmpty(contacts, nameof(contacts));

            var queryParameters = new QueryParameters(new QueryParameter(nameof(action), action));

            return(PatchAsync($"{groupId}/contacts", queryParameters.ToString(), JsonStreamContent.Create(contacts), nameof(AssignGroupContactsAsync), groupId, cancellationToken));
        }
        /// <summary>
        /// Gets the user's licenses and for a particular state if specified.
        /// </summary>
        /// <param name="state">The state code for which to return license information.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public Task <List <UserLicenseDetail> > GetLicenseDetailsAsync(string state, CancellationToken cancellationToken = default)
        {
            var queryParameters = new QueryParameters();

            if (!string.IsNullOrEmpty(state))
            {
                queryParameters.Add("state", state);
            }
            return(GetDirtyListAsync <UserLicenseDetail>(null, queryParameters.ToString(), nameof(GetLicenseDetailsAsync), null, cancellationToken));
        }
Example #22
0
        public Task AssignDocumentAttachmentsAsync(string documentId, AssignmentAction action, IEnumerable <EntityReference> attachmentEntities, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(documentId, nameof(documentId));
            action.Validate(nameof(action));
            Preconditions.NotNullOrEmpty(attachmentEntities, nameof(attachmentEntities));

            var queryParameters = new QueryParameters(new QueryParameter(nameof(action), action.AsString(EnumJsonConverter.CamelCaseNameFormat)));

            return(PatchAsync($"{documentId}/attachments", queryParameters.ToString(), JsonStreamContent.Create(attachmentEntities), nameof(AssignDocumentAttachmentsAsync), documentId, cancellationToken));
        }
Example #23
0
        public Task <string> GetLoanRawAsync(string loanId, IEnumerable <string> entities, CancellationToken cancellationToken = default)
        {
            var queryParameters = new QueryParameters();

            if (entities?.Any() == true)
            {
                queryParameters.Add("entities", string.Join(",", entities));
            }

            return(GetLoanRawAsync(loanId, queryParameters.ToString(), cancellationToken));
        }
Example #24
0
        public Task <List <ResourceLock> > GetResourceLocksAsync(string resourceId, string resourceType, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(resourceId, nameof(resourceId));
            Preconditions.NotNullOrEmpty(resourceType, nameof(resourceType));

            var queryParameters = new QueryParameters(
                new QueryParameter("resourceType", resourceType),
                new QueryParameter("resourceId", resourceId));

            return(GetAsync <List <ResourceLock> >(null, queryParameters.ToString(), nameof(GetResourceLocksAsync), null, cancellationToken));
        }
Example #25
0
 public override string GetLoginUrl(string returnUrl)
 {
     if(string.IsNullOrEmpty(ConnectionToken.RequestToken))
         RequestForRequestToken();
     var oauthParameters = new QueryParameters
                               {
                                   new QueryParameter("oauth_token", ConnectionToken.RequestToken)
                               };
     BeforeDirectingUserToServiceProvider(oauthParameters);
     return provider.UserLoginEndpoint + "?" + oauthParameters.ToString();
 }
Example #26
0
        /// <summary>
        /// Gets the organization with the specified <paramref name="orgId"/> using the specified <paramref name="view"/>.
        /// </summary>
        /// <param name="orgId">The organization's id.</param>
        /// <param name="view">The view of the organization to get.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public Task <Organization> GetOrganizationAsync(string orgId, string view, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(orgId, nameof(orgId));

            var queryParameters = new QueryParameters();

            if (!string.IsNullOrEmpty(view))
            {
                queryParameters.Add("view", view);
            }
            return(GetDirtyAsync <Organization>(orgId, queryParameters.ToString(), orgId == "root" ? nameof(GetRootOrganizationAsync) : nameof(GetOrganizationAsync), orgId, cancellationToken));
        }
Example #27
0
        public Task <string> GetLoanSchemaRawAsync(bool includeFieldExtensions, IEnumerable <string> entities, CancellationToken cancellationToken = default)
        {
            var queryParameters = new QueryParameters();

            if (entities?.Any() == true)
            {
                queryParameters.Add("entities", string.Join(",", entities));
            }
            queryParameters.Add("includeFieldExtensions", includeFieldExtensions.ToString().ToLower());

            return(GetLoanSchemaRawAsync(queryParameters.ToString(), cancellationToken));
        }
        /// <inheritdoc/>
        public Task <RateLockRequest> DenyRateLockRequestAsync(string requestId, RateLockCancelDenyOptions?denialOptions = null, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(requestId, nameof(requestId));

            denialOptions = denialOptions ?? new RateLockCancelDenyOptions();

            var queryParameters = new QueryParameters();

            queryParameters.Add("view", "entity");

            return(PutAsync($"{requestId}/denial", queryParameters.ToString(), JsonStreamContent.Create(denialOptions), nameof(DenyRateLockRequestAsync), requestId, cancellationToken, FuncCache <RateLockRequest> .ReadAsFunc));
        }
Example #29
0
        /// <summary>
        /// Returns details for a specified persona.
        /// </summary>
        /// <param name="id">Unique Identifier of the persona.</param>
        /// <param name="categories">The Persona Categories.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public Task <Persona> GetPersonaAsync(string id, IEnumerable <string> categories, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(id, nameof(id));

            var queryParams = new QueryParameters();

            if (categories != null)
            {
                queryParams.Add("categories", string.Join(",", categories));
            }
            return(GetDirtyAsync <Persona>(id, queryParams.ToString(), nameof(GetPersonaAsync), id, cancellationToken));
        }
Example #30
0
        /// <inheritdoc/>
        public Task UpdateMilestoneAsync(LoanMilestone milestone, string?action, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNull(milestone, nameof(milestone));
            Preconditions.NotNullOrEmpty(milestone.Id, $"{nameof(milestone)}.{nameof(milestone.Id)}");
            var queryParameters = new QueryParameters();

            if (!string.IsNullOrEmpty(action))
            {
                queryParameters.Add("action", action);
            }

            return(PatchAsync(milestone.Id, queryParameters.ToString(), JsonStreamContent.Create(milestone), nameof(UpdateMilestoneAsync), milestone.Id, cancellationToken));
        }
        /// <inheritdoc/>
        public Task <RateLockRequest> GetRateLockAsync(string requestId, LockView?view = LockView.Summary, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(requestId, nameof(requestId));

            var queryParameters = new QueryParameters();

            if (view.HasValue)
            {
                queryParameters.Add("view", view.ToString().ToLower());
            }

            return(GetDirtyAsync <RateLockRequest>(requestId, queryParameters.ToString(), nameof(GetRateLockAsync), requestId, cancellationToken));
        }
Example #32
0
        /// <summary>
        /// Retrieves all contact groups for a given contact type and group type.
        /// </summary>
        /// <param name="contactType">The contact type.</param>
        /// <param name="groupType">The contact group type.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public Task <List <ContactGroup> > GetGroupsAsync(string contactType, string groupType = null, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(contactType, nameof(contactType));

            var queryParameters = new QueryParameters();

            queryParameters.Add(nameof(contactType), contactType);
            if (!string.IsNullOrEmpty(groupType))
            {
                queryParameters.Add(nameof(groupType), groupType);
            }

            return(GetDirtyListAsync <ContactGroup>(null, queryParameters.ToString(), nameof(GetGroupsAsync), null, cancellationToken));
        }
        /// <inheritdoc/>
        public Task <UserRights> GetRightsAsync(UserRightsType type, string?category, CancellationToken cancellationToken = default)
        {
            type.Validate(nameof(type));

            var queryParameters = new QueryParameters();

            if (!string.IsNullOrEmpty(category))
            {
                queryParameters.Add("category", category);
            }
            var path = type.GetValue();

            return(GetDirtyAsync <UserRights>(path, queryParameters.ToString(), nameof(GetRightsAsync), path, cancellationToken));
        }
        /// <inheritdoc/>
        public Task <List <LoanAssociate> > GetAssociatesAsync(string?userId, string?roleId, CancellationToken cancellationToken = default)
        {
            var queryParameters = new QueryParameters();

            if (!string.IsNullOrEmpty(userId))
            {
                queryParameters.Add("userId", userId);
            }
            if (!string.IsNullOrEmpty(roleId))
            {
                queryParameters.Add("roleId", roleId);
            }

            return(GetDirtyListAsync <LoanAssociate>(null, queryParameters.ToString(), nameof(GetAssociatesAsync), null, cancellationToken));
        }
Example #35
0
        /// <summary>
        /// Returns a list of subscriptions.
        /// </summary>
        /// <param name="resources">Resource names to include.</param>
        /// <param name="events">Include subscriptions with these specified events.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public Task <List <WebhookSubscription> > GetSubscriptionsAsync(IEnumerable <string> resources, IEnumerable <string> events, CancellationToken cancellationToken = default)
        {
            var queryParameters = new QueryParameters();

            if (resources?.Any() == true)
            {
                queryParameters.Add("resource", string.Join(",", resources));
            }
            if (events?.Any() == true)
            {
                queryParameters.Add("events", string.Join(",", events));
            }

            return(GetDirtyListAsync <WebhookSubscription>("subscriptions", queryParameters.ToString(), nameof(GetSubscriptionsAsync), null, cancellationToken));
        }
Example #36
0
        /// <summary>
        /// Gets the user with the specified <paramref name="userId"/> and optionally includes the email signature in the response object.
        /// </summary>
        /// <param name="userId">The user's id.</param>
        /// <param name="viewEmailSignature">Indicates whether the email signature should be returned as part of the response.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async Task <User> GetUserAsync(string userId, bool?viewEmailSignature, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(userId, nameof(userId));

            var queryParameters = new QueryParameters();

            if (viewEmailSignature.HasValue)
            {
                queryParameters.Add("viewEmailSignature", viewEmailSignature.ToString().ToLower());
            }
            var user = await GetDirtyAsync <User>(userId, queryParameters.ToString(), nameof(GetUserAsync), userId, cancellationToken).ConfigureAwait(false);

            user.Initialize(Client, user.Id !);
            return(user);
        }
Example #37
0
        public Task <string> GetSubscriptionsRawAsync(IEnumerable <string> resources, IEnumerable <string> events, CancellationToken cancellationToken = default)
        {
            var queryParameters = new QueryParameters();

            if (resources?.Any() == true)
            {
                queryParameters.Add("resource", string.Join(",", resources));
            }
            if (events?.Any() == true)
            {
                queryParameters.Add("events", string.Join(",", events));
            }

            return(GetSubscriptionsRawAsync(queryParameters.ToString(), cancellationToken));
        }
 public static string CustomFeedExecutionError(string feedUrl, QueryParameters collection)
 {
     return "An error occurred while executing " + feedUrl + Environment.NewLine + "Request Parameters: " + ((collection == null) ? "" : ((collection == null) ? "" : collection.ToString()));
 }
Example #39
0
 /// <summary>
 /// Search for an artist in the MusicBrainz database, matching the given query.
 /// </summary>
 /// <param name="query">The query parameters.</param>
 /// <param name="limit">The maximum number of artists to return (default = 25).</param>
 /// <param name="offset">The offset to the artists list (enables paging, default = 0).</param>
 /// <returns></returns>
 public async static Task<ArtistList> SearchAsync(QueryParameters<Artist> query, int limit = 25, int offset = 0)
 {
     return (await SearchAsync<ArtistMetadata>(EntityName,
         query.ToString(), limit, offset)).Collection;
 }
        public void TestQuoteSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "bob dylan");

            Assert.AreEqual("artist:\"bob dylan\"", query.ToString());
        }
        public void DirectUserToServiceProvider()
        {
            QueryParameters oauthParameters = new QueryParameters();

            try
            {
                oauthParameters.Add(new QueryParameter("oauth_token", connectionToken.RequestToken));
                BeforeDirectingUserToServiceProvider(oauthParameters);
                logger.Debug("redirecting user for login to: " + provider.UserLoginEndpoint + "?" + oauthParameters.ToString());
                SocialAuthUser.Redirect(provider.UserLoginEndpoint + "?" + oauthParameters.ToString());
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.UserLoginRedirectionError(provider.UserLoginEndpoint + "?" + oauthParameters.ToString()), ex);
                throw new OAuthException(ErrorMessages.UserLoginRedirectionError(provider.UserLoginEndpoint + "?" + oauthParameters.ToString()), ex);
            }

        }
        public void TestQuoteMultiQuery()
        {
            var query = new QueryParameters<Artist>();

            query.Add("artist", "rolling stones");
            query.Add("tag", "rock");

            Assert.AreEqual("artist:\"rolling stones\" AND tag:rock", query.ToString());
        }
 public static string UserLoginResponseError(PROVIDER_TYPE providerType, QueryParameters collection)
 {
     return "An error occurred in user login." + Environment.NewLine + "Provider returned: " + ((collection == null) ? "" : collection.ToString());
 }
        public override System.Net.WebResponse ExecuteFeed(string feedURL, IProvider provider, BusinessObjects.Token connectionToken, BusinessObjects.TRANSPORT_METHOD transportMethod, byte[] content = null, Dictionary<string, string> headers = null)
        {

            string signature = "";
            OAuthHelper oauthHelper = new OAuthHelper();


            string timestamp = oauthHelper.GenerateTimeStamp();
            QueryParameters oauthParams = new QueryParameters();
            oauthParams.Add("oauth_consumer_key", provider.Consumerkey);
            oauthParams.Add("oauth_nonce", oauthHelper.GenerateNonce());
            oauthParams.Add("oauth_signature_method", provider.SignatureMethod.ToString());
            oauthParams.Add("oauth_timestamp", timestamp);
            oauthParams.Add("oauth_token", connectionToken.AccessToken);
            oauthParams.Add("oauth_version", "1.0");
            signature = oauthHelper.GenerateSignature(new Uri(feedURL), oauthParams, provider.Consumerkey, provider.Consumersecret, provider.SignatureMethod, TRANSPORT_METHOD.POST, connectionToken.TokenSecret);
            oauthParams.Add("oauth_signature", signature);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(feedURL);
            request.Method = transportMethod.ToString();
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    switch (header.Key)
                    {
                        case "ContentLength":
                            {
                                request.ContentLength = long.Parse(header.Value);
                                break;
                            }

                        case "ContentType":
                            {
                                request.ContentType = header.Value;
                                break;
                            }
                        default:
                            {
                                request.Headers[header.Key] = header.Value;
                                break;
                            }
                    }

                }

            }

            request.ContentLength = (content == null) ? 0 : content.Length;
            request.Headers.Add("Authorization", oauthHelper.GetAuthorizationHeader(oauthParams));
            request.GetRequestStream().Write(content, 0, content.Length);
            WebResponse wr = null;
            try
            {
                logger.Debug("Executing " + feedURL + " using " + transportMethod.ToString() + Environment.NewLine + "Request Parameters: " + oauthParams.ToString());
                wr = (WebResponse)request.GetResponse();
                logger.Info("Successfully executed  " + feedURL + " using " + transportMethod.ToString());
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.CustomFeedExecutionError(feedURL, oauthParams), ex);
                throw new OAuthException(ErrorMessages.CustomFeedExecutionError(feedURL, oauthParams), ex);
            }
            return wr;
        }
        /// <summary>
        /// Generate Signature
        /// </summary>
        /// <param name="requestURL"></param>
        /// <param name="oauthParameters"></param>
        /// <param name="consumerKey"></param>
        /// <param name="consumerSecret"></param>
        /// <param name="signatureType"></param>
        /// <param name="httpMethod"></param>
        /// <param name="tokenSecret"></param>
        /// <returns></returns>
        public string GenerateSignature(Uri requestURL, QueryParameters oauthParameters, string consumerKey, string consumerSecret,
            SIGNATURE_TYPE signatureType, TRANSPORT_METHOD httpMethod, string tokenSecret)
        {
            QueryParameters tmpOauthParameters = new QueryParameters();
            foreach (var param in oauthParameters)
            {
                if (param.Value.ToLower().Contains("http://") || param.Value.ToLower().Contains("https://"))
                    tmpOauthParameters.Add(new QueryParameter(param.Key, Utility.UrlEncode(param.Value)));
                else
                    tmpOauthParameters.Add(new QueryParameter(param.Key, param.Value));
            }

            tmpOauthParameters[OAuthSignatureMethodKey] = ParseSignatureEnum(signatureType);

            string signature = "";

            StringBuilder signatureBase = new StringBuilder();

            //1. URL encode and process Request URL
            string normalizedRequestUrl;
            normalizedRequestUrl = string.Format("{0}://{1}", requestURL.Scheme, requestURL.Host);
            if (!((requestURL.Scheme == "http" && requestURL.Port == 80) || (requestURL.Scheme == "https" && requestURL.Port == 443)))
            {
                normalizedRequestUrl += ":" + requestURL.Port;
            }
            normalizedRequestUrl += requestURL.AbsolutePath;
            normalizedRequestUrl = Utility.UrlEncode(normalizedRequestUrl);

            //2. URL Encode callbackUrl (if present)
            //if (tmpOauthParameters.HasName(OAuthCallbackKey))
            //    tmpOauthParameters[OAuthCallbackKey] = Utility.UrlEncode(tmpOauthParameters[OAuthCallbackKey]);

            //tmpOauthParameters["scope"] = Utility.UrlEncode(tmpOauthParameters["scope"]);

            foreach (var p in Utility.GetQuerystringParameters(requestURL.ToString()))
                tmpOauthParameters.Add(p.Key, UrlEncode(HttpUtility.UrlDecode(p.Value)));

                //following works for Twitter with spaces
                //tmpOauthParameters.Add(p.Key, UrlEncode(HttpUtility.UrlDecode(p.Value)));

            //3. Perform Lexographic Sorting
            tmpOauthParameters.Sort();

            //4. Generate Signature Base
            signatureBase.AppendFormat("{0}&", httpMethod.ToString().ToUpper());
            signatureBase.AppendFormat("{0}&", normalizedRequestUrl);
            signatureBase.AppendFormat("{0}", Utility.UrlEncode(tmpOauthParameters.ToString()));
            string sbase = signatureBase.ToString();
            logger.Debug("signature base:" + sbase);
            //5. Generate Signature
            switch (signatureType)
            {
                case SIGNATURE_TYPE.PLAINTEXT:
                    {
                        signature = Utility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret));
                        break;
                    }
                case SIGNATURE_TYPE.HMACSHA1:
                    {
                        HMACSHA1 hmacsha1 = new HMACSHA1();
                        hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : tokenSecret));
                        signature = GenerateSignatureUsingHash(sbase, hmacsha1);
                        logger.Debug("HMACSHA1 signature:" + signature);
                        break;
                    }
                default:
                    throw new ArgumentException("Unknown signature type", "signatureType");
            }

            return signature;
        }
 public static string RequestTokenRequestError(string url, QueryParameters collection)
 {
     return "An error occurred while requesting Request Token at " + url + Environment.NewLine + "with parameters " + ((collection == null) ? "" : collection.ToString());
 }
        public void RequestForAccessToken()
        {
            QueryParameters oauthParameters = new QueryParameters();
            string signature = "";
            OAuthHelper oauthHelper = new OAuthHelper();

            ////1. Generate Signature
            oauthParameters.Add("oauth_consumer_key", provider.Consumerkey);
            oauthParameters.Add("oauth_token", Utility.UrlEncode(ConnectionToken.RequestToken));
            oauthParameters.Add("oauth_signature_method", provider.SignatureMethod.ToString());
            oauthParameters.Add("oauth_timestamp", oauthHelper.GenerateTimeStamp());
            oauthParameters.Add("oauth_nonce", oauthHelper.GenerateNonce());
            oauthParameters.Add("oauth_version", "1.0");
            BeforeRequestingAccessToken(oauthParameters); // hook called
            signature = oauthHelper.GenerateSignature(new Uri(provider.AccessTokenEndpoint), oauthParameters, provider.Consumerkey, provider.Consumersecret, provider.SignatureMethod, provider.TransportName, string.Empty);
            oauthParameters.Add("oauth_signature", Utility.UrlEncode(signature));

            //2. Notify Consumer (if applicable)
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(provider.AccessTokenEndpoint + "?" + oauthParameters.ToString().Replace("HMACSHA1", "HMAC-SHA1"));
            request.Method = "GET";// always get irrespective of provider.TransportName.ToString();
            request.ContentLength = 0;
            string response = "";

            try
            {
                logger.Debug("Requesting Access Token at: " + request.RequestUri + Environment.NewLine + "Request Parameters: " + oauthParameters.ToString());
                using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
                using (Stream responseStream = webResponse.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    response = reader.ReadToEnd();
                    HandleAccessTokenResponse(Utility.GetQuerystringParameters(response));
                }

            }
            catch (Exception ex)
            {
                logger.Debug(ErrorMessages.AccessTokenRequestError(request.RequestUri.ToString(), oauthParameters), ex);
                throw new OAuthException(ErrorMessages.AccessTokenRequestError(request.RequestUri.ToString(), oauthParameters), ex);
            }
        }
 public static string AccessTokenResponseInvalid(QueryParameters collection)
 {
     return "Invalid Access Token received." + Environment.NewLine + "Provider returned: " + ((collection == null) ? "" : collection.ToString());
 }
        public override System.Net.WebResponse ExecuteFeed(string feedURL, IProvider provider, BusinessObjects.Token connectionToken, BusinessObjects.TRANSPORT_METHOD transportMethod)
        {
            string signature = "";
            OAuthHelper oauthHelper = new OAuthHelper();
            QueryParameters oauthParams = new QueryParameters();
            oauthParams.Add("oauth_consumer_key", provider.Consumerkey);
            oauthParams.Add("oauth_nonce", oauthHelper.GenerateNonce());
            oauthParams.Add("oauth_signature_method", provider.SignatureMethod.ToString());
            oauthParams.Add("oauth_timestamp", oauthHelper.GenerateTimeStamp());
            oauthParams.Add("oauth_token", connectionToken.AccessToken);
            oauthParams.Add("oauth_version", "1.0");


            ////1. Generate Signature
            signature = oauthHelper.GenerateSignature(new Uri(feedURL), oauthParams, provider.Consumerkey, provider.Consumersecret, provider.SignatureMethod, TRANSPORT_METHOD.GET, connectionToken.TokenSecret);
            oauthParams.Add("oauth_signature", signature);


            //3.Connect and Execute Feed

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(feedURL);
            request.Method = transportMethod.ToString();
            request.Headers.Add("Authorization", oauthHelper.GetAuthorizationHeader(oauthParams));
            //request.ContentType = "application/atom+xml";
            request.ContentLength = 0;
            WebResponse wr;
            try
            {
                logger.Debug("Executing " + feedURL + " using " + transportMethod.ToString() + Environment.NewLine + "Request Parameters: " + oauthParams.ToString());
                wr = (WebResponse)request.GetResponse();
                logger.Info("Successfully executed  " + feedURL + " using " + transportMethod.ToString());
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.CustomFeedExecutionError(feedURL, oauthParams), ex);
                throw new OAuthException(ErrorMessages.CustomFeedExecutionError(feedURL, oauthParams), ex);
            }
            return wr;
        }