Пример #1
0
        // Computes defensive statistics.
        public List <ListGroup> GetDefensiveAttributes()
        {
            AttributeSet ch  = new AttributeSet();
            AttributeSet def = new AttributeSet();

            // Difficulty.

            float life;

            if (ChaosInoculation)
            {
                life = Global["Maximum Life becomes #, Immune to Chaos Damage"][0];
            }
            else
            {
                life = Global["+# to maximum Life"][0];
                if (Global.ContainsKey("#% increased maximum Life"))
                {
                    life = IncreaseValueByPercentage(life, Global["#% increased maximum Life"][0]);
                }
            }
            ch["Life: #"] = new List <float>()
            {
                RoundValue(life, 0)
            };

            float mana    = Global["+# to maximum Mana"][0];
            float incMana = 0;

            if (Global.ContainsKey("#% increased maximum Mana"))
            {
                incMana = Global["#% increased maximum Mana"][0];
            }

            float es = 0;
            float lessArmourAndES = 0;

            if (Acrobatics)
            {
                lessArmourAndES += Global["#% Chance to Dodge Attacks. #% less Armour and Energy Shield, #% less Chance to Block Spells and Attacks"][1];
            }
            float shieldArmour, shieldEvasion;

            EnergyShield(ref mana, incMana, ref es, lessArmourAndES, out shieldArmour, out shieldEvasion);

            if (BloodMagic)
            {
                mana = 0;
            }

            ch["Mana: #"] = new List <float>()
            {
                RoundValue(mana, 0)
            };
            ch["Maximum Energy Shield: #"] = new List <float>()
            {
                RoundValue(es, 0)
            };
            ArmorAndEvasion(def, lessArmourAndES, shieldArmour, shieldEvasion);

            // Dodge Attacks and Spells.
            Dodge(def);

            // Energy Shield Recharge per Second.
            // @see http://pathofexile.gamepedia.com/Energy_shield
            EnergyShieldRegen(def, es);

            // Life Regeneration.
            LifeRegen(def, life, es);

            // Mana Regeneration.
            ManaRegen(def, mana);

            // Character attributes.
            ch["Strength: #"]     = Global["+# to Strength"];
            ch["Dexterity: #"]    = Global["+# to Dexterity"];
            ch["Intelligence: #"] = Global["+# to Intelligence"];

            // Shield, Staff and Dual Wielding detection.
            bool hasShield = OffHand.IsShield();

            Resistances(def, Difficulty.Normal, hasShield);
            Block(def, hasShield);

            HitAvoidance(def);

            List <ListGroup> groups = new List <ListGroup>();

            groups.Add(new ListGroup(L10n.Message("Character"), ch));
            groups.Add(new ListGroup(L10n.Message("Defense"), def));

            return(groups);
        }
