/// <summary>
        /// Logs in the user with the specified provider.
        /// </summary>
        /// <param name="provider">User credentials provider.</param>
        private void LoginWith(string provider)
        {
            // If already logging in
            if (this.IsBusy)
            {
                return;
            }

            // Remove OAUTH token
            Settings.Instance.Remove(Settings.OauthToken);

            // If launch URI delegate is provided
            if (((App)Application.Current).LaunchUriDelegate != null)
            {
                // Get the authorization URI from the server
                this.IsBusy = true;
                WebHelper.SendAsync(
                    Uris.GetAuthorizationUri(provider),
                    null,
                    this.ProcessLoginWithResult,
                    () => this.IsBusy = false);
            }
            else
            {
                // Display the not implemented error
                App.DisplayAlert(
                    Localization.ErrorDialogTitle,
                    Localization.ErrorNotImplemented,
                    Localization.DialogDismiss);
            }
        }
Beispiel #2
0
        public async Task <ImageSizesEntity> GetImageSizesAsync()
        {
            // NOTE: We need to append -0 to the image key otherwise we will not get the right value
            // /image/(*)!sizes
            //return await image____sizes();

            // /image/(*)!sizes

            // get the image key from the Uris if possible

            string        imgKey = ImageKey;
            UriDescriptor val;

            if (Uris.TryGetValue("Image", out val))
            {
                var posLastSlash = val.Uri.LastIndexOf("/");
                if (posLastSlash >= 0)
                {
                    imgKey = val.Uri.Substring(posLastSlash + 1);
                }
            }

            string requestUri = string.Format("{0}/image/{1}!sizes", SmugMug.v2.Constants.Addresses.SmugMugApi, imgKey);

            return(await RetrieveEntityAsync <ImageSizesEntity>(requestUri));
        }
 public void ReportStatus(CancellationToken cancellationToken)
 {
     try
     {
         var failureRate = (Uris.Count() - ProcessedDicomFiles.Count) / Uris.Count();
         if (failureRate > FailureThreshold)
         {
             var retry = Retries < MaxRetry;
             resultsService.ReportFailure(TaskId, retry, cancellationToken);
             Logger.LogInformation(
                 "Task marked as failed with failure rate={0}, total={1}, failed={2}, processed={3}, retry={4}",
                 failureRate,
                 Uris.Count(),
                 FailedDicomFiles.Count + FailedFiles.Count,
                 ProcessedDicomFiles.Count,
                 retry);
         }
         else
         {
             resultsService.ReportSuccess(TaskId, cancellationToken);
             Logger.LogInformation("Task marked as successful");
         }
     }
     catch (System.Exception ex)
     {
         Logger.LogError("Failed to report status back to Results Service: {0}", ex);
     }
 }
Beispiel #4
0
        private int CreateUrisHashCode()
        {
            var uriStrings     = Uris.Select(uri => uri.UrlString).ToArray();
            var hashCodeString = string.Join(string.Empty, uriStrings);

            return(hashCodeString.GetHashCode());
        }
Beispiel #5
0
 public void AddTracks(params string[] trackIds)
 {
     foreach (var trackId in trackIds)
     {
         Uris.Add(string.Format(SpotifyConstants.TrackUriFormat, trackId));
     }
 }
Beispiel #6
0
        /// <summary>
        /// Saves the user data.
        /// </summary>
        private void Save()
        {
            // If already saving information
            if (this.IsBusy)
            {
                return;
            }

            // Validate that the notification type is valid
            if (this.NotificationTypeIndex < 0)
            {
                App.DisplayAlert(
                    Localization.ErrorDialogTitle,
                    Localization.ErrorInvalidNotificationTypes,
                    Localization.DialogDismiss);
                return;
            }

            // Prepare the data to be send to the server
            var request = new Json.JsonObject {
                { "notification_types", this.NotificationTypeIndex }
            };

            // Send request to the server
            this.IsBusy = true;
            WebHelper.SendAsync(
                Uris.GetUpdateUserInfoUri(),
                request.AsHttpContent(),
                this.ProcessSaveResult,
                () => this.IsBusy = false);
        }
