Exemplo n.º 1
0
        public OpenWithForm()
        {
            InitializeComponent();

            notifyIcon.Icon = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Asterisk, true, Main.SystemResourcePath);

            searchBox.BackColor = Main.Colors.Control;
            searchBox.ForeColor = Main.Colors.ControlText;
            searchBox.DrawSearchSymbol(Main.Colors.ControlText);

            startBtn.Split(Main.Colors.ButtonText);
            foreach (var btn in new[] { startBtn, settingsBtn })
            {
                btn.BackColor = Main.Colors.Button;
                btn.ForeColor = Main.Colors.ButtonText;
                btn.FlatAppearance.MouseDownBackColor = Main.Colors.Button;
                btn.FlatAppearance.MouseOverBackColor = Main.Colors.ButtonHover;
            }

            appMenu.EnableAnimation(ContextMenuStripEx.Animations.SlideVerPositive, 100);
            appMenu.SetFixedSingle();
            appMenuItem2.Image = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Uac, Main.SystemResourcePath)?.ToBitmap();
            appMenuItem3.Image = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Directory, Main.SystemResourcePath)?.ToBitmap();
            appMenuItem7.Image = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.RecycleBinEmpty, Main.SystemResourcePath)?.ToBitmap();

            if (!searchBox.Focused)
            {
                searchBox.Select();
            }
        }
            //加载Multiple Sprite
            public Asset <T> LoadAsset <T>([NotNull] string asset_name, int multple_index) where T : UObject
            {
#if UI_RESOURCE
                GameObject asset = ResourcesEx.Load <GameObject>(texturePath + asset_name);
                if (asset == null)
                {
                    Develop.LogError("Load Error!Cant find sprite:" + asset_name);
                    return(null);
                }

                SpritePrefab sp = asset.GetComponent <SpritePrefab>();
                if (sp == null)
                {
                    Develop.LogError("Sprite Component Missing:" + asset_name);
                    return(null);
                }

                T sprite = (T)sp.GetSprite(asset_name, -1);
                if (sprite == null)
                {
                    Develop.LogError("Load Error!Cant find sprite:" + asset_name);
                    return(null);
                }
                return(new Asset_Real <T>(this, sprite));
#else
#if UNITY_EDITOR
                if (!UseBundleInEditor)
                {
                    var data_object = Manifest.LoadAssetDataBase <T>(this.BundleName, asset_name, multple_index);
                    return(new Asset_Real <T>(this, data_object));
                }
#endif
                if (this.BundleObject == null)
                {
                    Develop.LogErrorF("Bundle is not loaded {0}.{1}, Index = {2}", this.BundleName, asset_name, multple_index);
                    return(null);
                }

                if (!this.BundleObject.Contains(asset_name))
                {
                    Develop.LogErrorF("Asset Multiple Sprite CantFind {0}.{1}, Index = {2}", this.BundleName, asset_name, multple_index);
                    return(null);
                }

                var asset_object = this.BundleObject.LoadAssetWithSubAssets <T>(asset_name);
                if (null == asset_object)
                {
                    Develop.LogErrorF("Asset Multiple Sprite CantFind {0}.{1}, Index = {2}", this.BundleName, asset_name, multple_index);
                    return(null);
                }
                if (asset_object.Length > multple_index)
                {
                    return(new Asset_Real <T>(this, asset_object[multple_index]));
                }

                return(null);
#endif
            }
Exemplo n.º 3
0
    // Use this for initialization
    void Start()
    {
        var chair = ResourcesEx.LoadFromUri("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");

        //var box = Instantiate(GameObject.Find("Cube00"), this.transform);
        //box.transform.position += new Vector3(2, 2, 2);
        //Debug.Log("Test");
        //GameObject.Destroy(box);
    }
            public Asset LoadAssetAsync([NotNull] string asset_name)
            {
#if UI_RESOURCE
                GameObject asset = ResourcesEx.Load <GameObject>(texturePath + asset_name);
                if (asset == null)
                {
                    Develop.LogError("Load Error!Cant find sprite:" + asset_name);
                    return(null);
                }

                SpritePrefab sp = asset.GetComponent <SpritePrefab>();
                if (sp == null)
                {
                    Develop.LogError("Sprite Component Missing:" + asset_name);
                    return(null);
                }

                Sprite sprite = (Sprite)sp.GetSprite(1);
                if (sprite == null)
                {
                    Develop.LogError("Load Error!Cant find sprite:" + asset_name);
                    return(null);
                }

                return(new Asset_Real(this, sprite));
#else
#if UNITY_EDITOR
                if (!UseBundleInEditor)
                {
                    var data_object = Manifest.LoadAssetDataBase <UObject>(this.BundleName, asset_name);
                    return(new Asset_Real(this, data_object));
                }
#endif
                if (this.BundleObject == null)
                {
                    Develop.LogErrorF("Bundle is not loaded {0}.{1}", this.BundleName, asset_name);
                    return(null);
                }

                var asset_request = this.BundleObject.LoadAssetAsync(asset_name);
                if (null == asset_request)
                {
                    Develop.LogErrorF("Asset LoadFail {0}.{1}", this.BundleName, asset_name);
                    return(null);
                }
                return(new Asset_Real(this, asset_request));
#endif
            }
