public void DirectUserToServiceProvider()
        {
            UriBuilder ub = new UriBuilder(provider.UserLoginEndpoint);
            try
            {
                QueryParameters oauthParams = new QueryParameters();
                oauthParams.Add("client_id", provider.Consumerkey);
                oauthParams.Add("redirect_uri", connectionToken.ProviderCallbackUrl);
                oauthParams.Add("response_type", "code");
                oauthParams.Add("scope", provider.GetScope());
                //ub.SetQueryparameter("client_id", provider.Consumerkey);
                //ub.SetQueryparameter("redirect_uri", connectionToken.ProviderCallbackUrl);
                //ub.SetQueryparameter("response_type", "code");
                //ub.SetQueryparameter("scope", provider.GetScope());

                BeforeDirectingUserToServiceProvider(oauthParams);
                logger.Debug("Redirecting user for login to " + ub.ToString() + "?" + oauthParams.ToEncodedString());
                SocialAuthUser.Redirect(ub.ToString() + "?" + oauthParams.ToEncodedString());
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.UserLoginRedirectionError(ub.ToString()), ex);
                throw new OAuthException(ErrorMessages.UserLoginRedirectionError(ub.ToString()), ex);
            }
        }
Esempio n. 2
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());
        }
Esempio n. 3
0
        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());
        }
        public override string GetLoginUrl(string returnUrl)
        {
            var ub = new UriBuilder(provider.UserLoginEndpoint);

            var oauthParams = new QueryParameters();
            oauthParams.Add("client_id", provider.Consumerkey);
            oauthParams.Add("redirect_uri", returnUrl);
            oauthParams.Add("response_type", "code");
            oauthParams.Add("scope", provider.GetScope());

            BeforeDirectingUserToServiceProvider(oauthParams);
            return ub.ToString() + "?" + oauthParams.ToEncodedString();
        }
Esempio n. 5
0
        public void TestNegateSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

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

            Assert.AreEqual("NOT arid:1", query.ToString());
        }
Esempio n. 6
0
        public void TestInlineSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

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

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

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

            Assert.AreEqual("artist:\"rolling stones\"", query.ToString());
        }
Esempio n. 8
0
        public Task <string> ViewPipelineRawAsync(string parameters, int?limit, CancellationToken cancellationToken = default)
        {
            if (limit.HasValue)
            {
                Preconditions.GreaterThan(limit.GetValueOrDefault(), nameof(limit), 0);
            }

            var queryParameters = new QueryParameters();

            if (limit.HasValue)
            {
                queryParameters.Add(new QueryParameter("limit", limit.GetValueOrDefault().ToString()));
            }

            return(ViewPipelineRawAsync(parameters, queryParameters.ToString(), cancellationToken));
        }
Esempio n. 9
0
        public Task<bool> UnlockResourceAsync(string lockId, string resourceId, string resourceType, bool force, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(lockId, nameof(lockId));
            Preconditions.NotNullOrEmpty(resourceId, nameof(resourceId));
            Preconditions.NotNullOrEmpty(resourceType, nameof(resourceType));

            var queryParameters = new QueryParameters(
                new QueryParameter("resourceType", resourceType),
                new QueryParameter("resourceId", resourceId));
            if (force)
            {
                queryParameters.Add("force", "true");
            }

            return DeleteAsync(lockId, queryParameters.ToString(), cancellationToken);
        }
Esempio n. 10
0
        public async Task <Loan> GetLoanAsync(string loanId, IEnumerable <string> entities, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(loanId, nameof(loanId));

            var queryParameters = new QueryParameters();

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

            var loan = await GetDirtyAsync <Loan>(loanId, queryParameters.ToString(), nameof(GetLoanAsync), loanId, cancellationToken).ConfigureAwait(false);

            loan.Initialize(Client, loan.EncompassId);
            return(loan);
        }
Esempio n. 11
0
        public void AppendBiggerThen(object pValue, string pAlias, string pName)
        {
            var lParameter = string.Concat("@", pAlias, pName);

            if (ParenthesesOpen)
            {
                Builder.Append(" ");
            }
            else
            {
                Builder.Append(" and ");
            }

            Builder.Append(string.Concat("[", pAlias, "].[", pName, "] > ", lParameter)).AppendLine();
            QueryParameters.Add(lParameter, pValue);
        }
Esempio n. 12
0
        /// <summary>
        /// Generates the loan contract from the specified <paramref name="fieldValues"/>.
        /// </summary>
        /// <param name="fieldValues">The field values to generate the loan contract.</param>
        /// <param name="ignoreInvalidFields">Indicates whether to ignore invalid loan fields if specified in the request.</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 <Loan> GenerateContractAsync(IDictionary <string, object> fieldValues, bool?ignoreInvalidFields, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNullOrEmpty(fieldValues, nameof(fieldValues));

            var queryParameters = new QueryParameters();

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

            var loan = await PostAsync <Loan>("contractGenerator", queryParameters.ToString(), JsonStreamContent.Create(fieldValues), nameof(GenerateContractAsync), null, cancellationToken).ConfigureAwait(false);

            loan.Client = Client;
            return(loan);
        }
Esempio n. 13
0
        public override Task <dynamic> ExecuteAsync()
        {
            var ids = string.Join(Comma, _eventIds);

            if (_eventIds.Count > 1)
            {
                QueryParameters.Add(IdsKey, ids);
                Path = EventBatchPath;
            }
            else
            {
                Path = string.Format(EventPath, ids);
            }

            return(base.ExecuteAsync());
        }
Esempio n. 14
0
        public Task <List <LoanPipelineData> > ViewPipelineAsync(PipelineParameters parameters, int?limit, CancellationToken cancellationToken = default)
        {
            Preconditions.NotNull(parameters, nameof(parameters));
            if (limit.HasValue)
            {
                Preconditions.GreaterThan(limit.GetValueOrDefault(), nameof(limit), 0);
            }

            var queryParameters = new QueryParameters();

            if (limit.HasValue)
            {
                queryParameters.Add(new QueryParameter("limit", limit.GetValueOrDefault().ToString()));
            }

            return(PostAsync <List <LoanPipelineData> >(null, queryParameters.ToString(), JsonStreamContent.Create(parameters), nameof(ViewPipelineAsync), null, cancellationToken));
        }
