예제 #1
0
        protected override void Establish_context()
        {
            base.Establish_context();
            contentToDownloadPath = Path.Combine(contentDirectoryName, checkingFileName);

            NetworkSettings.SetupGet(setting => setting.BlockSize).Returns(10000);
            NetworkSettings.SetupGet(setting => setting.ProxyIP).Returns("");
            NetworkSettings.SetupGet(setting => setting.ProxyPort).Returns(1043);
            NetworkSettings.SetupGet(settng => settng.UseProxy).Returns(false);

            string downloadUri = Path.Combine(httpServiceEndpoint, contentDirectoryName, checkingFileName).Replace("\\", "/");

            UriSource.Setup(source => source.Uri).Returns(downloadUri);


            this.createDirectoryIfNotExists();
            this.createFileToDownloadInDirectory();
            webServiceManager           = new WebServiceManager(contentDirectoryName, "");
            saveDownloadedContentStream = new MemoryStream();

            string errorMessage = "";

            if (!webServiceManager.TryStart(httpServiceEndpoint, out errorMessage))
            {
                throw new InvalidOperationException(errorMessage);
            }
            NetworkClient.OnBlockDownloaded += new Action <byte[], int>(NetworkClient_OnBlockDownloaded);
        }
        private OperationResult DetermineLoadResult(Uri uri, UriSource source, AppSettings settings, LoadStatus status, PasswordParameters passwordParams, string currentPassword = default(string))
        {
            var result = OperationResult.Failed;

            if (status == LoadStatus.LoadWithBrowser || status == LoadStatus.Success)
            {
                var isNewConfiguration = source == UriSource.CommandLine || source == UriSource.Reconfiguration;

                Context.Next.Settings = settings;

                if (status == LoadStatus.LoadWithBrowser)
                {
                    result = HandleBrowserResource(uri);
                }
                else if (isNewConfiguration && settings.ConfigurationMode == ConfigurationMode.ConfigureClient)
                {
                    result = HandleClientConfiguration(uri, passwordParams, currentPassword);
                }
                else
                {
                    result = OperationResult.Success;
                }

                HandleStartUrlQuery(uri, source);
            }
            else
            {
                ShowFailureMessage(status, uri);
            }

            return(result);
        }
        private bool TryInitializeSettingsUri(out Uri uri, out UriSource source)
        {
            var isValidUri = false;

            uri    = null;
            source = default(UriSource);

            if (commandLineArgs?.Length > 1)
            {
                isValidUri = Uri.TryCreate(commandLineArgs[1], UriKind.Absolute, out uri);
                source     = UriSource.CommandLine;
                logger.Info($"Found command-line argument for configuration resource: '{uri}', the URI is {(isValidUri ? "valid" : "invalid")}.");
            }

            if (!isValidUri && File.Exists(ProgramDataFilePath))
            {
                isValidUri = Uri.TryCreate(ProgramDataFilePath, UriKind.Absolute, out uri);
                source     = UriSource.ProgramData;
                logger.Info($"Found configuration file in program data directory: '{uri}'.");
            }

            if (!isValidUri && File.Exists(AppDataFilePath))
            {
                isValidUri = Uri.TryCreate(AppDataFilePath, UriKind.Absolute, out uri);
                source     = UriSource.AppData;
                logger.Info($"Found configuration file in app data directory: '{uri}'.");
            }

            return(isValidUri);
        }
예제 #4
0
파일: BitmapImage.cs 프로젝트: Ref12/Grazor
        private void InitializeRenderResource()
        {
            if (isInitialized || renderResource == null || UriSource == null)
            {
                return;
            }

            renderResource.Initialize(UriSource.ResolveAbsoluteUri(BaseUri), SourceRect);
            isInitialized = true;
        }
        private void HandleStartUrlQuery(Uri uri, UriSource source)
        {
            if (source == UriSource.Reconfiguration && Uri.TryCreate(Context.ReconfigurationUrl, UriKind.Absolute, out var reconfigurationUri))
            {
                uri = reconfigurationUri;
            }

            if (uri != default(Uri) && uri.Query.LastIndexOf('?') > 0)
            {
                Context.Next.Settings.Browser.StartUrlQuery = uri.Query.Substring(uri.Query.LastIndexOf('?'));
            }
        }