Пример #2
0
 // Displays generic error message box with optional details.
 public static void Error(string message, string details = null)
 {
     MetroMessageBox.Show(GetActiveWindow(), Format(message, details), L10n.Message("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
 }
 public static Task ShowInfoAsync(this MetroWindow window, string message, string details = null, string title = null)
 {
     return(ShowAsync(window, message, details, title ?? L10n.Message("Information"), MessageBoxButton.OK, MessageBoxImage.Information));
 }
Пример #4
0
        private async Task Delete(IBuildViewModel build)
        {
            if (build == null)
            {
                return;
            }
            if (TreeFind <BuildViewModel>(b => b == CurrentBuild, build) != null)
            {
                await _dialogCoordinator.ShowInfoAsync(this,
                                                       L10n.Message("The currently opened build can not be deleted."));

                return;
            }
            if (build is IBuildFolderViewModel)
            {
                var result = await _dialogCoordinator.ShowQuestionAsync(this,
                                                                        string.Format(L10n.Message("This will delete the build folder \"{0}\" and all its contents.\n"),
                                                                                      build.Build.Name) + L10n.Message("Do you want to continue?"));

                if (result != MessageBoxResult.Yes)
                {
                    return;
                }
            }
            build.IsSelected        = false;
            build.Parent.IsSelected = true;
            build.Parent.Children.Remove(build);
            await DeleteBuildFile(build);
        }
Пример #5
0
        /// <summary>
        /// Converts the given XmlPseudoAttributes into PseudoAttributes.
        /// Does not resolve nesting so there may be duplicates.
        /// </summary>
        private IEnumerable <PseudoAttribute> ConvertFromXml(IEnumerable <XmlPseudoAttribute> xmlPseudoAttributes)
        {
            foreach (var xmlPseudo in xmlPseudoAttributes)
            {
                var pseudo = new PseudoAttribute(xmlPseudo.Name, xmlPseudo.Group);
                _pseudoNameDict[pseudo.Name] = pseudo;

                _nestedPseudosDict[pseudo.Name] = new List <string>();
                foreach (var xmlNestedPseudo in xmlPseudo.PseudoAttributes ?? new XmlNestedPseudoAttribute[0])
                {
                    _nestedPseudosDict[pseudo.Name].Add(xmlNestedPseudo.Name);
                }

                foreach (var xmlAttr in xmlPseudo.Attributes ?? new XmlNestedAttribute[0])
                {
                    var attr = new Attribute(xmlAttr.Name);
                    if (xmlAttr.ConversionMultiplierSpecified)
                    {
                        attr.ConversionMultiplier = (float)xmlAttr.ConversionMultiplier;
                    }
                    pseudo.Attributes.Add(attr);

                    var xmlConditions = xmlAttr.Conditions ?? new XmlAttributeConditions()
                    {
                        Items = new object[0]
                    };
                    for (var i = 0; i < xmlConditions.Items.Length; i++)
                    {
                        ICondition condition;
                        var        xmlCondition = xmlConditions.Items[i];
                        switch (xmlConditions.ItemsElementName[i])
                        {
                        case XmlItemsChoiceType.AndComposition:
                            var xmlAndComp = (XmlAndComposition)xmlCondition;
                            var andComp    = new AndComposition();
                            if (xmlAndComp.Keystone != null)
                            {
                                andComp.Conditions.Add(new KeystoneCondition(xmlAndComp.Keystone));
                            }
                            if (xmlAndComp.OffHand != null)
                            {
                                andComp.Conditions.Add(new OffHandCondition(xmlAndComp.OffHand));
                            }
                            if (xmlAndComp.Tag != null)
                            {
                                andComp.Conditions.Add(new TagCondition(xmlAndComp.Tag));
                            }
                            if (xmlAndComp.WeaponClass != null)
                            {
                                andComp.Conditions.Add(new WeaponClassCondition(xmlAndComp.WeaponClass));
                            }

                            if (xmlAndComp.NotCondition != null)
                            {
                                var notCond = ConvertXmlNotCondition(xmlAndComp.NotCondition, pseudo, attr);
                                andComp.Conditions.Add(notCond);
                            }
                            condition = andComp;
                            break;

                        case XmlItemsChoiceType.Not:
                            condition = ConvertXmlNotCondition((XmlNotCondition)xmlCondition, pseudo, attr);
                            break;

                        case XmlItemsChoiceType.OffHand:
                            condition = new OffHandCondition(xmlCondition.ToString() !);
                            break;

                        case XmlItemsChoiceType.Tag:
                            condition = new TagCondition(xmlCondition.ToString() !);
                            break;

                        case XmlItemsChoiceType.WeaponClass:
                            condition = new WeaponClassCondition(xmlCondition.ToString() !);
                            break;

                        case XmlItemsChoiceType.Keystone:
                            condition = new KeystoneCondition(xmlCondition.ToString() !);
                            break;

                        default:
                            throw new PseudoAttributeDataInvalidException(
                                      string.Format(L10n.Message("Unsupported condition type in attribute {0} in pseudo attribute {1}"), attr.Name, pseudo.Name));
                        }
                        attr.Conditions.Add(condition);
                    }
                }

                if (xmlPseudo.Hidden != "True")
                {
                    // If hidden they are only added to _pseudoNameDict and _nestedPseudosDict but not returned.
                    yield return(pseudo);
                }
            }
        }
 public static Task <MessageBoxResult> ShowQuestionAsync(this MetroWindow window, string message,
                                                         string title = null, MessageBoxImage image = MessageBoxImage.Question)
 {
     return(ShowAsync(window, message, title: title ?? L10n.Message("Confirmation"), buttons: MessageBoxButton.YesNo,
                      image: image, defaultResult: MessageBoxResult.No));
 }
Пример #7
0
 public static Task ShowWarningAsync(this MetroWindow window, string message, string?details = null, string?title = null)
 {
     return(ShowAsync(window, message, details, title ?? L10n.Message("Warning"), MessageBoxButton.OK, MessageBoxImage.Exclamation));
 }
Пример #8
0
        private async Task EditStashTabAsync(StashBookmarkViewModel bookmarkVm)
        {
            var bookmark = bookmarkVm.Bookmark;
            var vm       = new TabPickerViewModel
            {
                Color = bookmark.Color,
                Name  = bookmark.Name
            };
            var result = await _dialogCoordinator.EditStashTabAsync(this, vm);

            switch (result)
            {
            case TabPickerResult.Delete:
                Bookmarks.Remove(bookmarkVm);
                PersistentData.StashBookmarks.Remove(bookmark);
                break;

            case TabPickerResult.DeleteIncludingItems:
                var confirmationResult = await _dialogCoordinator.ShowQuestionAsync(this,
                                                                                    L10n.Message(
                                                                                        "This will delete all items between this and the next bookmark and can not be undone.\nDo you want to continue?"),
                                                                                    title : L10n.Message("Delete items"));

                if (confirmationResult == MessageBoxResult.Yes)
                {
                    DeleteBookmarkAndItems(bookmarkVm);
                }
                break;

            case TabPickerResult.Affirmative:
                bookmark.Name  = vm.Name;
                bookmark.Color = vm.Color;
                break;
            }
        }
Пример #9
0
 /// <summary>
 /// Instantiates a new SteinerTabViewModel.
 /// </summary>
 /// <param name="tree">The (not null) SkillTree instance to operate on.</param>
 public SteinerTabViewModel(SkillTree tree)
     : base(tree)
 {
     DisplayName = L10n.Message("Tagged Nodes");
 }
Пример #10
0
 public static Task <MessageBoxResult> ShowQuestionAsync(this MetroWindow window, string message,
                                                         string?details        = null, string?title = null, MessageBoxButton buttons = MessageBoxButton.YesNo,
                                                         MessageBoxImage image = MessageBoxImage.Question)
 {
     return(ShowAsync(window, message, details, title ?? L10n.Message("Confirmation"), buttons, image));
 }
        private async Task FileSystemWatcherOnChanged()
        {
            // There might be multiple changes, only react to the first one.
            // Events for changes that take some time should occur before they are reenabled.
            _fileSystemWatcher.EnableRaisingEvents = false;
            var message = L10n.Message("Files in your build save directory have been changed.\n" +
                                       "Do you want to reload all builds from the file system?");

            if (GetDirtyBuilds().Any())
            {
                message += L10n.Message("\nAll unsaved changes will be lost.");
            }
            message += L10n.Message("\n\nYou can also reload through the 'File' menu.");
            var result = await _dialogCoordinator.ShowQuestionAsync(this, message, title : L10n.Message("Builds changed"));

            if (result == MessageBoxResult.Yes)
            {
                await PersistentData.ReloadBuildsAsync();
            }
            _fileSystemWatcher.EnableRaisingEvents = true;
        }
Пример #12
0
        /// <summary>
        ///     Loads from the unofficial online tool
        /// </summary>
        public static void LoadBuildFromPoezone(SkillTree tree, string buildUrl)
        {
            if (!buildUrl.Contains('#'))
            {
                throw new FormatException();
            }

            const string dataUrl      = "http://poezone.ru/skilltree/data.js";
            const string buildPostUrl = "http://poezone.ru/skilltree/";
            string       build        = buildUrl.Substring(buildUrl.LastIndexOf('#') + 1);

            string dataFile, buildFile;

            {
                var req = (HttpWebRequest)WebRequest.Create(dataUrl);
                req.UserAgent =
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30";
                WebResponse resp = req.GetResponse();
                dataFile = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            }

            {
                string postData  = "build=" + build;
                byte[] postBytes = Encoding.ASCII.GetBytes(postData);
                var    req       = (HttpWebRequest)WebRequest.Create(buildPostUrl);
                req.Method        = "POST";
                req.ContentLength = postBytes.Length;
                req.ContentType   = "application/x-www-form-urlencoded";
                req.UserAgent     =
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30";
                req.Accept  = "application/json, text/javascript, */*; q=0.01";
                req.Host    = "poezone.ru";
                req.Referer = "http://poezone.ru/skilltree/";
                req.AutomaticDecompression = DecompressionMethods.GZip;
                //req.Headers.Add( "Accept", "application/json, text/javascript" );
                req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
                req.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
                req.Headers.Add("Accept-Language", "en-US,en;q=0.8");

                //req.Headers.Add( "Connection", "keep-alive" );
                //req.Headers.Add( "Host", "poezone.ru" );
                req.Headers.Add("Origin", "http://poezone.ru");
                //req.Headers.Add( "Referer", "http://poezone.ru/skilltree/" );
                //req.Headers.Add( "User-Agent", );
                req.Headers.Add("X-Requested-With", "XMLHttpRequest");
                req.Expect      = "";
                req.Credentials = CredentialCache.DefaultCredentials;

                Stream dataStream = req.GetRequestStream();
                dataStream.Write(postBytes, 0, postBytes.Length);
                dataStream.Close();

                WebResponse resp   = req.GetResponse();
                string      status = (resp as HttpWebResponse).StatusDescription;
                buildFile = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            }

            if (!buildFile.Contains("["))
            {
                Popup.Error(string.Format(L10n.Message("An error occured while attempting to load Skill tree from {0} location."), "poezone.ru"));
                return;
            }

            // position decompose
            var positions = new List <Vector2D?>();

            string[] lines = dataFile.Split('\n');
            foreach (string line in lines)
            {
                if (line.StartsWith("skillpos="))
                {
                    string posString = line.Substring(line.IndexOf('[') + 1,
                                                      line.LastIndexOf(']') - line.IndexOf('[') - 1);
                    var  sb        = new StringBuilder();
                    bool inBracket = false;
                    foreach (char c in posString)
                    {
                        if (!inBracket && c == ',')
                        {
                            positions.Add(sb.Length == 0
                                ? null
                                : new Vector2D?(new Vector2D(
                                                    int.Parse(sb.ToString().Split(',')[0]),
                                                    int.Parse(sb.ToString().Split(',')[1])
                                                    )));
                            sb.Clear();
                        }
                        else
                        {
                            if (c == '[')
                            {
                                inBracket = true;
                            }
                            else if (c == ']')
                            {
                                inBracket = false;
                            }
                            else
                            {
                                sb.Append(c);
                            }
                        }
                    }
                    positions.Add(sb.Length == 0
                        ? null
                        : new Vector2D?(new Vector2D(
                                            int.Parse(sb.ToString().Split(',')[0]),
                                            int.Parse(sb.ToString().Split(',')[1])
                                            )));
                }
            }

            // min max
            double minx = float.MaxValue, miny = float.MaxValue, maxx = float.MinValue, maxy = float.MinValue;

            foreach (var posn in positions)
            {
                if (!posn.HasValue)
                {
                    continue;
                }
                Vector2D pos = posn.Value;
                minx = Math.Min(pos.X, minx);
                miny = Math.Min(pos.Y, miny);
                maxx = Math.Max(pos.X, maxx);
                maxy = Math.Max(pos.Y, maxy);
            }

            double nminx = float.MaxValue, nminy = float.MaxValue, nmaxx = float.MinValue, nmaxy = float.MinValue;

            foreach (SkillNode node in SkillTree.Skillnodes.Values)
            {
                Vector2D pos = node.Position;
                nminx = Math.Min(pos.X, nminx);
                nminy = Math.Min(pos.Y, nminy);
                nmaxx = Math.Max(pos.X, nmaxx);
                nmaxy = Math.Max(pos.Y, nmaxy);
            }

            //respose
            string[] buildResp = buildFile.Replace("[", "").Replace("]", "").Split(',');
            int      character = int.Parse(buildResp[0]);
            var      skilled   = new List <int>();

            tree.Chartype = character;
            tree.SkilledNodes.Clear();
            SkillNode startnode =
                SkillTree.Skillnodes.First(nd => nd.Value.Name == SkillTree.CharName[tree.Chartype].ToUpper()).Value;

            tree.SkilledNodes.Add(startnode.Id);

            for (int i = 1; i < buildResp.Length; ++i)
            {
                if (!positions[int.Parse(buildResp[i])].HasValue)
                {
                    Debugger.Break();
                }

                Vector2D poezonePos = (positions[int.Parse(buildResp[i])].Value - new Vector2D(minx, miny)) *
                                      new Vector2D(1 / (maxx - minx), 1 / (maxy - miny));
                double minDis  = 2;
                var    minNode = new KeyValuePair <ushort, SkillNode>();
                foreach (var node in SkillTree.Skillnodes)
                {
                    Vector2D nodePos = (node.Value.Position - new Vector2D(nminx, nminy)) *
                                       new Vector2D(1 / (nmaxx - nminx), 1 / (nmaxy - nminy));
                    double dis = (nodePos - poezonePos).Length;
                    if (dis < minDis)
                    {
                        minDis  = dis;
                        minNode = node;
                    }
                }

                tree.SkilledNodes.Add(minNode.Key);
            }
            tree.UpdateAvailNodes();

            //string dataFile =
        }
        private void btnPopupLoadTabFile_Click(object sender, RoutedEventArgs e)
        {
            var fileDialog = new OpenFileDialog {
                Multiselect = false
            };
            var ftoload = fileDialog.ShowDialog(this);

            if (ftoload.Value)
            {
                var cont = File.ReadAllText(fileDialog.FileName);
                var mw   = this.Owner as MainWindow;
                if (mw == null)
                {
                    return;
                }

                var      stash          = mw.Stash;
                IntRange highlightrange = null;
                try
                {
                    var data = File.ReadAllText(fileDialog.FileName);

                    var json  = JObject.Parse(data);
                    var items = (json["items"] as JArray).Select(i => new Item((JObject)i)).ToArray();

                    //get free line
                    var y            = stash.LastOccupiedLine + 3;
                    var fittingitems = items.Where(i => i.X >= 0 && i.X + i.Width <= 12).ToList();


                    StashBookmark sb = new StashBookmark("imported", y);
                    if (cbTabs.SelectedItem != null)
                    {
                        var sstab = cbTabs.SelectedItem as StashBookmark;
                        sb = new StashBookmark(sstab.Name, y, sstab.Color);
                    }


                    stash.BeginUpdate();
                    stash.AddBookmark(sb);
                    var my             = fittingitems.Min(i => i.Y);
                    var y2             = y;
                    var unfittingitems = items.Where(i => i.X < 0 || i.X + i.Width > 12);
                    foreach (var item in items)
                    {
                        item.Y += y - my;
                        stash.Items.Add(item);
                        if (y2 < item.Y + item.Height)
                        {
                            y2 = item.Y + item.Height;
                        }
                    }


                    int x    = 0;
                    int maxh = 0;
                    var y3   = y2;
                    foreach (var item in unfittingitems)
                    {
                        if (x + item.Width > 12) //next line
                        {
                            x    = 0;
                            y2  += maxh;
                            maxh = 0;
                        }

                        item.X = x;
                        x     += item.Width;

                        if (maxh < item.Height)
                        {
                            maxh = item.Height;
                        }

                        item.Y = y2;
                        stash.Items.Add(item);

                        if (y3 < item.Y + item.Height)
                        {
                            y3 = item.Y + item.Height;
                        }
                    }
                    Popup.Info(string.Format(L10n.Message("New tab with {0} items was added to stash"), items.Length));
                    highlightrange = new IntRange()
                    {
                        From = y, Range = y3 - y
                    };
                }
                catch (Exception ex)
                {
                    Popup.Error(L10n.Message("An error occurred while attempting to load stash data."), ex.Message);
                }
                finally
                {
                    stash.EndUpdate();
                }

                if (highlightrange != null)
                {
                    stash.AddHighlightRange(highlightrange);
                }
            }
        }
Пример #14
0
 // Displays generic information message box with optional details.
 public static void Info(string message, string details = null)
 {
     MetroMessageBox.Show(GetActiveWindow(), Format(message, details), L10n.Message("Information"), MessageBoxButton.OK, MessageBoxImage.Information);
 }
Пример #15
0
        /// <summary>
        /// Imports the build located at <paramref name="buildPath"/>. <see cref="IPersistentData.SaveBuild"/> may be
        /// called by this method.
        /// </summary>
        public async Task ImportBuildFromFileAsync(string buildPath)
        {
            const string extension = SerializationConstants.BuildFileExtension;

            if (!File.Exists(buildPath) || Path.GetExtension(buildPath) != extension)
            {
                Log.Error($"Could not import build file from {buildPath}");
                var message = string.Format(
                    L10n.Message(
                        "Could not import build file, only existing files with the extension {0} can be imported."),
                    extension);
                await DialogCoordinator.ShowErrorAsync(PersistentData, message, title : L10n.Message("Import failed"));

                return;
            }

            var unifiedBuildsSavePath = PersistentData.Options.BuildsSavePath.Replace(Path.AltDirectorySeparatorChar,
                                                                                      Path.DirectorySeparatorChar);
            var unifiedPath = buildPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

            if (unifiedPath.StartsWith(unifiedBuildsSavePath))
            {
                // If BuildsSavePath is part of buildPath, just set it as current and selected build
                // Remove BuildsSavePath
                var relativePath = unifiedPath.Remove(0, unifiedBuildsSavePath.Length + 1);
                // Remove extension
                var path  = relativePath.Remove(relativePath.Length - extension.Length);
                var build = BuildForPath(path) as PoEBuild;
                if (build == null)
                {
                    Log.Warn($"Import failed, build with path {path} not found");
                    return;
                }

                PersistentData.CurrentBuild  = build;
                PersistentData.SelectedBuild = build;
            }
            else
            {
                // Else, proper import
                var build = await ImportBuildAsync(
                    async() => await XmlSerializationUtils.DeserializeFileAsync <XmlBuild>(buildPath));

                if (build != null)
                {
                    build.Name = Util.FindDistinctName(build.Name, PersistentData.RootBuild.Builds.Select(b => b.Name));
                    PersistentData.RootBuild.Builds.Add(build);
                    PersistentData.CurrentBuild  = build;
                    PersistentData.SelectedBuild = build;
                    PersistentData.SaveBuild(PersistentData.RootBuild);
                }
            }
        }
Пример #16
0
 // Displays generic warning message box with optional details.
 public static void Warning(string message, string details = null)
 {
     MetroMessageBox.Show(GetActiveWindow(), Format(message, details), L10n.Message("Warning"), MessageBoxButton.OK, MessageBoxImage.Exclamation);
 }
Пример #17
0
        // Overrides OnExit method to save persistent data.
        protected override void OnExit(ExitEventArgs e)
        {
            try
            {
                PrivatePersistentData.SavePersistentDataToFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(L10n.Message("An error occurred during a save operation.") + "\n\n" + ex.Message, L10n.Message("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
            }

            base.OnExit(e);
        }
Пример #18
0
        /* Checks for updates and returns release informations when there is newer one.
         * Returns null if there is no newer release.
         * If Prerelease argument is true, it will return also Pre-release, otherwise Pre-releases are ignored.
         * An existing last checked release will be discarded.
         * Throws UpdaterException if error occurs.
         */
        public static Release CheckForUpdates(bool Prerelease = true)
        {
            if (Latest != null)
            {
                if (Latest.IsDownloading)
                {
                    throw new UpdaterException(L10n.Message("Download already in progress"));
                }

                // If release was installed, report no update.
                if (Latest.IsInstalled)
                {
                    return(null);
                }

                Dispose();
            }

            if (IsNewerProductInstalled())
            {
                // Newer product is installed, there is no update.
                IsChecked = true;

                return(null);
            }

            var webClient = new UpdaterWebClient();

            webClient.Encoding = Encoding.UTF8;

            try
            {
                string json     = webClient.DownloadString(GitAPILatestReleaseURL);
                JArray releases = JArray.Parse(json);
                if (releases.Count < 1)
                {
                    throw new UpdaterException(L10n.Message("No release found"));
                }

                Version current = GetCurrentVersion(); // Current version (tag).

                // Iterate thru avialable releases.
                foreach (JObject release in (JArray)releases)
                {
                    // Drafts are not returned by API, but just in case...
                    bool draft = release["draft"].Value <bool>();
                    if (draft)
                    {
                        continue;        // Ignore drafts.
                    }
                    // Check if there are assets attached.
                    JArray assets = (JArray)release["assets"];
                    if (assets.Count < 1)
                    {
                        continue;                   // No assets, ignore it.
                    }
                    // Compare release tag with our version (tag).
                    string  tag     = release["tag_name"].Value <string>();
                    Version version = new Version(tag);
                    if (version.CompareTo(current) <= 0)
                    {
                        // Same or older version.
                        IsChecked = true;

                        return(null);
                    }

                    // Check if it is pre-release and we want to update to it.
                    bool prerelease = release["prerelease"].Value <bool>();
                    if (prerelease && !Prerelease)
                    {
                        continue;                            // Found unwanted pre-release, ignore it.
                    }
                    // Find release package.
                    string  fileName = null;
                    JObject pkgAsset = null;
                    foreach (JObject asset in assets)
                    {
                        // Check if asset upload completed.
                        if (asset["state"].Value <string>() != "uploaded")
                        {
                            continue;
                        }

                        string content_type = asset["content_type"].Value <string>();
                        if (content_type != PackageContentType)
                        {
                            continue;                                     // Not a package, ignore it.
                        }
                        fileName = asset["name"].Value <string>();
                        Match m = RePackage.Match(fileName);
                        if (m.Success)
                        {
                            // Found release package.
                            pkgAsset = asset;
                            break;
                        }
                    }
                    if (pkgAsset == null)
                    {
                        continue;                   // No package found.
                    }
                    // This is newer release.
                    IsChecked = true;
                    Latest    = new Release
                    {
                        Name         = release["name"].Value <string>(),
                        Description  = release["body"].Value <string>(),
                        IsPrerelease = prerelease,
                        // A release is an update, if file name starts with our PackageName.
                        IsUpdate        = fileName.StartsWith(GetPackageName(Properties.Version.ProductName) + "-"),
                        PackageFileName = fileName,
                        Version         = tag,
                        URI             = new Uri(pkgAsset["browser_download_url"].Value <string>())
                    };

                    // We are done, exit loop.
                    break;
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    throw new UpdaterException("HTTP " + ((int)((HttpWebResponse)e.Response).StatusCode) + " " + ((HttpWebResponse)e.Response).StatusDescription);
                }
                else
                {
                    throw new UpdaterException(e.Message, e);
                }
            }
            catch (Exception e)
            {
                throw new UpdaterException(e.Message, e);
            }

            return(Latest);
        }
 public DownloadItemsWindow(string characterName, string accountName)
 {
     InitializeComponent();
     tbCharName.Text = string.IsNullOrEmpty(characterName) ? L10n.Message("CharacterName") : characterName;
     tbAccName.Text  = string.IsNullOrEmpty(accountName) ? L10n.Message("AccountName") : accountName;
 }
Пример #20
0
        public ColorButtonDialog()
        {
            InitializeComponent();

            ObservableCollection <ColorItem> available = new ObservableCollection <ColorItem> {
                new ColorItem(null, "Default")
            };

            ObservableCollection <ColorItem> standard = new ObservableCollection <ColorItem>();

            foreach (NamedColor nc in ColorUtils.StandardColors)
            {
                standard.Add(new ColorItem(nc.Color, nc.Name));
            }


            BackgroundColorPicker.AvailableColorsHeader = BorderColorPicker.AvailableColorsHeader = TextColorPicker.AvailableColorsHeader = L10n.Message("Original color");
            BackgroundColorPicker.AvailableColors       = BorderColorPicker.AvailableColors = TextColorPicker.AvailableColors = available;
            BackgroundColorPicker.StandardColorsHeader  = BorderColorPicker.StandardColorsHeader = TextColorPicker.StandardColorsHeader = L10n.Message("Standard colors");
            BackgroundColorPicker.StandardColors        = BorderColorPicker.StandardColors = TextColorPicker.StandardColors = standard;
            BackgroundColorPicker.RecentColorsHeader    = BorderColorPicker.RecentColorsHeader = TextColorPicker.RecentColorsHeader = L10n.Message("Recent colors");
            BackgroundColorPicker.RecentColors          = BorderColorPicker.RecentColors = TextColorPicker.RecentColors = PersistentRecentColors;
            BackgroundColorPicker.AdvancedButtonHeader  = BorderColorPicker.AdvancedButtonHeader = TextColorPicker.AdvancedButtonHeader = L10n.Message("Custom", "color");
            BackgroundColorPicker.StandardButtonHeader  = BorderColorPicker.StandardButtonHeader = TextColorPicker.StandardButtonHeader = L10n.Message("Standard", "color");
        }
 public string GetCharacterName()
 {
     return(tbCharName.Text == L10n.Message("CharacterName") ? null : tbCharName.Text);
 }
 public static Task ShowErrorAsync(this MetroWindow window, string message, string details = null, string title = null)
 {
     return(ShowAsync(window, message, details, title ?? L10n.Message("Error"), MessageBoxButton.OK, MessageBoxImage.Error));
 }
 public string GetAccountName()
 {
     return(tbAccName.Text == L10n.Message("AccountName") ? null : tbAccName.Text);
 }
Пример #24
0
        public async Task InitializeAsync(IDialogCoordinator dialogCoordinator)
        {
            DialogCoordinator = dialogCoordinator;
            if (PersistentData.Options.BuildsSavePath == null)
            {
                if (AppData.IsPortable)
                {
                    PersistentData.Options.BuildsSavePath = AppData.GetFolder("Builds");
                }
                else
                {
                    // Ask user for path. Default: AppData.GetFolder("Builds")
                    var dialogSettings = new FileSelectorDialogSettings
                    {
                        DefaultPath       = AppData.GetFolder("Builds"),
                        IsFolderPicker    = true,
                        ValidationSubPath = GetLongestRequiredSubpath(),
                        IsCancelable      = false
                    };
                    if (!DeserializesBuildsSavePath)
                    {
                        dialogSettings.AdditionalValidationFunc =
                            path => Directory.Exists(path) && Directory.EnumerateFileSystemEntries(path).Any()
                                ? L10n.Message("Directory must be empty.")
                                : null;
                    }
                    PersistentData.Options.BuildsSavePath = await dialogCoordinator.ShowFileSelectorAsync(PersistentData,
                                                                                                          L10n.Message("Select build directory"),
                                                                                                          L10n.Message("Select the directory where builds will be stored.\n" +
                                                                                                                       "It will be created if it does not yet exist. You can change it in the settings later."),
                                                                                                          dialogSettings);
                }
            }
            Directory.CreateDirectory(PersistentData.Options.BuildsSavePath);
            await DeserializeAdditionalFilesAsync();

            PersistentData.EquipmentData = await DeserializeEquipmentData();

            PersistentData.StashItems.AddRange(await DeserializeStashItemsAsync());
        }
Пример #25
0
 // Displays generic Yes/No question message box.
 public static MessageBoxResult Ask(string message, MessageBoxImage icon = MessageBoxImage.Question)
 {
     return(MetroMessageBox.Show(GetActiveWindow(), message, L10n.Message("Question"), MessageBoxButton.YesNo, icon));
 }
Пример #26
0
        private async Task SaveBuildAs(BuildViewModel vm)
        {
            var build = vm.Build;
            var name  = await _dialogCoordinator.ShowValidatingInputDialogAsync(this, L10n.Message("Save as"),
                                                                                L10n.Message("Enter the new name of the build"), build.Name, s => _buildValidator.ValidateNewBuildName(s, vm.Parent));

            if (string.IsNullOrWhiteSpace(name))
            {
                return;
            }
            var newBuild = build.DeepClone();

            newBuild.Name = name;
            var newVm = new BuildViewModel(newBuild, Filter);

            var builds = vm.Parent.Children;

            if (build.CanRevert)
            {
                // The original build exists in the file system.
                build.RevertChanges();
                builds.Insert(builds.IndexOf(vm), newVm);
            }
            else
            {
                // The original build does not exist in the file system
                // It will be replaced by the new one.
                var i = builds.IndexOf(vm);
                builds.RemoveAt(i);
                builds.Insert(i, newVm);
            }

            CurrentBuild = newVm;
            await SaveBuild(newVm);
        }
Пример #27
0
 public AutomatedTabViewModel(SkillTree tree)
     : base(tree)
 {
     DisplayName = L10n.Message("Automated");
 }