Exemplo n.º 5
0
        private void AboutForm_Load(object sender, EventArgs e)
        {
            FormEx.Dockable(this);

            Icon = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.HelpShield, Main.SystemResourcePath);

            Lang.SetControlLang(this);
            Text = Lang.GetText(Name);

            Main.SetFont(this);

            AddFileInfoLabels();

            logoPanel.BackColor = Main.Colors.Base;

            updateBtnPanel.Width = TextRenderer.MeasureText(updateBtn.Text, updateBtn.Font).Width + 32;
            updateBtn.Image      = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Network, Main.SystemResourcePath)?.ToBitmap();
            updateBtn.ForeColor  = Main.Colors.ButtonText;
            updateBtn.BackColor  = Main.Colors.Button;
            updateBtn.FlatAppearance.MouseDownBackColor = Main.Colors.Button;
            updateBtn.FlatAppearance.MouseOverBackColor = Main.Colors.ButtonHover;

            _progressCircle = new ProgressCircle
            {
                Anchor        = updateBtnPanel.Anchor,
                BackColor     = Color.Transparent,
                ForeColor     = mainPanel.BackColor,
                InnerRadius   = 7,
                Location      = new Point(updateBtnPanel.Right + 3, updateBtnPanel.Top + 1),
                OuterRadius   = 9,
                RotationSpeed = 80,
                Size          = new Size(updateBtnPanel.Height, updateBtnPanel.Height),
                Thickness     = 3,
                Visible       = false
            };
            mainPanel.Controls.Add(_progressCircle);

            aboutInfoLabel.ActiveLinkColor = Main.Colors.Base;
            aboutInfoLabel.BorderStyle     = BorderStyle.None;
            aboutInfoLabel.Text            = string.Format(Lang.GetText(aboutInfoLabel), "Si13n7 Developments", Lang.GetText(aboutInfoLabel.Name + "LinkLabel1"), Lang.GetText(aboutInfoLabel.Name + "LinkLabel2"));
            aboutInfoLabel.Links.Clear();
            aboutInfoLabel.LinkText("Si13n7 Developments", "http://www.si13n7.com");
            aboutInfoLabel.LinkText(Lang.GetText(aboutInfoLabel.Name + "LinkLabel1"), "http://paypal.si13n7.com");
            aboutInfoLabel.LinkText(Lang.GetText(aboutInfoLabel.Name + "LinkLabel2"), "https://support.si13n7.com");

            copyrightLabel.Text = string.Format(copyrightLabel.Text, DateTime.Now.Year);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Validates the wellformedness of a list of uri strings.
        /// </summary>
        /// <param name="value">The value.</param>
        private void ValidateUris(IEnumerable <string> value)
        {
            if (value == null)
            {
                return;
            }

            foreach (string uri in value)
            {
                if (Uri.IsWellFormedUriString(uri, UriKind.Absolute))
                {
                    continue;
                }

                throw new FormatException(ResourcesEx.InvalidWellformedAbsoluteUriStringFormat(uri));
            }
        }
        /// <summary>
        /// Refreshes the information retrieved from the directory containing metadata files.
        /// </summary>
        internal void Initialize()
        {
            if (MetadataLocation == null)
            {
                return;
            }

            if (!Directory.Exists(MetadataLocation))
            {
                throw new DirectoryNotFoundException(ResourcesEx.MetadataLocationNotFoundFormat(MetadataLocation));
            }

            string[] files = Directory.GetFiles(MetadataLocation);
            foreach (string file in files)
            {
                HandleCreateIdp(file);
            }

            InitializeFileSystemWatcher();
        }
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.SamlContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public override void ProcessRequest(SamlHttpContext context)
        {
            string encoding = context.Request.QueryString["encoding"];

            try
            {
                if (!string.IsNullOrEmpty(encoding))
                {
                    context.Response.ContentEncoding = Encoding.GetEncoding(encoding);
                }
            }
            catch (ArgumentException)
            {
                HandleError(context, ResourcesEx.UnknownEncodingFormat(encoding));
                return;
            }

            bool sign = true;

            try
            {
                string param = context.Request.QueryString["sign"];
                if (!string.IsNullOrEmpty(param))
                {
                    sign = Convert.ToBoolean(param);
                }
            } catch (FormatException)
            {
                HandleError(context, Resources.GenericError);
                return;
            }

            context.Response.ContentType = Saml20Constants.METADATA_MIMETYPE;
            context.Response.AddHeader("Content-Disposition", "attachment; filename=\"metadata.xml\"");

            CreateMetadataDocument(context, sign);

            context.Response.End();
        }
Exemplo n.º 9
0
        internal static Icon GetSystemIcon(ResourcesEx.IconIndex index, bool large = false)
        {
            Icon icon;

            if (Icons.Any())
            {
                icon = Icons.FirstOrDefault(x => x.Item1.Equals(index) && x.Item2.Equals(large))?.Item3;
                if (icon != default(Icon))
                {
                    goto Return;
                }
            }
            icon = ResourcesEx.GetSystemIcon(index, large);
            if (icon == default(Icon))
            {
                goto Return;
            }
            var tuple = new Tuple <ResourcesEx.IconIndex, bool, Icon>(index, large, icon);

            Icons.Add(tuple);
Return:
            return(icon);
        }
Exemplo n.º 10
0
        private void SettingsForm_Load(object sender, EventArgs e)
        {
            FormEx.Dockable(this);

            if (Main.ScreenDpi > 96)
            {
                Font = SystemFonts.CaptionFont;
            }

            Icon = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.SystemControl, Main.SystemResourcePath);

            foreach (TabPage tab in tabCtrl.TabPages)
            {
                tab.BackColor = Main.Colors.BaseDark;
            }

            locationBtn.BackgroundImage = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Directory, Main.SystemResourcePath)?.ToBitmap();
            fileTypesMenu.EnableAnimation();
            fileTypesMenu.SetFixedSingle();
            associateBtn.Image = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Uac, Main.SystemResourcePath)?.ToBitmap();
            try
            {
                restoreFileTypesBtn.Image = new Bitmap(28, 16);
                using (var g = Graphics.FromImage(restoreFileTypesBtn.Image))
                {
                    g.DrawImage(ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Uac, Main.SystemResourcePath).ToBitmap(), 0, 0);
                    g.DrawImage(ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Undo, Main.SystemResourcePath).ToBitmap(), 12, 0);
                }
            }
            catch
            {
                restoreFileTypesBtn.Image      = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Uac, Main.SystemResourcePath)?.ToBitmap();
                restoreFileTypesBtn.ImageAlign = ContentAlignment.MiddleLeft;
                restoreFileTypesBtn.Text       = @"<=";
                if (restoreFileTypesBtn.Image != null)
                {
                    restoreFileTypesBtn.TextAlign = ContentAlignment.MiddleRight;
                }
            }

            previewBg.BackgroundImage       = Main.BackgroundImage.Redraw((int)Math.Round(Main.BackgroundImage.Width * .65f) + 1, (int)Math.Round(Main.BackgroundImage.Height * .65f) + 1);
            previewBg.BackgroundImageLayout = Main.BackgroundImageLayout;
            previewLogoBox.BackgroundImage  = Resources.PortableApps_Logo_gray.Redraw(previewLogoBox.Height, previewLogoBox.Height);
            var exeIco = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.ExeFile, Main.SystemResourcePath);

            if (exeIco != null)
            {
                previewImgList.Images.Add(exeIco.ToBitmap());
                previewImgList.Images.Add(exeIco.ToBitmap());
            }

            foreach (var btn in new[] { saveBtn, exitBtn })
            {
                btn.BackColor = Main.Colors.Button;
                btn.ForeColor = Main.Colors.ButtonText;
                btn.FlatAppearance.MouseDownBackColor = Main.Colors.Button;
                btn.FlatAppearance.MouseOverBackColor = Main.Colors.ButtonHover;
            }
            var strAppNames = Main.AppsInfo.Select(x => x.LongName).ToArray();
            var objAppNames = new object[strAppNames.Length];

            Array.Copy(strAppNames, objAppNames, objAppNames.Length);
            appsBox.Items.AddRange(objAppNames);

            appsBox.SelectedItem = _selectedItem;
            if (appsBox.SelectedIndex < 0)
            {
                appsBox.SelectedIndex = 0;
            }

            fileTypes.MaxLength  = short.MaxValue;
            addToShellBtn.Image  = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Uac, Main.SystemResourcePath)?.ToBitmap();
            rmFromShellBtn.Image = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Uac, Main.SystemResourcePath)?.ToBitmap();

            LoadSettings();
        }