예제 #6
0
 internal WebServiceUri(string url, string protocol, UriSource source, int serverVersion)
 {
     url      = WebServiceUri.urlPool.Intern(url);
     protocol = WebServiceUri.protocolPool.Intern(protocol);
     this.uri = new Uri(url);
     if (protocol != null)
     {
         this.protocol = protocol;
     }
     this.source        = source;
     this.serverVersion = serverVersion;
 }
        private bool TryInitializeSettingsUri(out Uri uri, out UriSource source)
        {
            var isValidUri = false;

            uri    = null;
            source = default(UriSource);

            if (commandLineArgs?.Length > 1)
            {
                isValidUri = Uri.TryCreate(commandLineArgs[1], UriKind.Absolute, out uri);

                // configuration passed via Custom Protocol
                if (isValidUri)
                {
                    if (uri.Scheme == appConfig.SebUriScheme || uri.Scheme == appConfig.SebUriSchemeSecure)
                    {
                        source = UriSource.Server;
                    }
                    else
                    {
                        if (commandLineArgs?.Length > 2 && !string.IsNullOrEmpty(commandLineArgs[2]) &&
                            commandLineArgs[2].ToLower() == "--debug")
                        {
                            source = UriSource.CommandLine;
                            logger.Info($"Debug mode key found.");
                        }
                        else
                        {
                            isValidUri = false;
                        }
                    }
                }

                logger.Info($"Found command-line argument for configuration resource: '{uri}', the URI is {(isValidUri ? "valid" : "invalid")}.");
            }

            //if (!isValidUri && File.Exists(ProgramDataFilePath))
            //{
            //	isValidUri = Uri.TryCreate(ProgramDataFilePath, UriKind.Absolute, out uri);
            //	source = UriSource.ProgramData;
            //	logger.Info($"Found configuration file in program data directory: '{uri}'.");
            //}

            //if (!isValidUri && File.Exists(AppDataFilePath))
            //{
            //	isValidUri = Uri.TryCreate(AppDataFilePath, UriKind.Absolute, out uri);
            //	source = UriSource.AppData;
            //	logger.Info($"Found configuration file in app data directory: '{uri}'.");
            //}

            return(isValidUri);
        }
예제 #8
0
        private void CreateRenderImageSource()
        {
            if (renderImageSource != null)
            {
                return;
            }

            if (!UriSource.IsNullOrEmpty())
            {
                renderImageSource = ApplicationHost.Current.RenderImageSourceFactory.CreateRenderImageSource(UriSource, SourceRect);
                renderImageSource.StateChanged += (sender, e) => SetRenderImageState(renderImageSource.State);
                SetRenderImageState(renderImageSource.State);
            }
        }
        private OperationResult LoadSettingsForStartup(Uri uri, UriSource source)
        {
            var currentPassword = default(string);
            var passwordParams  = default(PasswordParameters);
            var settings        = default(AppSettings);
            var status          = default(LoadStatus?);

            if (source == UriSource.CommandLine)
            {
                var hasAppDataFile     = File.Exists(AppDataFilePath);
                var hasProgramDataFile = File.Exists(ProgramDataFilePath);

                if (hasProgramDataFile)
                {
                    status = TryLoadSettings(new Uri(ProgramDataFilePath, UriKind.Absolute), UriSource.ProgramData, out _, out settings);
                }
                else if (hasAppDataFile)
                {
                    status = TryLoadSettings(new Uri(AppDataFilePath, UriKind.Absolute), UriSource.AppData, out _, out settings);
                }

                if ((!hasProgramDataFile && !hasAppDataFile) || status == LoadStatus.Success)
                {
                    currentPassword = settings?.Security.AdminPasswordHash;
                    status          = TryLoadSettings(uri, source, out passwordParams, out settings, currentPassword);
                }
            }
            else
            {
                status = TryLoadSettings(uri, source, out passwordParams, out settings);
            }

            if (status.HasValue)
            {
                return(DetermineLoadResult(uri, source, settings, status.Value, passwordParams, currentPassword));
            }
            else
            {
                return(OperationResult.Aborted);
            }
        }