Esempio n. 15
0
        /// <summary>
        /// This API allows you to generate SOTT with a given expiration time.
        /// </summary>
        /// <param name="timeDifference">The time difference you would like to pass, If you not pass difference then the default value is 10 minutes</param>
        /// <returns>Sott data For Registration</returns>
        /// 18.28

        public ApiResponse <SottResponseData> GenerateSott(int?timeDifference = null)
        {
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
                { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] }
            };

            if (timeDifference != null)
            {
                queryParameters.Add("timeDifference", timeDifference.ToString());
            }

            var resourcePath = "identity/v2/manage/account/sott";

            return(ConfigureAndExecute <SottResponseData>(HttpMethod.GET, resourcePath, queryParameters, null));
        }
Esempio n. 16
0
        public override Task <dynamic> ExecuteAsync()
        {
            Method = "GET";
            var ids = string.Join(Comma, _imageIds);

            if (_imageIds.Count > 1)
            {
                QueryParameters.Add(IdsKey, ids);
                Path = ImageBatchPath;
            }
            else
            {
                Path = string.Format(ImagePath, ids);
            }

            return(base.ExecuteAsync());
        }
Esempio n. 17
0
        public void AppendEntity(int pValue, IAbstractDal pEntity, string pCustomLeftKey, string pCustomRightKey)
        {
            var lParameter = string.Concat("@", pEntity.EntityAlias, pCustomRightKey);

            if (ParenthesesOpen)
            {
                Builder.Append(" ");
            }
            else
            {
                Builder.Append(" and ");
            }

            Builder.Append(string.Concat("[", pEntity.EntityAlias, "].[", pCustomLeftKey, "] = ", lParameter)).AppendLine();

            QueryParameters.Add(lParameter, pValue);
        }
        private static string GetEndpoint(string apiPath, out Dictionary <string, string> authHeaders, QueryParameters additionalParameters = null)
        {
            string baseEndPoint;

            authHeaders = null;
            if (ConfigDictionary.ContainsKey(LRConfigConstants.ApiRegion) && !string.IsNullOrWhiteSpace(ConfigDictionary[LRConfigConstants.ApiRegion]))
            {
                additionalParameters.Add("region", ConfigDictionary[LRConfigConstants.ApiRegion]);
            }
            if (apiPath.Contains("identity/v2") && additionalParameters.ContainsKey("apiSecret"))
            {
                additionalParameters.Remove("apiSecret");
                authHeaders = new Dictionary <string, string>
                {
                    [BaseConstants.AuthorizationHeader] = ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret]
                };
            }
            else if (apiPath.Contains("/auth") && additionalParameters.ContainsKey("access_token"))
            {
                authHeaders = new Dictionary <string, string>
                {
                    [BaseConstants.AccessTokenAuthorizationHeader] = BaseConstants.AccessTokenBearerHeader + additionalParameters["access_token"]
                };
                additionalParameters.Remove("access_token");
            }
            else if (apiPath.Contains("identity/v2/auth/register") && additionalParameters.ContainsKey("sott"))
            {
                authHeaders = new Dictionary <string, string> {
                    [BaseConstants.SottAuthorizationHeader] = additionalParameters["sott"]
                };
                additionalParameters.Remove("sott");
            }

            if (apiPath.Contains("ciam/appinfo"))
            {
                baseEndPoint = BaseConstants.BaseConfigApiEndpoint;
            }
            else
            {
                baseEndPoint = string.IsNullOrWhiteSpace(ConfigDictionary[LRConfigConstants.DomainName])
               ? BaseConstants.BaseRestApiEndpoint : ConfigDictionary[LRConfigConstants.DomainName];
            }

            return(string.IsNullOrWhiteSpace(apiPath)
                ? $"{baseEndPoint}{additionalParameters.ToUrlFormattedString()}": $"{baseEndPoint}{apiPath}{additionalParameters.ToUrlFormattedString()}");
        }
        /// <summary>
        /// Queries local datastore for studies based on specified search function.
        /// </summary>
        private void QueryStudies(string query, Converter <string, KeyValuePair <string, double>[]> searchFunc)
        {
            // if there is a previous task that may still be running, disconnect it so we effectively abandon it
            if (_queryStudiesTask != null)
            {
                _queryStudiesTask.ProgressUpdated -= OnQueryStudiesProgressUpdate;
            }

            // clear existing items
            _searchResults.Items.Clear();

            // create new task to query similar studies asynchronously so as not to block UI
            _queryStudiesTask = new BackgroundTask(
                delegate(IBackgroundTaskContext ctx)
            {
                KeyValuePair <string, double>[] similarStudyUids = searchFunc(query);
                foreach (KeyValuePair <string, double> kvp in similarStudyUids)
                {
                    string studyUid = kvp.Key;
                    double score    = kvp.Value;

                    QueryParameters queryParams = new QueryParameters();
                    queryParams.Add("PatientsName", "");
                    queryParams.Add("PatientId", "");
                    queryParams.Add("AccessionNumber", "");
                    queryParams.Add("StudyDescription", "");
                    queryParams.Add("ModalitiesInStudy", "");
                    queryParams.Add("StudyDate", "");
                    queryParams.Add("StudyInstanceUid", studyUid);

                    // currently only the local dicom store is supported
                    StudyItemList similarStudyItems = ImageViewerComponent.FindStudy(queryParams, null, "DICOM_LOCAL");

                    // should only ever be one result at most
                    // if zero results, it means the study exists in the tag database but not in the local dicom store
                    StudyItem studyItem = CollectionUtils.FirstElement(similarStudyItems);
                    if (studyItem != null)
                    {
                        StudyTableEntry entry = new StudyTableEntry(studyItem, MakeTagsString(_database.GetTagsForStudy(studyUid)), score);
                        ctx.ReportProgress(new StudyQueryProgress(entry));
                    }
                }
            }, false);

            _queryStudiesTask.ProgressUpdated += OnQueryStudiesProgressUpdate;
            _queryStudiesTask.Run();
        }