Exemplo n.º 11
0
        private void HandleRequest(SamlHttpContext context)
        {
            Trace.TraceMethodCalled(GetType(), "HandleRequest()");

            //Fetch config object
            SAML20FederationConfig config = SAML20FederationConfig.GetConfig();

            LogoutRequest logoutRequest = null;
            IDPEndPoint   endpoint      = null;
            string        message       = string.Empty;

            //Build the response object
            var response = new Saml20LogoutResponse();

            response.Issuer     = config.ServiceProvider.ID;
            response.StatusCode = Saml20Constants.StatusCodes.Success; // Default success. Is overwritten if something fails.

            if (context.Request.RequestType == "GET")                  // HTTP Redirect binding
            {
                HttpRedirectBindingParser parser = new HttpRedirectBindingParser(context.Request.Url);
                AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST,
                                      string.Format("Binding: redirect, Signature algorithm: {0}  Signature:  {1}, Message: {2}", parser.SignatureAlgorithm, parser.Signature, parser.Message));

                if (!parser.IsSigned)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Signature not present, msg: " + parser.Message);
                    response.StatusCode = Saml20Constants.StatusCodes.RequestDenied;
                }

                logoutRequest = parser.LogoutRequest;
                endpoint      = config.FindEndPoint(logoutRequest.Issuer.Value);

                if (endpoint.metadata == null)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Cannot find metadata for IdP: " + logoutRequest.Issuer.Value);
                    // Not able to return a response as we do not know the IdP.
                    HandleError(context, "Cannot find metadata for IdP " + logoutRequest.Issuer.Value);
                    return;
                }

                Saml20MetadataDocument metadata = endpoint.metadata;

                if (!parser.VerifySignature(metadata.GetKeys(KeyTypes.signing)))
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Request has been denied. Invalid signature redirect-binding, msg: " + parser.Message);
                    response.StatusCode = Saml20Constants.StatusCodes.RequestDenied;
                }

                message = parser.Message;
            }
            else if (context.Request.RequestType == "POST") // HTTP Post binding
            {
                HttpPostBindingParser parser = new HttpPostBindingParser(context);
                AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST,
                                      "Binding: POST, Message: " + parser.Message);

                if (!parser.IsSigned())
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Signature not present, msg: " + parser.Message);
                    response.StatusCode = Saml20Constants.StatusCodes.RequestDenied;
                }

                logoutRequest = parser.LogoutRequest;
                endpoint      = config.FindEndPoint(logoutRequest.Issuer.Value);
                if (endpoint.metadata == null)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Cannot find metadata for IdP");
                    // Not able to return a response as we do not know the IdP.
                    HandleError(context, "Cannot find metadata for IdP " + logoutRequest.Issuer.Value);
                    return;
                }

                Saml20MetadataDocument metadata = endpoint.metadata;

                // handle a logout-request
                if (!parser.CheckSignature(metadata.GetKeys(KeyTypes.signing)))
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Request has been denied. Invalid signature post-binding, msg: " + parser.Message);
                    response.StatusCode = Saml20Constants.StatusCodes.RequestDenied;
                }

                message = parser.Message;
            }
            else
            {
                //Error: We don't support HEAD, PUT, CONNECT, TRACE, DELETE and OPTIONS
                // Not able to return a response as we do not understand the request.
                HandleError(context, ResourcesEx.UnsupportedRequestTypeFormat(context.Request.RequestType));
            }

            AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, message);

            // Check that idp in session and request matches.
            string idpRequest = logoutRequest.Issuer.Value;

            // SessionFactory.SessionContext.Current.New is never the first call to Current due to the logic in Application_AuthenticateRequest() ... Saml20Identity.IsInitialized()
            // Hence we need to check on Saml20Identity.IsInitialized() instead of using SessionFactory.SessionContext.Current.New.
            bool isOioSamlSessionActive = Saml20Identity.IsInitialized();

            if (isOioSamlSessionActive)
            {
                object idpId = Saml20PrincipalCache.GetSaml20AssertionLite().Issuer;

                if (idpId != null && idpId.ToString() != idpRequest)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, ResourcesEx.IdPMismatchBetweenRequestAndSessionFormat(idpId, idpRequest), message);
                    response.StatusCode = Saml20Constants.StatusCodes.RequestDenied;
                }
            }
            else
            {
                // All other status codes than Success results in the IdP throwing an error page. Therefore we return default Success even if we do not have a session.
                AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Session does not exist. Continues the redirect logout procedure with status code success." + idpRequest, message);
            }

            //  Only logout if request is valid and we are working on an existing Session.
            if (Saml20Constants.StatusCodes.Success == response.StatusCode && isOioSamlSessionActive)
            {
                // Execute all actions that the service provider has configured
                DoLogout(context, true);
            }

            // Update the response object with informations that first is available when request has been parsed.
            IDPEndPointElement destination = DetermineEndpointConfiguration(SAMLBinding.REDIRECT, endpoint.SLOEndpoint, endpoint.metadata.SLOEndpoints());

            response.Destination  = destination.Url;
            response.InResponseTo = logoutRequest.ID;

            //Respond using redirect binding
            if (destination.Binding == SAMLBinding.REDIRECT)
            {
                HttpRedirectBindingBuilder builder = new HttpRedirectBindingBuilder();
                builder.RelayState = context.Request.Params["RelayState"];
                builder.Response   = response.GetXml().OuterXml;
                builder.signingKey = FederationConfig.GetConfig().SigningCertificate.GetCertificate().PrivateKey;
                string s = destination.Url + "?" + builder.ToQuery();
                context.Response.Redirect(s, true);
                return;
            }

            //Respond using post binding
            if (destination.Binding == SAMLBinding.POST)
            {
                throw new NotImplementedException("HttpPostBindingBuilder not ported");
                //HttpPostBindingBuilder builder = new HttpPostBindingBuilder(destination);
                //builder.Action = SAMLAction.SAMLResponse;
                //XmlDocument responseDocument = response.GetXml();
                //XmlSignatureUtils.SignDocument(responseDocument, response.ID);
                //builder.Response = responseDocument.OuterXml;
                //builder.RelayState = context.Request.Params["RelayState"];
                //builder.GetPage().ProcessRequest(context);
                //return;
            }
        }