예제 #10
0
        protected LoadStatus?TryLoadSettings(Uri uri, UriSource source, out PasswordParameters passwordParams, out AppSettings settings, string currentPassword = default(string))
        {
            passwordParams = new PasswordParameters {
                Password = string.Empty, IsHash = true
            };

            var status = configuration.TryLoadSettings(uri, out settings, passwordParams);

            if (status == LoadStatus.PasswordNeeded && currentPassword != default(string))
            {
                passwordParams.Password = currentPassword;
                passwordParams.IsHash   = true;

                status = configuration.TryLoadSettings(uri, out settings, passwordParams);
            }

            for (int attempts = 0; attempts < 5 && status == LoadStatus.PasswordNeeded; attempts++)
            {
                var isLocalConfig = source == UriSource.AppData || source == UriSource.ProgramData;
                var purpose       = isLocalConfig ? PasswordRequestPurpose.LocalSettings : PasswordRequestPurpose.Settings;
                var success       = TryGetPassword(purpose, out var password);

                if (success)
                {
                    passwordParams.Password = password;
                    passwordParams.IsHash   = false;
                }
                else
                {
                    return(null);
                }

                status = configuration.TryLoadSettings(uri, out settings, passwordParams);
            }

            return(status);
        }
예제 #11
0
        private void CreateRenderImageSource()
        {
            if (renderImageSource != null || UriSource == null)
            {
                return;
            }

            renderImageSource = ApplicationHost.Current.RenderImageSourceFactory.CreateRenderImageSource(UriSource.ResolveAbsoluteUri(BaseUri), SourceRect);
            renderImageSource.StateChanged += (sender, e) => SetRenderImageState(renderImageSource.State);
            SetRenderImageState(renderImageSource.State);
        }
예제 #12
0
 public static AutoDiscoverRequestOperation CreateForExternal(Application application, ClientContext clientContext, RequestLogger requestLogger, Uri targetUri, AutoDiscoverAuthenticator authenticator, EmailAddress[] emailAddresses, UriSource uriSource, AutodiscoverType autodiscoverType)
 {
     return(new AutoDiscoverRequestByDomain(application, clientContext, requestLogger, authenticator, targetUri, emailAddresses, autodiscoverType));
 }
예제 #13
0
 public static AutoDiscoverRequestOperation CreateForCrossForest(Application application, ClientContext clientContext, RequestLogger requestLogger, Uri targetUri, AutoDiscoverAuthenticator authenticator, EmailAddress[] emailAddresses, UriSource uriSource, AutodiscoverType autodiscoverType)
 {
     return(new AutoDiscoverRequestByDomain(application, clientContext, requestLogger, new AutoDiscoverAuthenticator(ProxyAuthenticator.CreateForSoap(clientContext.MessageId)), targetUri, emailAddresses, autodiscoverType));
 }