Esempio n. 20
0
        public void AppendBetween(object pValue, object pValue2, string pAlias, string pName)
        {
            var lParameter1 = string.Concat("@", pAlias, pName, "_min");
            var lParameter2 = string.Concat("@", pAlias, pName, "_max");

            if (ParenthesesOpen)
            {
                Builder.Append(" ");
            }
            else
            {
                Builder.Append(" and ");
            }

            Builder.Append(string.Concat("[", pAlias, "].[", pName, "] between ", lParameter1, " and ", lParameter2)).AppendLine();
            QueryParameters.Add(lParameter1, pValue);
            QueryParameters.Add(lParameter2, pValue2);
        }
Esempio n. 21
0
        /// <summary>
        /// This API can be used to login by Phone on a Multi-factor authentication enabled LoginRadius site.
        /// </summary>
        /// <param name="password">Password for the email</param>
        /// <param name="phone">New Phone Number</param>
        /// <param name="emailTemplate">Email template name</param>
        /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
        /// <param name="loginUrl">Url where the user is logging from</param>
        /// <param name="smsTemplate">SMS Template name</param>
        /// <param name="smsTemplate2FA">SMS Template Name</param>
        /// <param name="verificationUrl">Email verification url</param>
        /// <returns>Complete user UserProfile data</returns>
        /// 9.8.3

        public ApiResponse <MultiFactorAuthenticationResponse <Identity> > MFALoginByPhone(string password, string phone,
                                                                                           string emailTemplate   = null, string fields = "", string loginUrl = null, string smsTemplate = null, string smsTemplate2FA = null,
                                                                                           string verificationUrl = null)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(password));
            }
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
            };

            if (!string.IsNullOrWhiteSpace(emailTemplate))
            {
                queryParameters.Add("emailTemplate", emailTemplate);
            }
            if (!string.IsNullOrWhiteSpace(fields))
            {
                queryParameters.Add("fields", fields);
            }
            if (!string.IsNullOrWhiteSpace(loginUrl))
            {
                queryParameters.Add("loginUrl", loginUrl);
            }
            if (!string.IsNullOrWhiteSpace(smsTemplate))
            {
                queryParameters.Add("smsTemplate", smsTemplate);
            }
            if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
            {
                queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
            }
            if (!string.IsNullOrWhiteSpace(verificationUrl))
            {
                queryParameters.Add("verificationUrl", verificationUrl);
            }

            var bodyParameters = new BodyParameters
            {
                { "password", password },
                { "phone", phone }
            };

            var resourcePath = "identity/v2/auth/login/2fa";

            return(ConfigureAndExecute <MultiFactorAuthenticationResponse <Identity> >(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
Esempio n. 22
0
        public static User GetDomainUser(Database database, string domainName, string userName)
        {
            string          query      = EntryControl.Resources.Sec.User.GetUserId;
            QueryParameters parameters = new QueryParameters("domainName", domainName);

            parameters.Add("userName", userName);

            object result = database.ExecuteScalar(query, parameters);

            if (result != null)
            {
                return(User.LoadUser(database, (int)result));
            }
            else
            {
                return(null);
            }
        }
Esempio n. 23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="otp"></param>
        /// <param name="optionalParams"></param>
        /// <returns></returns>
        public ApiResponse <LoginResponse> LoginByOneTimePassCode(string phone, string otp,
                                                                  LoginRadiusApiOptionalParams optionalParams)
        {
            Validate(new ArrayList {
                phone, otp
            });
            var additionalQueryParams = new QueryParameters {
                { "phone", phone }, { "otp", otp }
            };

            if (!string.IsNullOrWhiteSpace(optionalParams.SmsTemplate))
            {
                additionalQueryParams.Add("SmsTemplate", optionalParams.SmsTemplate);
            }
            return(ConfigureAndExecute <LoginResponse>(RequestType.Authentication, HttpMethod.Get,
                                                       _resoucePath.ToString(),
                                                       additionalQueryParams));
        }
Esempio n. 24
0
        public ApiResponse <LoginRadiusPostResponse> VerifyEmail(string vToken, string url,
                                                                 string welcomeEmailTemplate = "")
        {
            Validate(new ArrayList {
                vToken, url
            });
            var additionalQueryParams = new QueryParameters {
                ["VerificationToken"] = vToken, ["url"] = url
            };

            if (!string.IsNullOrWhiteSpace(welcomeEmailTemplate))
            {
                additionalQueryParams.Add("welcomeEmailTemplate", welcomeEmailTemplate);
            }
            return(ConfigureAndExecute <LoginRadiusPostResponse>(RequestType.Authentication, HttpMethod.Get,
                                                                 _resoucePath.ToString(),
                                                                 additionalQueryParams));
        }
        public override HttpRequest SignRequest(Signer signer, AlibabaCloudCredentials credentials,
                                                FormatType?format, ProductDomain domain)
        {
            if (this.BodyParameters != null && this.BodyParameters.Count > 0)
            {
                var    formParams = new Dictionary <string, string>(this.BodyParameters);
                string formStr    = ConcatQueryString(formParams);
                byte[] formData   = System.Text.Encoding.UTF8.GetBytes(formStr);
                this.SetContent(formData, "UTF-8", FormatType.FORM);
            }

            var imutableMap = new Dictionary <string, string>(this.Headers);

            if (null != signer && null != credentials)
            {
                var accessKeyId = credentials.GetAccessKeyId();
                imutableMap = Composer.RefreshSignParameters(Headers, signer, accessKeyId, format);
                if (credentials is BasicSessionCredentials)
                {
                    var sessionToken = ((BasicSessionCredentials)credentials).GetSessionToken();
                    if (null != sessionToken)
                    {
                        imutableMap.Add("x-acs-security-token", sessionToken);
                    }
                }

                if (credentials is BearerTokenCredential)
                {
                    var bearerToken = ((BearerTokenCredential)credentials).GetBearerToken();
                    if (null != bearerToken)
                    {
                        QueryParameters.Add("x-acs-bearer-token", bearerToken);
                    }
                }

                var strToSign = Composer.ComposeStringToSign(Method, uriPattern, signer,
                                                             QueryParameters, imutableMap, pathParameters);
                var signature = signer.SignString(strToSign, credentials);
                DictionaryUtil.Add(imutableMap, "Authorization", "acs " + accessKeyId + ":" + signature);
            }
            Url          = this.ComposeUrl(domain.DomianName, QueryParameters);
            this.Headers = imutableMap;
            return(this);
        }
Esempio n. 26
0
        private QueryParameters CreateParameters()
        {
            QueryParameters parameters = new QueryParameters("idUnit", unit.Id);

            parameters.Add("trackMark", trackMark);
            parameters.Add("licensePlate", licensePlate);
            parameters.Add("driverName", driverName);
            parameters.Add("driverPhone", driverPhone);
            parameters.Add("cargo", Cargo);
            parameters.Add("isClosed", isClosed);

            return(parameters);
        }
Esempio n. 27
0
        public static List <User> LoadList(Database database, Unit unit, int groupId)
        {
            List <User>     userList   = new List <User>();
            string          query      = EntryControl.Resources.Ref.Unit.UserList;
            QueryParameters parameters = new QueryParameters("unitId", unit.Id);

            parameters.Add("roleId", groupId);

            using (DbDataReader reader = database.ExecuteReader(query, parameters))
            {
                while (reader.Read())
                {
                    userList.Add(new User(reader));
                }
                reader.Close();
            }

            return(userList);
        }
        public SearchImages WithResponseField(string value)
        {
            if (!QueryParameters.ContainsKey(FieldsKey))
            {
                QueryParameters.Add(FieldsKey, new List <string> {
                    value
                });
            }
            else
            {
                var fields = (IList <string>)QueryParameters[FieldsKey];
                if (!fields.Contains(value))
                {
                    fields.Add(value);
                }
            }

            return(this);
        }
Esempio n. 29
0
        public static BindingList <PlanAppoint> LoadList(EPVDatabase database, DateTime date)
        {
            Units units = new Units(database);

            BindingList <PlanAppoint> list = new BindingList <PlanAppoint>();

            QueryParameters parameters = new QueryParameters("dateFrom", date);

            parameters.Add("dateTo", date.AddDays(1).AddSeconds(-1));

            DbDataReader reader = database.ExecuteReader(Queries.QuerySelectList, parameters);

            while (reader.Read())
            {
                list.Add(new PlanAppoint(reader, units));
            }
            reader.Close();
            return(list);
        }
        public override HttpRequest SignRequest(Signer signer, AlibabaCloudCredentials credentials,
                                                FormatType?format, ProductDomain domain)
        {
            Dictionary <String, String> imutableMap = new Dictionary <String, String>(QueryParameters);

            if (null != signer && null != credentials)
            {
                String accessKeyId  = credentials.GetAccessKeyId();
                String accessSecret = credentials.GetAccessKeySecret();
                if (credentials is BasicSessionCredentials)
                {
                    String sessionToken = ((BasicSessionCredentials)credentials).GetSessionToken();
                    if (null != sessionToken)
                    {
                        QueryParameters.Add("SecurityToken", sessionToken);
                    }
                }
                imutableMap = Composer.RefreshSignParameters(QueryParameters, signer, accessKeyId, format);
                imutableMap.Add("RegionId", RegionId);

                Dictionary <String, String> paramsToSign = new Dictionary <String, String>(imutableMap);
                if (this.BodyParameters != null && this.BodyParameters.Count > 0)
                {
                    Dictionary <String, String> formParams = new Dictionary <String, String>(this.BodyParameters);
                    string formStr  = ConcatQueryString(formParams);
                    byte[] formData = System.Text.Encoding.UTF8.GetBytes(formStr);
                    this.SetContent(formData, "UTF-8", FormatType.FORM);
                    foreach (var formParam in formParams)
                    {
                        DictionaryUtil.Add(paramsToSign, formParam.Key, formParam.Value);
                    }
                }

                String strToSign = this.Composer.ComposeStringToSign(Method, null, signer, paramsToSign, null, null);
                String signature = signer.SignString(strToSign, accessSecret + "&");
                imutableMap.Add("Signature", signature);

                this.StringToSign = strToSign;
            }

            Url = this.ComposeUrl(domain.DomianName, imutableMap);
            return(this);
        }
        private static StudyItemList RetrieveAnnotationsInformationForStudy(string studyInstanceUID)
        {
            var queryParams = new QueryParameters();

            queryParams.Add("PatientsName", "");
            queryParams.Add("ReferringPhysiciansName", "");
            queryParams.Add("PatientId", "");
            queryParams.Add("AccessionNumber", "");
            queryParams.Add("StudyDescription", "");
            queryParams.Add("ModalitiesInStudy", "SR");
            queryParams.Add("StudyDate", "");
            queryParams.Add("StudyInstanceUid", studyInstanceUID);

            var serverTree         = new ServerTree();
            var failedServerInfo   = new List <KeyValuePair <string, Exception> >();
            var localDataStoreList = new List <IServerTreeNode>();

            localDataStoreList.Add(serverTree.RootNode.LocalDataStoreNode);

            return(Query(queryParams, failedServerInfo, localDataStoreList));
        }
Esempio n. 32
0
        public DbCompileResult Merge(DbResolveResult whereResult, IDialect dialect)
        {
            int lastParamIndex = QueryParameters.Count;
            var query          = whereResult.SqlQuery;

            foreach (var param in whereResult.QueryParameters)
            {
                var newParamName = $"{dialect.ParameterPrefix}P{lastParamIndex}";

                QueryParameters.Add(newParamName, param.Value);
                query = query.Replace(param.Key, newParamName);

                lastParamIndex++;
            }

            SqlQuery = $"{SqlQuery} {dialect.Where} {query}";

            return(this);
        }
        /// <summary>
        /// This API is used to send one time password to a given phone number for a frictionless login/registration.
        /// </summary>
        /// <param name="oneTouchLoginByPhoneModel">Model Class containing Definition of payload for OneTouchLogin By PhoneModel API</param>
        /// <param name="smsTemplate">SMS Template name</param>
        /// <returns>Response containing Definition of Complete Validation data</returns>
        /// 1.4

        public ApiResponse <PostResponse> OneTouchLoginByPhone(OneTouchLoginByPhoneModel oneTouchLoginByPhoneModel, string smsTemplate = null)
        {
            if (oneTouchLoginByPhoneModel == null)
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(oneTouchLoginByPhoneModel));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
            };

            if (!string.IsNullOrWhiteSpace(smsTemplate))
            {
                queryParameters.Add("smsTemplate", smsTemplate);
            }

            var resourcePath = "identity/v2/auth/onetouchlogin/phone";

            return(ConfigureAndExecute <PostResponse>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(oneTouchLoginByPhoneModel)));
        }
        private void GetUserRole()
        {
            string          query      = DispatcherService.Resources.Doc.MaterialPermit.GetUserRole;
            QueryParameters parameters = new QueryParameters("userId", User.Id);

            parameters.Add("unitId", ((Unit)cboxUnit.SelectedItem).Id);

            object result = Database.ExecuteScalar(query, parameters);

            if (result == null)
            {
                IsCreator = false;
                IsSigner  = false;
            }
            else
            {
                IsCreator = true;
                IsSigner  = ((int)result == 5);
            }
        }