Beispiel #7
0
        public static void InjectDependencies(this WebAssemblyHostBuilder builder)
        {
            var services      = builder.Services;
            var configuration = builder.Configuration;

            // default (from Program.cs)
            services.AddScoped(sp => new HttpClient {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });

            // shared
            services.AddScoped <ISimpleLogger, SimpleLogger>();
            services.AddScoped <ICustomHttpClientFactory, CustomHttpClientFactory>();
            services.AddScoped <IApiClient, ApiClient>();

            // this project
            services.AddScoped <IWeatherService, WeatherService>();

            var uris = new Uris();

            configuration.GetSection(nameof(Uris)).Bind(uris);
            //services.AddSingleton(uris);
            Console.WriteLine($"API url: {uris.Backend.AbsoluteUri}");

            services.SetupHttpClient(ApiClient.Name, uris.Backend.AbsoluteUri);
        }
 public DocumentQuery(params string[] uris)
 {
     foreach (var uri in uris)
     {
         Uris.Add(uri);
     }
 }
Beispiel #9
0
        public override bool Execute()
        {
            if (Retries < 0)
            {
                Log.LogError($"Invalid task parameter value: Retries={Retries}");
                return(false);
            }

            if (RetryDelayMilliseconds < 0)
            {
                Log.LogError($"Invalid task parameter value: RetryDelayMilliseconds={RetryDelayMilliseconds}");
                return(false);
            }

            if (File.Exists(DestinationPath) && !Overwrite)
            {
                return(true);
            }

            if (string.IsNullOrWhiteSpace(Uri) && (Uris == null || Uris.Count() == 0))
            {
                Log.LogError($"Invalid task parameter value: {nameof(Uri)} and {nameof(Uris)} are empty.");
                return(false);
            }

            Directory.CreateDirectory(Path.GetDirectoryName(DestinationPath));

            if (!string.IsNullOrWhiteSpace(Uri))
            {
                return(DownloadFromUriAsync(Uri).Result);
            }

            if (Uris != null)
            {
                foreach (var uriConfig in Uris)
                {
                    var uri          = uriConfig.ItemSpec;
                    var encodedToken = uriConfig.GetMetadata("token");

                    if (!string.IsNullOrWhiteSpace(encodedToken))
                    {
                        var encodedTokenBytes = System.Convert.FromBase64String(encodedToken);
                        var decodedToken      = System.Text.Encoding.UTF8.GetString(encodedTokenBytes);
                        uri = $"{uri}{decodedToken}";
                    }

                    if (DownloadFromUriAsync(uri).Result)
                    {
                        return(true);
                    }
                }

                Log.LogError($"Download from all targets failed. List of attempted targets: {string.Join(", ", Uris.Select(m => m.ItemSpec))}");
            }

            Log.LogError($"Failed to download file using addresses in {nameof(Uri)} and/or {nameof(Uris)}.");

            return(false);
        }
        public Either <string, TestsMatchResult> MatchTestRuns(Some <string> oldTestsRunUrl, Some <string> newTestsRunUrl)
        {
            Func <string, Either <string, Lst <TestBuildResult> > > getBuildTests = testsRunUrl =>
                                                                                    Uris.ParseUri(testsRunUrl).Bind(ParseBuildId).Bind(_buildTestsObtainer.GetBuildFailedTests);

            return(getBuildTests(oldTestsRunUrl)
                   .LiftM2(getBuildTests(newTestsRunUrl), _testResultMatcher.MatchTestRuns));
        }
Beispiel #11
0
 public override BitwardenItemLogin ConvertBack()
 {
     return(new BitwardenItemLogin
     {
         Uris = Uris.Select(x => x.ConvertBack()).ToList(),
         Username = Username,
         Password = Password,
     });
 }