예제 #14
0
        internal ProxyWebRequest(Application application, ClientContext clientContext, RequestType requestType, RequestLogger requestLogger, QueryList queryList, TargetServerVersion targetVersion, ProxyAuthenticator proxyAuthenticator, WebServiceUri webServiceUri, UriSource source) : base(application, clientContext, requestLogger, "ProxyWebRequest")
        {
            this.proxyAuthenticator = proxyAuthenticator;
            this.url         = webServiceUri.Uri.OriginalString;
            this.protocol    = webServiceUri.Protocol;
            this.source      = source;
            this.queryList   = queryList;
            this.requestType = requestType;
            this.service     = application.CreateService(webServiceUri, targetVersion, requestType);
            if (proxyAuthenticator.AuthenticatorType == AuthenticatorType.WSSecurity || proxyAuthenticator.AuthenticatorType == AuthenticatorType.OAuth)
            {
                if (webServiceUri.ServerVersion >= Globals.E15Version && clientContext.RequestSchemaVersion >= ExchangeVersionType.Exchange2012)
                {
                    this.service.RequestServerVersionValue = new RequestServerVersion
                    {
                        Version = ExchangeVersionType.Exchange2012
                    };
                }
                else
                {
                    this.service.RequestServerVersionValue = new RequestServerVersion
                    {
                        Version = ExchangeVersionType.Exchange2009
                    };
                }
            }
            else if (targetVersion >= TargetServerVersion.E15 && clientContext.RequestSchemaVersion == ExchangeVersionType.Exchange2012)
            {
                this.service.RequestServerVersionValue = new RequestServerVersion
                {
                    Version = ExchangeVersionType.Exchange2012
                };
            }
            this.service.CookieContainer  = new CookieContainer();
            this.service.requestTypeValue = new RequestTypeHeader();
            if (requestType == RequestType.CrossSite || requestType == RequestType.IntraSite)
            {
                if (Configuration.BypassProxyForCrossSiteRequests)
                {
                    this.service.Proxy = new WebProxy();
                }
                this.service.requestTypeValue.RequestType = ProxyRequestType.CrossSite;
                if (requestType == RequestType.CrossSite)
                {
                    this.failedCounter = PerformanceCounters.CrossSiteCalendarFailuresPerSecond;
                    this.averageProcessingTimeCounter     = PerformanceCounters.AverageCrossSiteFreeBusyRequestProcessingTime;
                    this.averageProcessingTimeCounterBase = PerformanceCounters.AverageCrossSiteFreeBusyRequestProcessingTimeBase;
                    this.requestStatisticsType            = RequestStatisticsType.CrossSiteProxy;
                }
                else
                {
                    this.failedCounter = PerformanceCounters.IntraSiteProxyFreeBusyFailuresPerSecond;
                    this.averageProcessingTimeCounter     = PerformanceCounters.AverageIntraSiteProxyFreeBusyRequestProcessingTime;
                    this.averageProcessingTimeCounterBase = PerformanceCounters.AverageIntraSiteProxyFreeBusyRequestProcessingTimeBase;
                    this.requestStatisticsType            = RequestStatisticsType.IntraSiteProxy;
                }
            }
            else
            {
                bool flag = false;
                if (Configuration.BypassProxyForCrossForestRequests)
                {
                    this.service.Proxy = new WebProxy();
                    flag = true;
                }
                this.service.requestTypeValue.RequestType = ProxyRequestType.CrossForest;
                if (requestType == RequestType.FederatedCrossForest)
                {
                    if (proxyAuthenticator.AuthenticatorType == AuthenticatorType.OAuth)
                    {
                        this.failedCounter = PerformanceCounters.FederatedByOAuthFreeBusyFailuresPerSecond;
                        this.averageProcessingTimeCounter     = PerformanceCounters.AverageFederatedByOAuthFreeBusyRequestProcessingTime;
                        this.averageProcessingTimeCounterBase = PerformanceCounters.AverageFederatedByOAuthFreeBusyRequestProcessingTimeBase;
                        this.requestStatisticsType            = RequestStatisticsType.OAuthProxy;
                        this.service.requestTypeValue         = null;
                    }
                    else
                    {
                        this.failedCounter = PerformanceCounters.FederatedFreeBusyFailuresPerSecond;
                        this.averageProcessingTimeCounter     = PerformanceCounters.AverageFederatedFreeBusyRequestProcessingTime;
                        this.averageProcessingTimeCounterBase = PerformanceCounters.AverageFederatedFreeBusyRequestProcessingTimeBase;
                        this.requestStatisticsType            = RequestStatisticsType.FederatedProxy;
                    }
                    if (!flag)
                    {
                        Server localServer = LocalServerCache.LocalServer;
                        if (localServer != null && localServer.InternetWebProxy != null)
                        {
                            ProxyWebRequest.ProxyWebRequestTracer.TraceDebug <object, Uri>((long)this.GetHashCode(), "{0}: Using custom InternetWebProxy {1}", TraceContext.Get(), localServer.InternetWebProxy);
                            this.service.Proxy = new WebProxy(localServer.InternetWebProxy);
                        }
                    }
                }
                else
                {
                    this.failedCounter = PerformanceCounters.CrossForestCalendarFailuresPerSecond;
                    this.averageProcessingTimeCounter     = PerformanceCounters.AverageCrossForestFreeBusyRequestProcessingTime;
                    this.averageProcessingTimeCounterBase = PerformanceCounters.AverageCrossForestFreeBusyRequestProcessingTimeBase;
                    this.requestStatisticsType            = RequestStatisticsType.CrossForestProxy;
                }
            }
            if (!Configuration.DisableGzipForProxyRequests)
            {
                this.service.EnableDecompression = true;
            }
            string address = this.queryList[0].Email.Address;

            ProxyWebRequest.ProxyWebRequestTracer.TraceDebug <object, string, WebServiceUri>((long)this.GetHashCode(), "{0}: Adding Anchor Mailbox Header {1} to the request to {2}.", TraceContext.Get(), address, webServiceUri);
            this.service.HttpHeaders.Add("X-AnchorMailbox", address);
            if (!string.IsNullOrEmpty(base.ClientContext.RequestId))
            {
                this.service.HttpHeaders.Add("client-request-id", base.ClientContext.RequestId);
            }
        }