Exemplo n.º 12
0
        private void HandleResponse(SamlHttpContext context)
        {
            Trace.TraceMethodCalled(GetType(), "HandleResponse()");


            string message = string.Empty;

            if (context.Request.RequestType == "GET")
            {
                HttpRedirectBindingParser parser   = new HttpRedirectBindingParser(context.Request.Url);
                LogoutResponse            response = Serialization.DeserializeFromXmlString <LogoutResponse>(parser.Message);

                AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                      string.Format("Binding: redirect, Signature algorithm: {0}  Signature:  {1}, Message: {2}", parser.SignatureAlgorithm, parser.Signature, parser.Message));

                IDPEndPoint idp = RetrieveIDPConfiguration(response.Issuer.Value);

                AuditLogging.IdpId       = idp.Id;
                AuditLogging.AssertionId = response.ID;

                if (idp.metadata == null)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("No IDP metadata, unknown IDP, response: {0}", parser.Message));
                    HandleError(context, Resources.UnknownIDP);
                    return;
                }

                if (!parser.VerifySignature(idp.metadata.Keys))
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("Invalid signature in redirect-binding, response: {0}", parser.Message));
                    HandleError(context, Resources.SignatureInvalid);
                    return;
                }

                message = parser.Message;
            }
            else if (context.Request.RequestType == "POST")
            {
                HttpPostBindingParser parser = new HttpPostBindingParser(context);
                AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                      "Binding: POST, Message: " + parser.Message);


                LogoutResponse response = Serialization.DeserializeFromXmlString <LogoutResponse>(parser.Message);

                IDPEndPoint idp = RetrieveIDPConfiguration(response.Issuer.Value);

                if (idp.metadata == null)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("No IDP metadata, unknown IDP, response: {0}", parser.Message));
                    HandleError(context, Resources.UnknownIDP);
                    return;
                }

                if (!parser.IsSigned())
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("Signature not present, response: {0}", parser.Message));
                    HandleError(context, Resources.SignatureNotPresent);
                }

                // signature on final message in logout
                if (!parser.CheckSignature(idp.metadata.Keys))
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("Invalid signature in post-binding, response: {0}", parser.Message));
                    HandleError(context, Resources.SignatureInvalid);
                }

                message = parser.Message;
            }
            else
            {
                AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                      string.Format("Unsupported request type format, type: {0}", context.Request.RequestType));
                HandleError(context, ResourcesEx.UnsupportedRequestTypeFormat(context.Request.RequestType));
            }

            XmlDocument doc = new XmlDocument();

            doc.XmlResolver        = null;
            doc.PreserveWhitespace = true;
            doc.LoadXml(message);

            XmlElement statElem =
                (XmlElement)doc.GetElementsByTagName(Status.ELEMENT_NAME, Saml20Constants.PROTOCOL)[0];

            Status status = Serialization.DeserializeFromXmlString <Status>(statElem.OuterXml);

            if (status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
            {
                AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                      string.Format("Unexpected status code: {0}, msg: {1}", status.StatusCode.Value, message));
                HandleError(context, status);
                return;
            }

            AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                  "Assertion validated succesfully");

            //Log the user out locally
            DoLogout(context);
        }