Esempio n. 35
0
        /// <summary>
        /// The Contact API is used to get contacts/friends/connections data from the user's social account.This is one of the APIs that makes up the LoginRadius Friend Invite System. The data will normalized into LoginRadius' standard data format. This API requires setting permissions in your LoginRadius Dashboard. <br><br><b>Note:</b> Facebook restricts access to the list of friends that is returned. When using the Contacts API with Facebook you will only receive friends that have accepted some permissions with your app. <br><br><b>Supported Providers:</b> Facebook, Foursquare, Google, LinkedIn, Live, Twitter, Vkontakte, Yahoo
        /// </summary>
        /// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
        /// <param name="nextCursor">Cursor value if not all contacts can be retrieved once.</param>
        /// <returns>Response containing Definition of Contact Data with Cursor</returns>
        /// 27.1

        public ApiResponse <CursorResponse <Contact> > GetContacts(string accessToken, string nextCursor = "")
        {
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
            }
            var queryParameters = new QueryParameters
            {
                { "access_token", accessToken }
            };

            if (!string.IsNullOrWhiteSpace(nextCursor))
            {
                queryParameters.Add("nextCursor", nextCursor);
            }

            var resourcePath = "api/v2/contact";

            return(ConfigureAndExecute <CursorResponse <Contact> >(HttpMethod.GET, resourcePath, queryParameters, null));
        }
        /// <summary>
        /// This API sends the OTP to specified phone number
        /// </summary>
        /// <param name="forgotPINOtpByPhoneModel">Model Class containing Definition for Forgot Pin Otp By Phone API</param>
        /// <param name="smsTemplate"></param>
        /// <returns>Response Containing Validation Data and SMS Data</returns>
        /// 42.7

        public ApiResponse <UserProfilePostResponse <SMSResponseData> > SendForgotPINSMSByPhone(ForgotPINOtpByPhoneModel forgotPINOtpByPhoneModel, string smsTemplate = null)
        {
            if (forgotPINOtpByPhoneModel == null)
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(forgotPINOtpByPhoneModel));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
            };

            if (!string.IsNullOrWhiteSpace(smsTemplate))
            {
                queryParameters.Add("smsTemplate", smsTemplate);
            }

            var resourcePath = "identity/v2/auth/pin/forgot/otp";

            return(ConfigureAndExecute <UserProfilePostResponse <SMSResponseData> >(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(forgotPINOtpByPhoneModel)));
        }
Esempio n. 37
0
        /// <summary>
        /// The User Profile API is used to get the latest updated social profile data from the user's social account after authentication. The social profile will be retrieved via oAuth and OpenID protocols. The data is normalized into LoginRadius' standard data format. This API should be called using the access token retrieved from the refresh access token API.
        /// </summary>
        /// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
        /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
        /// <returns>Response containing Definition for Complete UserProfile data</returns>
        /// 38.2

        public ApiResponse <UserProfile> GetRefreshedSocialUserProfile(string accessToken, string fields = "")
        {
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
            }
            var queryParameters = new QueryParameters
            {
                { "access_token", accessToken }
            };

            if (!string.IsNullOrWhiteSpace(fields))
            {
                queryParameters.Add("fields", fields);
            }

            var resourcePath = "api/v2/userprofile/refresh";

            return(ConfigureAndExecute <UserProfile>(HttpMethod.GET, resourcePath, queryParameters, null));
        }
        public override string GetLoginUrl(string returnUrl)
        {
            var oauthParameters = new QueryParameters();
            string processedUrl = "";
            if(string.IsNullOrEmpty(provider.UserLoginEndpoint))
                PerformDiscovery();
            oauthParameters.Add("openid.ns", "http://specs.openid.net/auth/2.0");
            oauthParameters.Add("openid.claimed_id", "http://specs.openid.net/auth/2.0/identifier_select");
            oauthParameters.Add("openid.identity", "http://specs.openid.net/auth/2.0/identifier_select");
            oauthParameters.Add("openid.return_to", returnUrl);
            oauthParameters.Add("openid.realm", ConnectionToken.Domain);
            oauthParameters.Add("openid.mode", "checkid_setup");
            oauthParameters.Add("openid.ns.pape", "http://specs.openid.net/extensions/pape/1.0");
            oauthParameters.Add("openid.ns.max_auth_age", "0");
            oauthParameters.Add("openid.ns.ax", "http://openid.net/srv/ax/1.0");
            oauthParameters.Add("openid.ax.mode", "fetch_request");
            oauthParameters.Add("openid.ax.type.country", "http://axschema.org/contact/country/home");
            oauthParameters.Add("openid.ax.type.email", "http://axschema.org/contact/email");
            oauthParameters.Add("openid.ax.type.firstname", "http://axschema.org/namePerson/first");
            oauthParameters.Add("openid.ax.type.language", "http://axschema.org/pref/language");
            oauthParameters.Add("openid.ax.type.lastname", "http://axschema.org/namePerson/last");
            oauthParameters.Add("openid.ax.required", "country,email,firstname,language,lastname");
            //ADDING OAUTH PROTOCOLS
            oauthParameters.Add("openid.ns.oauth", "http://specs.openid.net/extensions/oauth/1.0");
            oauthParameters.Add("openid.oauth.consumer", provider.Consumerkey);

            BeforeDirectingUserToServiceProvider(oauthParameters);

            processedUrl = oauthParameters.ToEncodedString();

            return provider.UserLoginEndpoint + "?" + processedUrl;

        }
        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;
        }
        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;
        }
        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 void HandleRequestToken(QueryParameters responseCollection)
        {
            //In Hybrid protocol, OAuth may not be necessary. In such case flow ends
            //But some providers may have scope black as scope is defined at provider directly (like Yahoo)

            if (responseCollection.HasName("openid.mode"))
            {
                if (responseCollection["openid.mode"].Contains("cancel"))
                    throw new UserDeniedPermissionException(provider.ProviderType);
            }

            if (!string.IsNullOrEmpty(provider.GetScope()) || provider.IsScopeDefinedAtProvider)
                if (responseCollection.HasName("openid.oauth.request_token"))
                    ConnectionToken.RequestToken = responseCollection["openid.oauth.request_token"];
                else if (responseCollection.HasName("openid.ext2.request_token"))
                    ConnectionToken.RequestToken = responseCollection["openid.ext2.request_token"];
                else
                {
                    logger.Error(ErrorMessages.RequestTokenResponseInvalid(responseCollection));
                    throw new OAuthException(ErrorMessages.RequestTokenResponseInvalid(responseCollection));
                }
            QueryParameters openIDValues = new QueryParameters();
            if (responseCollection.HasName("openid.ns.ext1"))
            {
                if (responseCollection.HasName("openid.ext1.value.email"))
                    openIDValues.Add(new QueryParameter("openid.ext1.value.email", responseCollection["openid.ext1.value.email"]));
                if (responseCollection.HasName("openid.ext1.value.firstname"))
                    openIDValues.Add(new QueryParameter("openid.ext1.value.firstname", responseCollection["openid.ext1.value.firstname"]));
                if (responseCollection.HasName("openid.ext1.value.lastname"))
                    openIDValues.Add(new QueryParameter("openid.ext1.value.lastname", responseCollection["openid.ext1.value.lastname"]));
                if (responseCollection.HasName("openid.ext1.value.language"))
                    openIDValues.Add(new QueryParameter("openid.ext1.value.language", responseCollection["openid.ext1.value.language"]));
                if (responseCollection.HasName("openid.ext1.value.country"))
                    openIDValues.Add(new QueryParameter("openid.ext1.value.country", responseCollection["openid.ext1.value.country"]));
                if (responseCollection.HasName("openid.identity"))
                    openIDValues.Add(new QueryParameter("openid.identity", responseCollection["openid.identity"]));
                ConnectionToken.ResponseCollection.AddRange(openIDValues, true);
            }
            else if (responseCollection.HasName("openid.ns.ax"))
            {
                if (responseCollection.HasName("openid.ax.value.email"))
                    openIDValues.Add(new QueryParameter("openid.ax.value.email", responseCollection["openid.ax.value.email"]));
                if (responseCollection.HasName("openid.ax.value.firstname"))
                    openIDValues.Add(new QueryParameter("openid.ax.value.firstname", responseCollection["openid.ax.value.firstname"]));
                if (responseCollection.HasName("openid.ax.value.lastname"))
                    openIDValues.Add(new QueryParameter("openid.ax.value.lastname", responseCollection["openid.ax.value.lastname"]));
                if (responseCollection.HasName("openid.ax.value.language"))
                    openIDValues.Add(new QueryParameter("openid.ax.value.language", responseCollection["openid.ax.value.language"]));
                if (responseCollection.HasName("openid.ax.value.country"))
                    openIDValues.Add(new QueryParameter("openid.ax.value.country", responseCollection["openid.ax.value.country"]));
                ConnectionToken.ResponseCollection.AddRange(openIDValues, true);
            }
            logger.Info("User successfully logged in and returned with Authorization Token");
        }
Esempio n. 43
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());
        }
        private static StudyItemList RetrieveAnnotationsInformationForStudy(string studyInstanceUID)
        {
            var queryParams = new QueryParameters();
            queryParams.Add("PatientsName", "");
            queryParams.Add("ReferringPhysiciansName", "");
            queryParams.Add("PatientId", "");
            queryParams.Add("AccessionNumber", "");
            queryParams.Add("StudyDescription", "");
            queryParams.Add("ModalitiesInStudy", "SR");
            queryParams.Add("StudyDate", "");
            queryParams.Add("StudyInstanceUid", studyInstanceUID);

            var serverTree = new ServerTree();
            var failedServerInfo = new List<KeyValuePair<string, Exception>>();
            var localDataStoreList = new List<IServerTreeNode>();
            localDataStoreList.Add(serverTree.RootNode.LocalDataStoreNode);

            return Query(queryParams, failedServerInfo, localDataStoreList);
        }
Esempio n. 45
0
        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);
            }

        }
Esempio n. 46
0
        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", connectionToken.AuthorizationToken);
            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");
            oauthParameters.Add("oauth_verifier", connectionToken.OauthVerifier);
            signature = oauthHelper.GenerateSignature(new Uri(provider.AccessTokenEndpoint), oauthParameters, provider.Consumerkey, provider.Consumersecret, provider.SignatureMethod, provider.TransportName, connectionToken.TokenSecret);
            oauthParameters.Add("oauth_signature", signature);

            //2. Notify Consumer (if applicable)
            BeforeRequestingAccessToken(oauthParameters); // hook called

            //3.Connect and obtain Token
            string targetUrl = provider.AccessTokenEndpoint + "?" +
                               oauthHelper.GetAuthorizationUrlParameters(oauthParameters);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUrl);
            request.Method = provider.TransportName.ToString();
            //request.Headers.Add("Authorization", oauthHelper.GetAuthorizationHeader(oauthParameters));
            request.ContentLength = 0;
            string response = "";

            try
            {
                logger.Debug("Requesting Access Token at " + provider.AccessTokenEndpoint);
                using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
                using (Stream responseStream = webResponse.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    response = reader.ReadToEnd();
                    var responseCollection = Utility.GetQuerystringParameters(response);
                    HandleAccessTokenResponse(responseCollection);

                }

            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.AccessTokenRequestError(provider.AccessTokenEndpoint, oauthParameters), ex);
                throw new OAuthException(ErrorMessages.AccessTokenRequestError(provider.AccessTokenEndpoint, oauthParameters), ex);
            }


        }
Esempio n. 47
0
        public void TestQuoteSimpleQuery()
        {
            var query = new QueryParameters<Artist>();

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

            Assert.AreEqual("artist:\"bob dylan\"", query.ToString());
        }
        public void HandleAccessTokenResponse(string response)
        {
            QueryParameters responseCollection = new QueryParameters();

            try
            {
                if (response.StartsWith("{")) // access token is returned in JSON format
                {
                    //  {"access_token":"asasdasdAA","expires_in":3600,"scope":"wl.basic","token_type":"bearer"}
                    JObject accessTokenJson = JObject.Parse(response);
                    responseCollection.Add("response", response);
                    ConnectionToken.AccessToken = accessTokenJson.SelectToken("access_token").ToString().Replace("\"", "");
                    if (accessTokenJson.SelectToken("expires_in") != null)
                        ConnectionToken.ExpiresOn = DateTime.Now.AddSeconds(int.Parse(accessTokenJson.SelectToken("expires_in").ToString().Replace("\"", "")) - 20);
                    //put in raw list
                    foreach (var t in accessTokenJson.AfterSelf())
                        ConnectionToken.ResponseCollection.Add(t.Type.ToString(), t.ToString());
                    logger.Info("Access Token successfully received");
                    isSuccess = true;
                }
                else // access token is returned as part of Query String
                {

                    responseCollection = Utility.GetQuerystringParameters(response);
                    string keyForAccessToken = responseCollection.Single(x => x.Key.Contains("token")).Key;

                    ConnectionToken.AccessToken = responseCollection[keyForAccessToken].Replace("\"", "");
                    if (responseCollection.ToList().Exists(x => x.Key.ToLower().Contains("expir")))
                    {
                        string keyForExpiry = responseCollection.Single(x => x.Key.Contains("expir")).Key;
                        ConnectionToken.ExpiresOn = ConnectionToken.ExpiresOn = DateTime.Now.AddSeconds(int.Parse(responseCollection[keyForExpiry].Replace("\"", "")) - 20);
                    }
                    //put in raw list
                    responseCollection.ToList().ForEach(x => ConnectionToken.ResponseCollection.Add(x.Key, x.Value));
                    logger.Info("Access Token successfully received");
                    isSuccess = true;

                }
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.AccessTokenResponseInvalid(responseCollection), ex);
                throw new OAuthException(ErrorMessages.AccessTokenResponseInvalid(responseCollection), ex);
            }
        }
Esempio n. 49
0
		private async Task<Album> GetAlbumQuery(string artistName, string albumName)
		{
			// If we have an artist in form "LastName, FirstName" change it to "FirstName LastName" to have both results
			var artistNameOriginal = _switchedArtist.IsMatch(artistName) ? string.Format(" OR {0}",SwitchArtist(artistName)) : "";

			var query = new QueryParameters<Release>();
			query.Add("artist", string.Format("{0} {1}", artistName, artistNameOriginal));
			query.Add("release", albumName);
			var albums = await Release.SearchAsync(query);

			// First look for Albums from the selected country in AmazonSites
			var mbAlbum = albums.Items.FirstOrDefault(r => (r.Title != null && r.Title.ToLower() == albumName.ToLower()) && (r.Country != null && r.Country.ToLower() == Options.MainSettings.AmazonSite.ToLower()));
			if (mbAlbum == null)
			{
				// Look for European wide release
				mbAlbum = albums.Items.FirstOrDefault(r => (r.Title != null && r.Title.ToLower() == albumName.ToLower()) && (r.Country != null && r.Country.ToLower() == "xe"));
				if (mbAlbum == null)
				{
					// Look for US release
					mbAlbum = albums.Items.FirstOrDefault(r => (r.Title != null && r.Title.ToLower() == albumName.ToLower()) && (r.Country != null && r.Country.ToLower() == "us"));
					if (mbAlbum == null)
					{
						mbAlbum = albums.Items.Count > 0 ? albums.Items[0] : null;
						if (mbAlbum == null)
						{
							return null;
						}
					}
				}
			}

			var release = await Release.GetAsync(mbAlbum.Id, new[] { "recordings", "media", "artists", "discids" });
			
			var album = new Album();
			album.LargeImageUrl = release.CoverArtArchive != null && release.CoverArtArchive.Front
				? string.Format(@"http://coverartarchive.org/release/{0}/front.jpg", release.Id)
				: "";
			album.CoverHeight = "0";
			album.CoverWidth = "0";
			album.Artist = JoinArtists(release.Credits);
			album.Title = release.Title;
			album.Year = release.Date;
			album.DiscCount = release.MediumList.Items.Count;

			// Get the Tracks
			var discs = new List<List<AlbumTrack>>();	
			foreach (var medium in release.MediumList.Items)
			{
				var albumTracks = new List<AlbumTrack>();
				foreach (var track in medium.Tracks.Items)
				{
					AlbumTrack albumtrack = new AlbumTrack();
					albumtrack.Number = track.Position;
					TimeSpan duration = TimeSpan.FromMilliseconds(track.Recording.Length);
					albumtrack.Duration = string.Format("{0:mm\\:ss}", duration);
					albumtrack.Title = track.Recording.Title;
					albumTracks.Add(albumtrack);
				}
				discs.Add(albumTracks);
			}
			album.Discs = discs;
			return album;
		}
Esempio n. 50
0
        /// <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 void DirectUserToServiceProvider()
        {

            QueryParameters oauthParameters = new QueryParameters();
            string processedUrl = "";

            try
            {
                oauthParameters.Add("openid.ns", "http://specs.openid.net/auth/2.0");
                oauthParameters.Add("openid.claimed_id", "http://specs.openid.net/auth/2.0/identifier_select");
                oauthParameters.Add("openid.identity", "http://specs.openid.net/auth/2.0/identifier_select");
                oauthParameters.Add("openid.return_to", connectionToken.ProviderCallbackUrl);
                oauthParameters.Add("openid.realm", connectionToken.Domain);
                oauthParameters.Add("openid.mode", "checkid_setup");
                oauthParameters.Add("openid.ns.pape", "http://specs.openid.net/extensions/pape/1.0");
                oauthParameters.Add("openid.ns.max_auth_age", "0");
                oauthParameters.Add("openid.ns.ax", "http://openid.net/srv/ax/1.0");
                oauthParameters.Add("openid.ax.mode", "fetch_request");
                oauthParameters.Add("openid.ax.type.country", "http://axschema.org/contact/country/home");
                oauthParameters.Add("openid.ax.type.email", "http://axschema.org/contact/email");
                oauthParameters.Add("openid.ax.type.firstname", "http://axschema.org/namePerson/first");
                oauthParameters.Add("openid.ax.type.language", "http://axschema.org/pref/language");
                oauthParameters.Add("openid.ax.type.lastname", "http://axschema.org/namePerson/last");
                oauthParameters.Add("openid.ax.required", "country,email,firstname,language,lastname");
                //ADDING OAUTH PROTOCOLS
                oauthParameters.Add("openid.ns.oauth", "http://specs.openid.net/extensions/oauth/1.0");
                oauthParameters.Add("openid.oauth.consumer", provider.Consumerkey);

                BeforeDirectingUserToServiceProvider(oauthParameters);

                processedUrl = oauthParameters.ToEncodedString();

                logger.Debug("Redirecting user for login to " + processedUrl);
                SocialAuthUser.Redirect(provider.UserLoginEndpoint + "?" + processedUrl);
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.UserLoginRedirectionError(provider.UserLoginEndpoint + "?" + processedUrl), ex);
            }
        }
		private static StudyItemList RetrieveAnnotationsInformationForStudy(string studyInstanceUID)
		{
			QueryParameters queryParams = new QueryParameters();
			queryParams.Add("PatientsName", "");
			queryParams.Add("ReferringPhysiciansName", "");
			queryParams.Add("PatientId", "");
			queryParams.Add("AccessionNumber", "");
			queryParams.Add("StudyDescription", "");
			queryParams.Add("ModalitiesInStudy", "SR");
			queryParams.Add("StudyDate", "");
			queryParams.Add("StudyInstanceUid", studyInstanceUID);

			ServerTree serverTree = new ServerTree();
			List<KeyValuePair<string, Exception>> failedServerInfo = new List<KeyValuePair<string, Exception>>();
			List<IServerTreeNode> localDataStoreList = new List<IServerTreeNode>();

			// TODO - retrieve annotations from remote host as well. Maybe, when streaming is in use only?

			localDataStoreList.Add(serverTree.RootNode.LocalDataStoreNode);

			return Query(queryParams, failedServerInfo, localDataStoreList);
		}
Esempio n. 53
0
        public void RequestForRequestToken()
        {

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


            //Twitter Test @ https://dev.twitter.com/docs/auth/oauth
            //oauthParameters.Add("oauth_callback", "http://localhost:3005/the_dance/process_callback?service_provider_id=11");
            //oauthParameters.Add("oauth_consumer_key", "GDdmIQH6jhtmLUypg82g");
            //oauthParameters.Add("oauth_nonce", "QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk");
            //oauthParameters.Add("oauth_signature_method", "HMAC-SHA1");
            //oauthParameters.Add("oauth_timestamp", "1272323042");
            //oauthParameters.Add("oauth_version", "1.0");
            //signature = oauthHelper.GenerateSignature(new Uri(provider.RequestTokenEndpoint), oauthParameters, "GDdmIQH6jhtmLUypg82g", "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", provider.SignatureMethod, provider.TransportName, string.Empty);

            ////1. Setup request parameters
            oauthParameters.Add("oauth_consumer_key", provider.Consumerkey);
            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");
            oauthParameters.Add("oauth_callback", connectionToken.Domain + "SocialAuth/validate.sauth");

            //2. Notify Consumer (optionally user may wish to add extra parameters)
            BeforeRequestingRequestToken(oauthParameters); // hook called

            //3. Generate Signature
            signature = oauthHelper.GenerateSignature(new Uri(provider.RequestTokenEndpoint), oauthParameters, provider.Consumerkey, provider.Consumersecret, provider.SignatureMethod, provider.TransportName, string.Empty);
            oauthParameters.Add("oauth_signature", signature);


            //4.Connect and obtain Token
            logger.Debug("Requesting Request Token at: " + provider.RequestTokenEndpoint);
            string requestUrl = provider.RequestTokenEndpoint + "?" + oauthHelper.GetAuthorizationUrlParameters(oauthParameters);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
            request.Method = provider.TransportName.ToString();
            //request.Headers.Add("Authorization", oauthHelper.GetAuthorizationHeader(oauthParameters));
            request.ContentLength = 0;
            //request.ContentType = "application/x-www-form-urlencoded";
            //TODO: Check issue with Authorization Header
            string response = "";

            try
            {

                logger.Debug("Requesting Request Token at: " + provider.RequestTokenEndpoint);
                using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
                using (Stream responseStream = webResponse.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    response = reader.ReadToEnd();
                    if (response.Contains("oauth_token_secret"))
                    {
                        logger.Debug("Request Token response: " + response.ToString());
                        var responseCollection = Utility.GetQuerystringParameters(response);
                        HandleRequestTokenGrant(responseCollection);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.RequestTokenRequestError(provider.RequestTokenEndpoint, oauthParameters), ex);
                throw new OAuthException(ErrorMessages.RequestTokenRequestError(provider.RequestTokenEndpoint, oauthParameters), ex);
            }
        }