예제 #15
0
 private AutoDiscoverRequestXmlByUser(Application application, ClientContext clientContext, RequestLogger requestLogger, Uri targetUri, AutoDiscoverAuthenticator authenticator, EmailAddress[] emailAddresses, UriSource uriSource, AutodiscoverType autodiscoverType) : base(application, clientContext, requestLogger, targetUri, authenticator, emailAddresses, autodiscoverType)
 {
     this.uriSource = uriSource;
 }
예제 #16
0
 private AsyncRequestWithQueryList CreateRequest(QueryList queryList, ProxyAuthenticator proxyAuthenticator, WebServiceUri webServiceUri, UriSource source)
 {
     return(new GetFolderAndProxyRequest(base.Application, (InternalClientContext)base.ClientContext, RequestType.CrossForest, base.RequestLogger, queryList, TargetServerVersion.Unknown, proxyAuthenticator, webServiceUri));
 }
예제 #17
0
 internal AutoDiscoverRequest(Application application, ClientContext clientContext, RequestLogger requestLogger, Uri targetUri, EmailAddress emailAddress, ICredentials credentialsForDiscovery, UriSource uriSource) : base(application, clientContext, requestLogger, "AutoDiscoverRequest")
 {
     this.uriSource               = uriSource;
     this.emailAddress            = emailAddress;
     this.credentialsForDiscovery = credentialsForDiscovery;
     this.targetUri               = targetUri;
     CertificateValidationManager.RegisterCallback(Globals.CertificateValidationComponentId, new RemoteCertificateValidationCallback(CertificateErrorHandler.CertValidationCallback));
 }
 private AsyncRequest CreateRequest(QueryList queryList, ProxyAuthenticator proxyAuthenticator, WebServiceUri webServiceUri, UriSource source)
 {
     return(new ProxyWebRequest(base.Application, base.ClientContext, RequestType.FederatedCrossForest, base.RequestLogger, queryList, TargetServerVersion.Unknown, proxyAuthenticator, webServiceUri, source));
 }
예제 #19
0
        private void OnUriSourceChanged()
        {
            if (Parent == null)
            {
                // If the parent is not present we can wait for OnAttachedToWindow to call again.
                return;
            }

            ResetImage();

            if (!UriSource.HasValue())
            {
                return;
            }
            var newUri = new Uri(UriSource);

            if (newUri.Scheme == "resource" ||
                newUri.IsFile ||
                newUri.IsLocalResource())
            {
                SetImageResource(GetResourceId(newUri.PathAndQuery.TrimStart(new[] { '/' })));
            }
            else if (UriSource.StartsWith("res:///", StringComparison.OrdinalIgnoreCase))
            {
                int resourceId;

                if (int.TryParse(UriSource.Replace("res:///", ""), out resourceId))
                {
                    SetImageResource(resourceId);
                }
                else
                {
                    this.Log().WarnFormat("Failed to load asset resource [{0}]", UriSource);
                }
            }
            else if (UriSource.StartsWith("file://", StringComparison.OrdinalIgnoreCase) || newUri.IsAppData())
            {
                if (_targetHeight <= 0 || _targetWidth <= 0)
                {
                    _sourceUpdateRequired = true;
                    return;
                }

                var filePath = newUri.IsAppData() ?
                               AppDataUriEvaluator.ToPath(newUri) :
                               UriSource.TrimStart("file://", StringComparison.OrdinalIgnoreCase);

                var options = new BitmapFactory.Options();
                options.InJustDecodeBounds = true;
                BitmapFactory.DecodeFile(filePath, options).SafeDispose();
                var sampleSize = CalculateInSampleSize(options, _targetWidth, _targetHeight);

                options.InJustDecodeBounds = false;
#pragma warning disable CS0618 // Type or member is obsolete
                options.InPurgeable = true;
#pragma warning restore CS0618 // Type or member is obsolete
                options.InSampleSize = sampleSize;

                var bitmap = BitmapFactory.DecodeFile(filePath, options);

                if (_currentBitmap != bitmap)
                {
                    SetImageBitmap(bitmap);
                }
            }
            else
            {
                _download.Disposable = CoreDispatcher.Main
                                       .RunAsync(
                    CoreDispatcherPriority.Normal,
                    async(ct) =>
                {
                    var localUri = UriSource;

                    using (var b = await DownloadImage(localUri, _targetWidth, _targetHeight, ct))
                    {
                        if (!ct.IsCancellationRequested && b != null)
                        {
                            if (_currentBitmap != b)
                            {
                                SetImageBitmap(b);
                            }

                            if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                            {
                                this.Log().DebugFormat("Bitmap set {0}", localUri);
                            }

                            if (_isInteractive)
                            {
                                _saveScale = 1f;
                                OnDrawableChanged();
                            }
                        }
                        else if (b == null && ImageLoader == null)
                        {
                            // The bitmap may be null if the image loader has already set the image from

                            this.Log().Warn("Bitmap is null after image download");
                        }
                    }
                }
                    );
            }
        }
        private void OnUriSourceChanged()
        {
            ResetImage();

            if (!UriSource.HasValue())
            {
                return;
            }
            var newUri = new Uri(UriSource);

            if (newUri.Scheme == "resource")
            {
                Resource = GetResourceId(newUri.PathAndQuery.TrimStart('/'));
            }
            else if (UriSource.StartsWith("res:///", StringComparison.OrdinalIgnoreCase))
            {
                int resourceId;

                if (int.TryParse(UriSource.Replace("res:///", ""), out resourceId))
                {
                    Resource = resourceId;
                }
                else
                {
                    if (this.Log().IsEnabled(LogLevel.Warning))
                    {
                        this.Log().WarnFormat("Failed to load asset resource [{0}]", UriSource);
                    }
                }
            }
            else if (UriSource.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
            {
                var filePath = UriSource.TrimStart("file://", StringComparison.OrdinalIgnoreCase);

                var options = new BitmapFactory.Options();
                options.InJustDecodeBounds = true;
                BitmapFactory.DecodeFile(filePath, options).SafeDispose();
                var sampleSize = CalculateInSampleSize(options, TargetWidth, TargetHeight);

                options.InJustDecodeBounds = false;
                options.InPurgeable        = true;
                options.InSampleSize       = sampleSize;

                CurrentBitmap = BitmapFactory.DecodeFile(filePath, options);
            }
            else
            {
#if !IS_UNO
                _download.Disposable = new CoreDispatcherScheduler(CoreDispatcher.Main, CoreDispatcherPriority.Normal)
                                       .ScheduleAsync((object)null, async(s, state, ct) =>
                {
                    var localUri = UriSource;

                    var b = await DownloadImage(localUri, TargetWidth, TargetHeight, ct);
                    if (!ct.IsCancellationRequested && b != null)
                    {
                        CurrentBitmap = b;
                        ImageDownloaded();

                        if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                        {
                            this.Log().DebugFormat("Bitmap set {0}", localUri);
                        }
                    }
                    else if (b == null && ImageLoader == null)
                    {
                        // The bitmap may be null if the image loader has already set the image from

                        if (this.Log().IsEnabled(LogLevel.Warning))
                        {
                            this.Log().Warn("Bitmap is null after image download");
                        }
                    }
                }
                                                      );
#endif
            }
        }