Exemplo n.º 13
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            var iniFile = Path.ChangeExtension(PathEx.LocalPath, ".ini");

            if (!File.Exists(iniFile))
            {
                Ini.SetFile(iniFile);
                Ini.Write("Settings", "Language", "English");
                Ini.Write("Settings", "Architecture", Environment.Is64BitProcess ? "64 bit" : "32 bit");
                Ini.Write("Settings", "DoNotAskAgain", false);
            }
            else
            {
                Ini.SetFile(iniFile);
            }
            if (!Ini.Read("Settings", "DoNotAskAgain", false))
            {
                Form langSelection = new LangSelectionForm();
                if (langSelection.ShowDialog() != DialogResult.OK)
                {
                    MessageBoxEx.Show(Resources.Msg_Hint_03, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Application.Exit();
                    return;
                }
            }
            var    lang   = $"{Ini.Read<string>("Settings", "Language", "English")} ({Ini.Read<string>("Settings", "Architecture", Environment.Is64BitProcess ? "64 bit" : "32 bit")})";
            var    source = NetEx.Transfer.DownloadString(Resources.RegexUrl);
            string updUrl = null;

            try
            {
                foreach (Match match in Regex.Matches(source, Resources.RegexLinePattern, RegexOptions.Singleline))
                {
                    var mLine = match.Groups[1].ToString();
                    var mLang = Regex.Match(mLine, Resources.RegexLanguagePattern, RegexOptions.Singleline).Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mLang) || !mLang.EqualsEx(lang))
                    {
                        continue;
                    }
                    var mVer = Regex.Match(mLine, Resources.RegexVersionPattern, RegexOptions.Singleline).Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mVer) || mVer.ContainsEx("trial", "free", "beta"))
                    {
                        continue;
                    }
                    var mName = Regex.Match(mLine, Resources.RegexFileNamePattern, RegexOptions.Singleline).Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mName))
                    {
                        continue;
                    }
                    updUrl = string.Format(Resources.UpdateUrl, mName);
                    if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                    {
                        updUrl = null;
                        continue;
                    }
                    break;
                }
                if (string.IsNullOrEmpty(updUrl))
                {
                    throw new ArgumentNullException(nameof(updUrl));
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_02, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);

            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "7z.zip");
                        ResourcesEx.Extract(Resources._7z, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 14
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl = null;

            try
            {
                var regexUrl = Resources.RegexUrl;
                if (!Ini.ReadDirect("Settings", "BetaUpdates").EqualsEx("1", "True"))
                {
                    regexUrl += "/latest";
                }
                var source = NetEx.Transfer.DownloadString(regexUrl);
                if (string.IsNullOrWhiteSpace(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                source = TextEx.FormatNewLine(source);
#if x86
                const string arch = "32";
#else
                const string arch = "64";
#endif
                source = source.SplitNewLine().Where(x => x.ContainsEx(Resources.SearchPrefix) && x.ContainsEx(string.Format(Resources.SearchSuffix, arch))).Take(1).Join();
                foreach (Match match in Regex.Matches(source, Resources.RegexPattern, RegexOptions.Singleline))
                {
                    var mPath = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mPath) || mPath.Count(c => c == '/') != 1)
                    {
                        continue;
                    }
                    updUrl = string.Format(Resources.UpdateUrl, mPath);
                    break;
                }
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);
            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "7z.zip");
                        ResourcesEx.Extract(Resources._7z, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 15
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl = null;

            try
            {
                var source = NetEx.Transfer.DownloadString(Resources.RegexFirstUrl);
                if (string.IsNullOrWhiteSpace(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(Resources.RegexSecBtnMatch)).Take(1).Join();
                foreach (Match match in Regex.Matches(source, Resources.RegexSecUrlPattern, RegexOptions.Singleline))
                {
                    var mUrl = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mUrl))
                    {
                        continue;
                    }
                    source = NetEx.Transfer.DownloadString(mUrl);
                    if (string.IsNullOrWhiteSpace(source))
                    {
                        throw new ArgumentNullException(nameof(source));
                    }
                    source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(Resources.RegexThirdBtnMatch) || !Resources.RegexThirdExtMatch.SplitNewLine().Any(y => x.ContainsEx(y))).Take(1).Join();
                    foreach (Match match2 in Regex.Matches(source, Resources.RegexThirdUrlPattern, RegexOptions.Singleline))
                    {
                        mUrl = match2.Groups[1].ToString();
                        if (string.IsNullOrWhiteSpace(mUrl))
                        {
                            continue;
                        }
                        if (mUrl.ContainsEx("/show/"))
                        {
                            mUrl = mUrl.Replace("/show/", "/get/");
                        }
                        updUrl = mUrl;
                        break;
                    }
                    break;
                }
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);

            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "iu.zip");
                        ResourcesEx.Extract(Resources.iu, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 16
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl = null;

            try
            {
                var source = NetEx.Transfer.DownloadString(Resources.RegexUrl);
                if (string.IsNullOrWhiteSpace(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                var paths = new Dictionary <Version, string>();
                foreach (Match match in Regex.Matches(source, Resources.RegexPattern, RegexOptions.Singleline))
                {
                    var mPath = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mPath) || mPath.Count(c => c == '/') != 1)
                    {
                        continue;
                    }
                    var mVer = mPath.Split('/').FirstOrDefault();
                    if (string.IsNullOrEmpty(mVer) || !mVer.All(c => char.IsDigit(c) || c == '.'))
                    {
                        continue;
                    }
                    if (!Version.TryParse(mVer, out Version ver) || paths.ContainsKey(ver))
                    {
                        continue;
                    }
                    paths.Add(ver, mPath);
                }
                updUrl = string.Format(Resources.UpdateUrl, paths[paths.Keys.Max()]);
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);

            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "iu.zip");
                        ResourcesEx.Extract(Resources.iu, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 17
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl;

            try
            {
                updUrl = string.Format(Resources.UpdateUrl,
#if x86
                                       "x86"
#else
                                       "x64"
#endif
                                       );
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var appPath    = PathEx.Combine(Resources.AppPath);
            var localDate  = File.GetLastWriteTime(appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);
            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "iu.zip");
                        ResourcesEx.Extract(Resources.iu, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 18
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl;

            try
            {
                var mirrors   = Resources.UpdateMirrors.SplitNewLine();
                var mirrorMap = new Dictionary <long, string>();
                foreach (var url in mirrors)
                {
                    var ping = NetEx.Ping(url);
                    while (mirrorMap.ContainsKey(ping))
                    {
                        ping++;
                    }
                    mirrorMap.Add(ping, url);
                }
                var sortedPings = mirrorMap.Keys.ToList();
                sortedPings.Sort();
                var bestPing = sortedPings.Min();
                var mirror   = mirrorMap[bestPing];
                var source   = NetEx.Transfer.DownloadString(string.Format(Resources.RegexUrl, mirror));
                if (string.IsNullOrWhiteSpace(source))
                {
                    foreach (var ping in sortedPings)
                    {
                        source = NetEx.Transfer.DownloadString(string.Format(Resources.RegexUrl, ping));
                        break;
                    }
                }
                if (string.IsNullOrWhiteSpace(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                var vers = new List <Version>();
                foreach (Match match in Regex.Matches(source, Resources.RegexVersionPattern, RegexOptions.Singleline))
                {
                    var mVer = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mVer))
                    {
                        continue;
                    }
                    var cVer = mVer.ToCharArray();
                    if (!cVer.Count(char.IsDigit).IsBetween(3, 16) || !cVer.Count(c => c == '.').IsBetween(2, 3))
                    {
                        continue;
                    }
                    mVer = new string(mVer.Where(c => char.IsDigit(c) || c == '.').ToArray());
                    if (!Version.TryParse(mVer, out Version ver))
                    {
                        continue;
                    }
                    vers.Add(ver);
                }
                _ver   = vers.Max();
                updUrl = string.Format(Resources.UpdateUrl, mirror, _ver,
#if x86
                                       "32"
#else
                                       "64"
#endif
                                       );
                var exists = NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent);
                if (!exists)
                {
                    foreach (var ping in sortedPings)
                    {
                        updUrl = string.Format(Resources.UpdateUrl, mirrorMap[ping], _ver,
#if x86
                                               "32"
#else
                                               "64"
#endif
                                               );
                        exists = NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent);
                        if (exists)
                        {
                            break;
                        }
                    }
                }
                if (!exists)
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);
            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "7z.zip");
                        ResourcesEx.Extract(Resources._7z, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 19
0
        private void MenuViewFormUpdate(bool setWindowLocation = true)
        {
            appsListView.BeginUpdate();
            try
            {
                appsListView.Items.Clear();
                appsListView.SmallImageList?.Images.Clear();
                if (!appsListView.Scrollable)
                {
                    appsListView.Scrollable = true;
                }

                var largeImages = Settings.Window.LargeImages;
                imageList.Images.Clear();
                foreach (var appData in CacheData.CurrentAppInfo)
                {
                    var key = appData.Key;
                    if (string.IsNullOrWhiteSpace(key))
                    {
                        continue;
                    }

                    var name = appData.Name;
                    if (string.IsNullOrWhiteSpace(name))
                    {
                        continue;
                    }

                    Image image;
                    if (CacheData.CurrentImages.ContainsKey(key))
                    {
                        image = CacheData.CurrentImages[key];
                        goto Finalize;
                    }
                    if (CacheData.AppImages.ContainsKey(key))
                    {
                        image = CacheData.AppImages[key];
                        goto UpdateCache;
                    }

                    var exePath = appData.FilePath;
                    if (!File.Exists(exePath))
                    {
                        continue;
                    }
                    try
                    {
                        var imgPath   = Path.ChangeExtension(exePath, ".ico");
                        var indicator = largeImages ? 32 : 16;
                        if (File.Exists(imgPath))
                        {
                            exePath = imgPath;
                            goto FromFile;
                        }
                        imgPath = Path.ChangeExtension(exePath, ".png");
                        if (!File.Exists(imgPath))
                        {
                            var appDir = Path.GetDirectoryName(exePath);
                            var imgDir = Path.Combine(appDir, "App\\AppInfo");
                            if (largeImages)
                            {
                                var sizes = new[] { 32, 40, 48, 64, 96, 128, 256 };
                                foreach (var size in sizes)
                                {
                                    imgPath = Path.Combine(imgDir, $"appicon_{size}.png");
                                    if (File.Exists(imgPath))
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                imgPath = Path.Combine(imgDir, "appicon_16.png");
                            }
                        }
                        if (File.Exists(imgPath))
                        {
                            image = Image.FromFile(imgPath);
                            if (image != default)
                            {
                                if (image.Width != image.Height || image.Width != indicator)
                                {
                                    image = image.Redraw(indicator, indicator);
                                }
                                goto UpdateCache;
                            }
                        }
                        if (exePath.EndsWithEx(".bat", ".cmd", ".jse", ".vbe", ".vbs"))
                        {
                            image = CacheData.GetSystemImage(ImageResourceSymbol.CommandPrompt, largeImages);
                            goto UpdateCache;
                        }
FromFile:
                        using (var ico = ResourcesEx.GetIconFromFile(exePath, 0, largeImages))
                        {
                            image = ico?.ToBitmap()?.Redraw(indicator, indicator);
                            if (image != default)
                            {
                                goto UpdateCache;
                            }
                        }
                    }
                    catch (Exception ex) when(ex.IsCaught())
                    {
                        Log.Write(ex);
                    }

                    image = CacheData.GetSystemImage(ImageResourceSymbol.Application, largeImages);
                    if (image == default)
                    {
                        continue;
                    }

UpdateCache:
                    if (!CacheData.CurrentImages.ContainsKey(key))
                    {
                        CacheData.CurrentImages.Add(key, image);
                    }

Finalize:
                    imageList.Images.Add(image);
                    appsListView.Items.Add(name, imageList.Images.Count - 1);
                }

                if (largeImages)
                {
                    imageList.ImageSize = new Size(32, 32);
                }
                appsListView.SmallImageList = imageList;
                CacheData.UpdateCurrentImagesFile();

                if (!setWindowLocation)
                {
                    return;
                }
                var taskbarLocation = TaskBar.GetLocation(Handle);
                if (Settings.Window.DefaultPosition == 0 && taskbarLocation != TaskBarLocation.Hidden)
                {
                    var screen = Screen.PrimaryScreen.WorkingArea;
                    foreach (var scr in Screen.AllScreens)
                    {
                        if (!scr.Bounds.Contains(Cursor.Position))
                        {
                            continue;
                        }
                        screen = scr.WorkingArea;
                        break;
                    }
                    switch (taskbarLocation)
                    {
                    case TaskBarLocation.Left:
                    case TaskBarLocation.Top:
                        Left = screen.X;
                        Top  = screen.Y;
                        break;

                    case TaskBarLocation.Right:
                        Left = screen.Width - Width;
                        Top  = screen.Y;
                        break;

                    default:
                        Left = screen.X;
                        Top  = screen.Height - Height;
                        break;
                    }
                }
                else
                {
                    Left = Cursor.Position.X - Width / 2;
                    Top  = Cursor.Position.Y - Height / 2;
                    if (!WinApi.NativeHelper.WindowIsOutOfScreenArea(Handle, out var newRect))
                    {
                        return;
                    }
                    Left = newRect.X;
                    Top  = newRect.Y;
                }
            }
            finally
            {
                appsListView.EndUpdate();
                appsCount.Text = string.Format(CultureInfo.InvariantCulture, Language.GetText(appsCount), appsListView.Items.Count, appsListView.Items.Count == 1 ? Language.GetText(nameof(en_US.App)) : Language.GetText(nameof(en_US.Apps)));
                if (!appsListView.Focus())
                {
                    appsListView.Select();
                }
            }
        }
Exemplo n.º 20
0
        private void MenuViewForm_Load(object sender, EventArgs e)
        {
            BackColor = Color.FromArgb(byte.MaxValue, Main.Colors.Base.R, Main.Colors.Base.G, Main.Colors.Base.B);
            if (Main.ScreenDpi > 96)
            {
                Font = SystemFonts.CaptionFont;
            }
            Icon        = Resources.PortableApps_blue;
            MaximumSize = Screen.FromHandle(Handle).WorkingArea.Size;
            Lang.SetControlLang(this);
            for (var i = 0; i < appMenu.Items.Count; i++)
            {
                appMenu.Items[i].Text = Lang.GetText(appMenu.Items[i].Name);
            }
            if (Main.SetFont(this))
            {
                layoutPanel.Size = new Size(Width - 2, Height - 2);
            }
            Main.SetFont(appMenu);

            layoutPanel.BackgroundImage       = Main.BackgroundImage;
            layoutPanel.BackgroundImageLayout = Main.BackgroundImageLayout;
            layoutPanel.BackColor             = Main.Colors.Base;
            layoutPanel.SetControlStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer);
            ControlEx.DrawSizeGrip(layoutPanel, Main.Colors.Base,
                                   (o, args) =>
            {
                Point point;
                switch (TaskBar.GetLocation(Handle))
                {
                case TaskBar.Location.Right:
                    point = new Point(1, Height - 1);
                    break;

                case TaskBar.Location.Bottom:
                    point = new Point(Width - 1, 1);
                    break;

                default:
                    point = new Point(Width - 1, Height - 1);
                    break;
                }
                WinApi.NativeHelper.ClientToScreen(Handle, ref point);
                WinApi.NativeHelper.SetCursorPos((uint)point.X, (uint)point.Y);
                var inputMouseDown = new WinApi.DeviceInput();
                inputMouseDown.Data.Mouse.Flags = 0x2;
                inputMouseDown.Type             = 0;
                var inputMouseUp = new WinApi.DeviceInput();
                inputMouseUp.Data.Mouse.Flags = 0x4;
                inputMouseUp.Type             = 0;
                WinApi.DeviceInput[] inputs   =
                {
                    inputMouseUp,
                    inputMouseDown
                };
                WinApi.NativeHelper.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(WinApi.DeviceInput)));
            },
                                   (o, args) =>
            {
                var p = o as PictureBox;
                if (p == null)
                {
                    return;
                }
                switch (TaskBar.GetLocation(Handle))
                {
                case TaskBar.Location.Right:
                case TaskBar.Location.Bottom:
                    p.Cursor = Cursors.SizeNESW;
                    break;

                default:
                    p.Cursor = Cursors.SizeNWSE;
                    break;
                }
            });

            _hideHScrollBar = Ini.Read("Settings", "Window.HideHScrollBar", false);
            if (Main.ScreenDpi > 96)
            {
                appsListViewPanel.Font = SystemFonts.SmallCaptionFont;
            }
            appsListViewPanel.BackColor = Main.Colors.Control;
            appsListViewPanel.ForeColor = Main.Colors.ControlText;
            appsListView.BackColor      = appsListViewPanel.BackColor;
            appsListView.ForeColor      = appsListViewPanel.ForeColor;
            appsListView.SetDoubleBuffer();
            appsListView.SetMouseOverCursor();

            searchBox.BackColor = Main.Colors.Control;
            searchBox.ForeColor = Main.Colors.ControlText;
            searchBox.DrawSearchSymbol(Main.Colors.ControlText);
            SearchBox_Leave(searchBox, EventArgs.Empty);

            title.ForeColor     = Main.BackgroundImage.GetAverageColor().InvertRgb().ToGrayScale();
            logoBox.Image       = Resources.PortableApps_Logo_gray.Redraw(logoBox.Height, logoBox.Height);
            appsCount.ForeColor = title.ForeColor;

            aboutBtn.BackgroundImage = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Help, Main.SystemResourcePath)?.ToBitmap();
            aboutBtn.BackgroundImage = aboutBtn.BackgroundImage.SwitchGrayScale($"{aboutBtn.Name}BackgroundImage");

            profileBtn.BackgroundImage = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.UserDir, true, Main.SystemResourcePath)?.ToBitmap();
            downloadBtn.Image          = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Network, Main.SystemResourcePath)?.ToBitmap();
            settingsBtn.Image          = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.SystemControl, Main.SystemResourcePath)?.ToBitmap();
            foreach (var btn in new[] { downloadBtn, settingsBtn })
            {
                btn.BackColor = Main.Colors.Button;
                btn.ForeColor = Main.Colors.ButtonText;
                btn.FlatAppearance.MouseDownBackColor = Main.Colors.Button;
                btn.FlatAppearance.MouseOverBackColor = Main.Colors.ButtonHover;
            }

            appMenuItem2.Image = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Uac, Main.SystemResourcePath)?.ToBitmap();
            appMenuItem3.Image = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Directory, Main.SystemResourcePath)?.ToBitmap();
            appMenuItem5.Image = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.Pin, Main.SystemResourcePath)?.ToBitmap();
            appMenuItem7.Image = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.RecycleBinEmpty, Main.SystemResourcePath)?.ToBitmap();
            appMenu.CloseOnMouseLeave(32);
            appMenu.EnableAnimation();
            appMenu.SetFixedSingle();

            var docDir = PathEx.Combine(PathEx.LocalDir, "Documents");

            if (Directory.Exists(docDir) && Data.DirIsLink(docDir) && !Data.MatchAttributes(docDir, FileAttributes.Hidden))
            {
                Data.SetAttributes(docDir, FileAttributes.Hidden);
            }

            _windowOpacity = Ini.Read("Settings", "Window.Opacity", 95d);
            if (_windowOpacity.IsBetween(20d, 100d))
            {
                _windowOpacity /= 100d;
            }
            else
            {
                _windowOpacity = .95d;
            }

            var windowFadeInEffect = Ini.Read("Settings", "Window.FadeInEffect", 0);

            _windowFadeInDuration = Ini.Read("Settings", "Window.FadeInDuration", 100);
            if (_windowFadeInDuration < 25)
            {
                _windowFadeInDuration = 25;
            }
            if (_windowFadeInDuration > 750)
            {
                _windowFadeInDuration = 750;
            }

            var windowWidth = Ini.Read("Settings", "Window.Size.Width", MinimumSize.Width);

            if (windowWidth > MinimumSize.Width && windowWidth < MaximumSize.Width)
            {
                Width = windowWidth;
            }
            if (windowWidth > MaximumSize.Width)
            {
                Width = MaximumSize.Width;
            }

            var windowHeight = Ini.Read("Settings", "Window.Size.Height", MinimumSize.Height);

            if (windowHeight > MinimumSize.Height && windowHeight < MaximumSize.Height)
            {
                Height = windowHeight;
            }
            if (windowHeight > MaximumSize.Height)
            {
                Height = MaximumSize.Height;
            }

            MenuViewForm_Update();

            var windowAnimation = windowFadeInEffect == 0 ? WinApi.AnimateWindowFlags.Blend : WinApi.AnimateWindowFlags.Slide;

            switch (windowAnimation)
            {
            case WinApi.AnimateWindowFlags.Blend:
                return;

            case WinApi.AnimateWindowFlags.Slide:
                var windowPosition = Ini.Read("Settings", "Window.DefaultPosition", 0);
                if (windowPosition == 1)
                {
                    windowAnimation = WinApi.AnimateWindowFlags.Center;
                    break;
                }
                switch (TaskBar.GetLocation(Handle))
                {
                case TaskBar.Location.Left:
                    windowAnimation |= WinApi.AnimateWindowFlags.HorPositive;
                    break;

                case TaskBar.Location.Top:
                    windowAnimation |= WinApi.AnimateWindowFlags.VerPositive;
                    break;

                case TaskBar.Location.Right:
                    windowAnimation |= WinApi.AnimateWindowFlags.HorNegative;
                    break;

                case TaskBar.Location.Bottom:
                    windowAnimation |= WinApi.AnimateWindowFlags.VerNegative;
                    break;

                default:
                    windowAnimation = WinApi.AnimateWindowFlags.Center;
                    break;
                }
                break;
            }
            Opacity = _windowOpacity;
            WinApi.NativeHelper.AnimateWindow(Handle, _windowFadeInDuration, windowAnimation);
        }