Beispiel #12
0
        public void can_delete_user_with_correct_credentials()
        {
            given_request_to(Uris.User(2))
            .Delete()
            .Credentials("username", "password");

            when_retrieving_the_response();

            Response.StatusCode.ShouldBe(200);
        }
Beispiel #13
0
        public void cannot_delete_user_with_wrong_credentials()
        {
            given_request_to(Uris.User(2))
            .Delete()
            .Credentials("username", "wrongpassword");

            when_retrieving_the_response();

            Response.StatusCode.ShouldBe(401);
        }
Beispiel #14
0
        public CipherLoginModel(CipherLoginData data)
        {
            Uris = data.Uris?.Select(u => new CipherLoginUriModel(u))?.ToList();
            if (!Uris?.Any() ?? true)
            {
                Uri = data.Uri;
            }

            Username = data.Username;
            Password = data.Password;
            Totp     = data.Totp;
        }
Beispiel #15
0
        public CipherLoginModel(CipherLoginData data)
        {
            Uris = data.Uris?.Select(u => new CipherLoginUriModel(u))?.ToList();
            if (!Uris?.Any() ?? true)
            {
                Uri = data.Uri;
            }

            Username             = data.Username;
            Password             = data.Password;
            PasswordRevisionDate = data.PasswordRevisionDate;
            Totp = data.Totp;
            AutofillOnPageLoad = data.AutofillOnPageLoad;
        }
Beispiel #16
0
        /// <summary>
        /// Gets the user informarion from the server.
        /// </summary>
        private void GetUserInfo()
        {
            // If already loading user infomation
            if (this.IsBusy)
            {
                return;
            }

            // Send request to the server
            this.IsBusy = true;
            WebHelper.SendAsync(
                Uris.GetGetUserInfoUri(),
                null,
                this.ProcessGetUserDataResult,
                () => this.IsBusy = false);
        }
Beispiel #17
0
        /// <summary>
        /// Parse certificate for alternate name extension.
        /// </summary>
        private void Parse(byte[] data)
        {
            if (Oid.Value != Oids.SubjectAltName &&
                Oid.Value != Oids.SubjectAltName2)
            {
                throw new FormatException("Extension has unknown oid.");
            }

            Uris.Clear();
            DomainNames.Clear();
            IPAddresses.Clear();

            var altNames        = new DerOctetString(data);
            var altNamesObjects = X509ExtensionUtilities.FromExtensionValue(altNames);
            var generalNames    =
                Org.BouncyCastle.Asn1.X509.GeneralNames.GetInstance(altNamesObjects);

            foreach (var generalName in generalNames.GetNames())
            {
                switch (generalName.TagNo)
                {
                case Org.BouncyCastle.Asn1.X509.GeneralName.UniformResourceIdentifier:
                    Uris.Add(generalName.Name.ToString());
                    break;

                case Org.BouncyCastle.Asn1.X509.GeneralName.DnsName:
                    DomainNames.Add(generalName.Name.ToString());
                    break;

                case Org.BouncyCastle.Asn1.X509.GeneralName.IPAddress:
                    try {
                        var addr = Asn1OctetString
                                   .GetInstance(generalName.Name)
                                   .GetOctets();
                        IPAddresses.Add(new IPAddress(addr).ToString());
                    }
                    catch {
                        throw new FormatException(
                                  "Certificate contains invalid IP address.");
                    }
                    break;

                default:
                    break;
                }
            }
        }
Beispiel #18
0
 public PdfController(
     PdfDataContext context,
     IStorage pdfStorage,
     Uris uris,
     IHangfireQueue backgroundJob,
     TemplatingEngine templatingEngine,
     IErrorPages errorPages,
     IMqMessages mqMessages)
 {
     _context          = context;
     _pdfStorage       = pdfStorage;
     _uris             = uris;
     _backgroundJobs   = backgroundJob;
     _templatingEngine = templatingEngine;
     _errorPages       = errorPages;
     _mqMessages       = mqMessages;
 }
Beispiel #19
0
        public LoginData ToLoginData()
        {
            var l = new LoginData();

            l.PasswordRevisionDate = PasswordRevisionDate;
            BuildDataModel(this, l, new HashSet <string>
            {
                "Username",
                "Password",
                "Totp"
            });
            if (Uris?.Any() ?? false)
            {
                l.Uris = Uris.Select(u => u.ToLoginUriData()).ToList();
            }
            return(l);
        }
Beispiel #20
0
        public async Task Save(Payload <IPayload> payload)
        {
            _logger.LogInformation($"Saving apartment for rent data located in: {payload.Apartment.City}");
            var apartmentContent = new StringContent(JsonConvert.SerializeObject(payload), System.Text.Encoding.UTF8, "application/json");
            HttpResponseMessage response;
            string url = Uris.GetUrl(_apartmentUrl, payload.InObject.GetType().Name);

            if (payload.Apartment.Id > 0)
            {
                response = await _httpClient.PutAsync(url, apartmentContent);
            }
            else
            {
                response = await _httpClient.PostAsync(url, apartmentContent);
            }
            _logger.LogInformation($"Response of saving apartment, Status Code: {response.StatusCode}");
            response.EnsureSuccessStatusCode();
        }
Beispiel #21
0
        protected override void PrepareParam()
        {
            if (Uris == null || !Uris.Any())
            {
                throw new Exception();
            }

            AddParam(Uris);

            if (Options != null)
            {
                AddParam(Options);
                if (Position.HasValue)
                {
                    AddParam(Position);
                }
            }
        }
        /// <summary>
        /// Retries the login process after user consent to change session.
        /// </summary>
        /// <param name="request">The request to retry.</param>
        /// <param name="response">The response received from the server.</param>
        private async void RetryLogin(JsonObject request, JsonValue response)
        {
            // Ask the user consent to override session
            var consent = await App.DisplayAlert(
                Localization.ConfirmationDialogTitle,
                Localization.ConfirmationSesionChange,
                Localization.ButtonConfirm,
                Localization.Cancel);

            // If the user consent received
            if (consent)
            {
                // Modify the request based on server response
                var grantType = response.GetItemOrDefault("grant_type").GetStringValueOrDefault(string.Empty);
                if (!string.IsNullOrEmpty(grantType))
                {
                    request["grant_type"] = grantType;
                }

                var state = response.GetItemOrDefault("state").GetStringValueOrDefault(string.Empty);
                if (!string.IsNullOrEmpty(state))
                {
                    request["state"] = state;
                }

                // Resent the request to the server
                request.Add("override", true);
                WebHelper.SendAsync(
                    Uris.GetLoginUri(),
                    request.AsHttpContent(),
                    this.ProcessLoginResult,
                    () => this.IsBusy = false);
            }
            else
            {
                // Cancel the task
                this.UserName = string.Empty;
                this.Password = string.Empty;
                this.OnPropertyChanged(nameof(this.Password));
                this.IsBusy = false;
            }
        }
Beispiel #23
0
        public override object GetData(DeterministicRandom r)
        {
            if (needToAddFilesWithSearchPatterns)
            {
                UriList urisFromPathList = MakeUris(pathList);

                if (Uris == null)
                {
                    Uris = urisFromPathList;
                }
                else
                {
                    Uris.AddRange(MakeUris(pathList));
                }

                needToAddFilesWithSearchPatterns = false;
            }

            return(r.NextItem <Uri>(Uris));
        }
Beispiel #24
0
        public async Task UploadImage(IFormFile file, Guid requestId)
        {
            if (file == null)
            {
                return;
            }
            var rule = new IsFileNotNull().And(new IsFileSizeSuitable(_options)).And(new IsFileExtntionSuitable()).And(new IsFileSignatureSuitable());

            if (!rule.IsSatisfiedBy(file))
            {
                throw new ArgumentException("Data saved, but file size should less than 2Mb and type should be [JPG, JPEG, PNG].");
            }
            string url     = Uris.GetUrl(_apartmentUrl, "Pic");
            var    imgData = new MultipartFormDataContent
            {
                { new StreamContent(file.OpenReadStream()), "imgfile", file.FileName }
            };

            _httpClient.DefaultRequestHeaders.Add("x-requestid", requestId.ToString());
            var response = await _httpClient.PostAsync(url, imgData);

            _logger.LogDebug("[UploadImage] -> response code {StatusCode}", response.StatusCode);
            response.EnsureSuccessStatusCode();
        }
Beispiel #25
0
        public async Task Should_return_meeting_room_when_booking_courtroom()
        {
            const bool   audioRecordingRequired = false;
            const string ingestUrl = null;
            var          endpoints = new List <EndpointDto>
            {
                new EndpointDto {
                    Id = Guid.NewGuid(), Pin = "1234", DisplayName = "one", SipAddress = "99191919"
                },
                new EndpointDto {
                    Id = Guid.NewGuid(), Pin = "5678", DisplayName = "two", SipAddress = "5385983832"
                }
            };

            var hearingParams = new CreateHearingParams
            {
                Virtual_courtroom_id = _testConference.Id.ToString(),
                Callback_uri         = _kinlyConfigOptions.Value.CallbackUri,
                Recording_enabled    = audioRecordingRequired,
                Recording_url        = ingestUrl,
                Streaming_enabled    = false,
                Streaming_url        = null,
                Jvs_endpoint         = endpoints.Select(EndpointMapper.MapToEndpoint).ToList()
            };

            var uris = new Uris
            {
                Admin = "admin", Participant = "participant", Pexip_node = "pexip"
            };

            _kinlyApiClientMock
            .Setup(x => x.CreateHearingAsync(It.Is <CreateHearingParams>(param =>
                                                                         param.Virtual_courtroom_id == hearingParams.Virtual_courtroom_id &&
                                                                         param.Callback_uri == hearingParams.Callback_uri &&
                                                                         param.Recording_enabled == hearingParams.Recording_enabled &&
                                                                         param.Recording_url == hearingParams.Recording_url &&
                                                                         param.Streaming_enabled == hearingParams.Streaming_enabled &&
                                                                         param.Streaming_url == hearingParams.Streaming_url
                                                                         )))
            .ReturnsAsync(() => new Hearing
            {
                Uris = uris,
                Telephone_conference_id = "12345678",
                Virtual_courtroom_id    = Guid.NewGuid()
            });

            var result = await _kinlyPlatformService.BookVirtualCourtroomAsync(_testConference.Id,
                                                                               audioRecordingRequired,
                                                                               ingestUrl,
                                                                               endpoints);

            result.Should().NotBeNull();
            result.AdminUri.Should().Be(uris.Admin);
            result.JudgeUri.Should().Be(uris.Participant);
            result.ParticipantUri.Should().Be(uris.Participant);
            result.PexipNode.Should().Be(uris.Pexip_node);

            _kinlyApiClientMock.Verify(x => x.CreateHearingAsync(It.Is <CreateHearingParams>(param =>
                                                                                             param.Virtual_courtroom_id == hearingParams.Virtual_courtroom_id &&
                                                                                             param.Callback_uri == hearingParams.Callback_uri &&
                                                                                             param.Recording_enabled == hearingParams.Recording_enabled &&
                                                                                             param.Recording_url == hearingParams.Recording_url &&
                                                                                             param.Streaming_enabled == hearingParams.Streaming_enabled &&
                                                                                             param.Streaming_url == hearingParams.Streaming_url &&
                                                                                             param.Jvs_endpoint != null && param.Jvs_endpoint.Count == hearingParams.Jvs_endpoint.Count
                                                                                             )), Times.Once);
        }
Beispiel #26
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public ServiceDependencies()
        {
            // $hack(jefflill): This screams for dependency injection.

            var textLogger = new TextLogger(LogManager.Default);

            // Parse: NEON_SERVICE_DEPENDENCIES_URIS

            var urisVar = Environment.GetEnvironmentVariable("NEON_SERVICE_DEPENDENCIES_URIS");

            if (!string.IsNullOrEmpty(urisVar))
            {
                var uris = urisVar.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var item in uris)
                {
                    var uriString = item.Trim();

                    if (string.IsNullOrEmpty(uriString))
                    {
                        continue;
                    }

                    if (Uri.TryCreate(uriString, UriKind.Absolute, out var uri))
                    {
                        Uris.Add(uri);
                    }
                    else
                    {
                        textLogger.LogWarn($"Service Dependency: [{uriString}] is not a valid URI and will be ignored.");
                    }
                }
            }

            // Parse: NEON_SERVICE_DEPENDENCIES_DISABLE_DNS_CHECK

            var disableDnsCheckVar = Environment.GetEnvironmentVariable("NEON_SERVICE_DEPENDENCIES_DISABLE_DNS_CHECK");

            if (!string.IsNullOrEmpty(disableDnsCheckVar))
            {
                if (NeonHelper.TryParseBool(disableDnsCheckVar, out var disableDnsCheck))
                {
                    DisableDnsCheck = disableDnsCheck;
                }
                else
                {
                    textLogger.LogWarn($"Service Dependency: [NEON_SERVICE_DEPENDENCIES_DISABLE_DNS_CHECK={disableDnsCheckVar}] is not a valid and will be ignored.");
                }
            }

            // Parse: NEON_SERVICE_DEPENDENCIES_TIMEOUT_SECONDS

            var timeoutSecondsVar = Environment.GetEnvironmentVariable("NEON_SERVICE_DEPENDENCIES_TIMEOUT_SECONDS");

            if (!string.IsNullOrEmpty(timeoutSecondsVar))
            {
                if (double.TryParse(timeoutSecondsVar, out var timeoutSeconds) && timeoutSeconds >= 0)
                {
                    Timeout = TimeSpan.FromSeconds(timeoutSeconds);
                }
                else
                {
                    textLogger.LogWarn($"Service Dependency: [NEON_SERVICE_DEPENDENCIES_TIMEOUT_SECONDS={timeoutSecondsVar}] is not a valid and will be ignored.");
                }
            }

            // Parse: NEON_SERVICE_DEPENDENCIES_WAIT_SECONDS

            var waitSecondsVar = Environment.GetEnvironmentVariable("NEON_SERVICE_DEPENDENCIES_WAIT_SECONDS");

            if (!string.IsNullOrEmpty(waitSecondsVar))
            {
                if (double.TryParse(waitSecondsVar, out var waitSeconds) && waitSeconds >= 0)
                {
                    Wait = TimeSpan.FromSeconds(waitSeconds);
                }
                else
                {
                    textLogger.LogWarn($"Service Dependency: [NEON_SERVICE_DEPENDENCIES_WAIT_SECONDS={waitSecondsVar}] is not a valid and will be ignored.");
                }
            }
        }
Beispiel #27
0
 /// <summary>
 /// Adds a new Host for Nancy to listen on.
 /// </summary>
 /// <param name="scheme">http or https. Defaults to http.</param>
 /// <param name="domain">The domain to listen on e.g. www.mydomain.com. Defaults to localhost.</param>
 /// <param name="port">The port to listen on. Defaults to 8080.</param>
 public void AddHost(string scheme = "http", string domain = "localhost", int port = 8080)
 {
     Uris.Add(new UriBuilder(scheme, domain, port).Uri);
 }
        /// <summary>
        /// Resumes the log in with the specified provider.
        /// </summary>
        /// <param name="authorizationUri">The user authorization URI.</param>
        private void ResumeLoginWith(Uri authorizationUri)
        {
            // Get the saved OAUTH state
            var stateString = Settings.Instance.GetValue(Settings.OauthToken, "{}");
            var oauthState  = (JsonObject)Json.Json.Read(stateString);

            Settings.Instance.Remove(Settings.OauthToken);

            // Get the query parameters from the URI
            Debug.WriteLine("ResumeLoginWith({0})", authorizationUri);
            var query = authorizationUri.Query;

            if ((query.Length > 0) && (query[0] == '?'))
            {
                query = query.Substring(1);
            }

            // Parse the keys and values
            var pairs     = query.Split('&');
            var arguments = new Dictionary <string, string>();

            foreach (var pair in pairs)
            {
                var split = pair.Split('=');
                arguments.Add(
                    Uri.UnescapeDataString(split[0]),
                    split.Length > 1 ? Uri.UnescapeDataString(split[1]) : string.Empty);
            }

            // If error is present
            if (arguments.ContainsKey("error"))
            {
                // Report error to the user
                App.DisplayAlert(
                    Localization.ErrorDialogTitle,
                    Localization.ErrorCancelled,
                    Localization.DialogDismiss);
                return;
            }

            // Add the result to the saved state
            foreach (var kvp in arguments)
            {
                oauthState.Add(kvp.Key, kvp.Value);
            }

            // Add the device and push token
            var deviceId  = ((App)Application.Current).DeviceId;
            var pushToken = ((App)Application.Current).PushToken;

            oauthState.Add("device", deviceId);
            if (!string.IsNullOrEmpty(pushToken))
            {
                oauthState.Add("push_token", pushToken);
            }

            // Setup error handlers
            // - If session is already opened by another device, request user consent
            var handlers = new Dictionary <System.Net.HttpStatusCode, Action <JsonValue> >
            {
                { System.Net.HttpStatusCode.Conflict, resp => this.RetryLogin(oauthState, resp) }
            };

            // Send request to the server
            this.IsBusy = true;
            WebHelper.SendAsync(
                Uris.GetLoginUri(),
                oauthState.AsHttpContent(),
                this.ProcessLoginResult,
                () => this.IsBusy = false,
                handlers);
        }
        /// <summary>
        /// Logs in the user with the provided credentials.
        /// </summary>
        private void Login()
        {
            // Login the user
            System.Diagnostics.Debug.WriteLine("{0}:{1}", this.UserName, this.Password);

            // If already logging in
            if (this.IsBusy)
            {
                return;
            }

            // Validate that the user name is a valid email
            var user    = this.UserName.Trim().ToLower();
            var isEmail = Regex.IsMatch(
                user,
                @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z",
                RegexOptions.IgnoreCase);

            if (!isEmail)
            {
                App.DisplayAlert(
                    Localization.ErrorDialogTitle,
                    Localization.ErrorInvalidUserLogin,
                    Localization.DialogDismiss);
                return;
            }

            // Validate that the password is present
            if (this.Password.Length <= 2)
            {
                App.DisplayAlert(
                    Localization.ErrorDialogTitle,
                    Localization.ErrorInvalidPassword,
                    Localization.DialogDismiss);
                return;
            }

            // Prepare the data to be send to the server
            var deviceId = ((App)Application.Current).DeviceId;
            var request  = new Json.JsonObject
            {
                { "grant_type", "password" },
                { "username", user },
                { "password", this.Password },
                { "scope", "user submit-report" },
                { "device", deviceId }
            };

            // If push token exists
            var pushToken = ((App)Application.Current).PushToken;

            if (!string.IsNullOrEmpty(pushToken))
            {
                request.Add("push_token", pushToken);
            }

            // Setup error handlers
            // - If session is already opened by another device, request user consent
            var handlers = new Dictionary <System.Net.HttpStatusCode, Action <JsonValue> >
            {
                { System.Net.HttpStatusCode.Conflict, resp => this.RetryLogin(request, resp) }
            };

            // Send request to the server
            this.IsBusy = true;
            WebHelper.SendAsync(
                Uris.GetLoginUri(),
                request.AsHttpContent(),
                this.ProcessLoginResult,
                () => this.IsBusy = false,
                handlers);
        }
Beispiel #30
0
 private IEnumerable <Uri> UrisByStatus(SpiderPageStatus status) =>
 Uris
 .Where(x => x.Value == status)
 .Select(x => x.Key)
 .OrderBy(x => x.ToString());