Exemplo n.º 21
0
        private void MenuViewForm_Update(bool setWindowLocation = true)
        {
            Main.CheckAvailableApps();
            appsListView.BeginUpdate();
            try
            {
                appsListView.Items.Clear();
                if (!appsListView.Scrollable)
                {
                    appsListView.Scrollable = true;
                }

                imgList.Images.Clear();

                var cachePath = Path.Combine(Main.TmpDir, "images.dat");
                var cacheDict = new Dictionary <string, Image>();
                var cacheSize = 0;

                string dictPath = null;
                Dictionary <string, Image> imgDict = null;
                Image defExeIcon = null;

                for (var i = 0; i < Main.AppsInfo.Count; i++)
                {
                    var appInfo  = Main.AppsInfo[i];
                    var longName = appInfo.LongName;
                    if (string.IsNullOrWhiteSpace(longName))
                    {
                        continue;
                    }

                    appsListView.Items.Add(longName, i);
                    var shortName = appInfo.ShortName;
                    if (File.Exists(cachePath))
                    {
                        if (cacheDict?.Any() != true)
                        {
                            cacheDict = File.ReadAllBytes(cachePath).DeserializeObject <Dictionary <string, Image> >();
                            cacheSize = cacheDict.Count;
                        }
                        if (cacheDict?.ContainsKey(shortName) == true)
                        {
                            var img = cacheDict[shortName];
                            imgList.Images.Add(shortName, img);
                            continue;
                        }
                    }

                    if (dictPath == null)
                    {
                        dictPath = PathEx.Combine(PathEx.LocalDir, "Assets\\images.dat");
                    }
                    if (!File.Exists(dictPath))
                    {
                        goto TryHard;
                    }
                    if (imgDict == null)
                    {
                        imgDict = File.ReadAllBytes(dictPath).DeserializeObject <Dictionary <string, Image> >();
                    }
                    if (imgDict == null)
                    {
                        goto TryHard;
                    }
                    if (imgDict?.ContainsKey(shortName) == true)
                    {
                        var img = imgDict[shortName];
                        imgList.Images.Add(shortName, img);
                        cacheDict.Add(shortName, img);
                        continue;
                    }

TryHard:
                    try
                    {
                        var   exePath = appInfo.ExePath;
                        var   imgPath = Path.ChangeExtension(exePath, ".png");
                        Image img;
                        if (!string.IsNullOrEmpty(imgPath) && File.Exists(imgPath))
                        {
                            img = Image.FromFile(imgPath);
                            imgList.Images.Add(shortName, img);
                            cacheDict.Add(shortName, img);
                            continue;
                        }
                        var appDir = Path.GetDirectoryName(exePath);
                        if (!string.IsNullOrEmpty(appDir) && !File.Exists(imgPath))
                        {
                            imgPath = Path.Combine(appDir, "App\\AppInfo\\appicon_16.png");
                        }
                        if (!string.IsNullOrEmpty(imgPath) && File.Exists(imgPath))
                        {
                            img = Image.FromFile(imgPath)?.Redraw(16, 16);
                            imgList.Images.Add(shortName, img);
                            cacheDict.Add(shortName, img);
                            continue;
                        }
                        using (var ico = ResourcesEx.GetIconFromFile(exePath))
                        {
                            img = ico?.ToBitmap()?.Redraw(16, 16);
                            if (img == null)
                            {
                                goto Default;
                            }
                            imgList.Images.Add(shortName, img);
                            cacheDict.Add(shortName, img);
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }

Default:
                    if (defExeIcon == null)
                    {
                        defExeIcon = ResourcesEx.GetSystemIcon(ResourcesEx.IconIndex.ExeFile, Main.SystemResourcePath)?.ToBitmap().Redraw(16, 16);
                    }
                    if (defExeIcon == null)
                    {
                        continue;
                    }
                    imgList.Images.Add(shortName, defExeIcon);
                }

                appsListView.SmallImageList = imgList;
                if (cacheDict.Count > 0 && (cacheDict.Count != cacheSize || !File.Exists(cachePath)))
                {
                    File.WriteAllBytes(cachePath, cacheDict.SerializeObject());
                }

                if (!setWindowLocation)
                {
                    return;
                }
                var defaultPos      = Ini.Read("Settings", "Window.DefaultPosition", 0);
                var taskbarLocation = TaskBar.GetLocation(Handle);
                if (defaultPos == 0 && taskbarLocation != TaskBar.Location.Hidden)
                {
                    var screen = Screen.PrimaryScreen.WorkingArea;
                    foreach (var scr in Screen.AllScreens)
                    {
                        if (!scr.Bounds.Contains(Cursor.Position))
                        {
                            continue;
                        }
                        screen = scr.WorkingArea;
                        break;
                    }
                    switch (taskbarLocation)
                    {
                    case TaskBar.Location.Left:
                    case TaskBar.Location.Top:
                        Left = screen.X;
                        Top  = screen.Y;
                        break;

                    case TaskBar.Location.Right:
                        Left = screen.Width - Width;
                        Top  = screen.Y;
                        break;

                    default:
                        Left = screen.X;
                        Top  = screen.Height - Height;
                        break;
                    }
                }
                else
                {
                    var newLocation = GetWindowStartPos(new Point(Width, Height));
                    Left = newLocation.X;
                    Top  = newLocation.Y;
                }
            }
            finally
            {
                appsListView.EndUpdate();
                appsCount.Text = string.Format(Lang.GetText(appsCount), appsListView.Items.Count, appsListView.Items.Count == 1 ? Lang.GetText(nameof(en_US.App)) : Lang.GetText(nameof(en_US.Apps)));
                if (!appsListView.Focus())
                {
                    appsListView.Select();
                }
            }
        }
Exemplo n.º 22
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl = null;

            try
            {
                _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppDisplayName));
                var hlpPath = Path.Combine(_tmpDir, "js.zip");
                ResourcesEx.Extract(Resources.js, hlpPath, true);
                Compaction.Unzip(hlpPath, _tmpDir);
                Thread.Sleep(200);
                var helperPath = Path.Combine(_tmpDir, "read.js");
                var source     = Path.Combine(_tmpDir, "source.txt");
                File.WriteAllText(helperPath, Resources.JsScript);
                using (var p = ProcessEx.Send(string.Format(Resources.RunScript, _tmpDir), Elevation.IsAdministrator, ProcessWindowStyle.Hidden, false))
                    if (p?.HasExited == false)
                    {
                        p.WaitForExit();
                    }
                source = File.ReadAllText(source);
                if (string.IsNullOrWhiteSpace(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(".exe")).Take(1).Join();
                foreach (Match match in Regex.Matches(source, Resources.RegexUrlPattern, RegexOptions.Singleline))
                {
                    var mUrl = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mUrl))
                    {
                        continue;
                    }
                    updUrl = mUrl.Trim('"');
                    break;
                }
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);

            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        var hlpPath = Path.Combine(_tmpDir, "iu.zip");
                        ResourcesEx.Extract(Resources.iu, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }