Esempio n. 1
0
        /// <summary>Get the mod info for an update key.</summary>
        /// <param name="updateKey">The namespaced update key.</param>
        private async Task <ModInfoModel> GetInfoForUpdateKeyAsync(string updateKey)
        {
            // parse update key
            UpdateKey parsed = UpdateKey.Parse(updateKey);

            if (!parsed.LooksValid)
            {
                return(new ModInfoModel($"The update key '{updateKey}' isn't in a valid format. It should contain the site key and mod ID like 'Nexus:541'."));
            }

            // get matching repository
            if (!this.Repositories.TryGetValue(parsed.Repository, out IModRepository repository))
            {
                return(new ModInfoModel($"There's no mod site with key '{parsed.Repository}'. Expected one of [{string.Join(", ", this.Repositories.Keys)}]."));
            }

            // fetch mod info
            return(await this.Cache.GetOrCreateAsync($"{repository.VendorKey}:{parsed.ID}".ToLower(), async entry =>
            {
                ModInfoModel result = await repository.GetModInfoAsync(parsed.ID);
                if (result.Error == null)
                {
                    if (result.Version == null)
                    {
                        result.Error = $"The update key '{updateKey}' matches a mod with no version number.";
                    }
                    else if (!Regex.IsMatch(result.Version, this.VersionRegex, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase))
                    {
                        result.Error = $"The update key '{updateKey}' matches a mod with invalid semantic version '{result.Version}'.";
                    }
                }
                entry.AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(result.Error == null ? this.SuccessCacheMinutes : this.ErrorCacheMinutes);
                return result;
            }));
        }
Esempio n. 2
0
        /// <summary>Get the mod info for an update key.</summary>
        /// <param name="updateKey">The namespaced update key.</param>
        private async Task <ModInfoModel> GetInfoForUpdateKeyAsync(UpdateKey updateKey)
        {
            // get mod
            if (!this.ModCache.TryGetMod(updateKey.Repository, updateKey.ID, out CachedMod mod) || this.ModCache.IsStale(mod.LastUpdated, mod.FetchStatus == RemoteModStatus.TemporaryError ? this.ErrorCacheMinutes : this.SuccessCacheMinutes))
            {
                // get site
                if (!this.Repositories.TryGetValue(updateKey.Repository, out IModRepository repository))
                {
                    return(new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, $"There's no mod site with key '{updateKey.Repository}'. Expected one of [{string.Join(", ", this.Repositories.Keys)}]."));
                }

                // fetch mod
                ModInfoModel result = await repository.GetModInfoAsync(updateKey.ID);

                if (result.Error == null)
                {
                    if (result.Version == null)
                    {
                        result.SetError(RemoteModStatus.InvalidData, $"The update key '{updateKey}' matches a mod with no version number.");
                    }
                    else if (!SemanticVersion.TryParse(result.Version, out _))
                    {
                        result.SetError(RemoteModStatus.InvalidData, $"The update key '{updateKey}' matches a mod with invalid semantic version '{result.Version}'.");
                    }
                }

                // cache mod
                this.ModCache.SaveMod(repository.VendorKey, updateKey.ID, result, out mod);
            }
            return(mod.GetModel());
        }
Esempio n. 3
0
        /// <summary>Get the mod info for an update key.</summary>
        /// <param name="updateKey">The namespaced update key.</param>
        /// <param name="allowNonStandardVersions">Whether to allow non-standard versions.</param>
        /// <param name="mapRemoteVersions">Maps remote versions to a semantic version for update checks.</param>
        private async Task <ModInfoModel> GetInfoForUpdateKeyAsync(UpdateKey updateKey, bool allowNonStandardVersions, IDictionary <string, string> mapRemoteVersions)
        {
            // get mod page
            IModPage page;

            {
                bool isCached =
                    this.ModCache.TryGetMod(updateKey.Site, updateKey.ID, out Cached <IModPage> cachedMod) &&
                    !this.ModCache.IsStale(cachedMod.LastUpdated, cachedMod.Data.Status == RemoteModStatus.TemporaryError ? this.Config.Value.ErrorCacheMinutes : this.Config.Value.SuccessCacheMinutes);

                if (isCached)
                {
                    page = cachedMod.Data;
                }
                else
                {
                    page = await this.ModSites.GetModPageAsync(updateKey);

                    this.ModCache.SaveMod(updateKey.Site, updateKey.ID, page);
                }
            }

            // get version info
            return(this.ModSites.GetPageVersions(page, updateKey.Subkey, allowNonStandardVersions, mapRemoteVersions));
        }
Esempio n. 4
0
        public void UpdateExisting()
        {
            var updateStrategy = new UpdateKey <string, string>();

            using (var blocks = CreateBlocks(true))
            {
                var gist = CreateGist(blocks, updateStrategy);
                gist.Insert("A", "value for A");
                blocks.AutoCommit = true;
            }
            using (var blocks = CreateBlocks(true))
            {
                var gist = CreateGist(blocks, updateStrategy);
                gist.Insert("A", "new value for A");
                blocks.AutoCommit = true;
            }

            using (var blocks = CreateBlocks(false))
            {
                var gist = CreateGist(blocks, updateStrategy);

                CollectionAssert.AreEqual(new[] { "A" }, gist.Scan().Select(kv => kv.Key).ToArray());
                CollectionAssert.AreEqual(new[] { "new value for A" }, gist.Scan().Select(kv => kv.Value).ToArray());
            }
        }
        /// <summary>Get update keys based on the available mod metadata, while maintaining the precedence order.</summary>
        /// <param name="specifiedKeys">The specified update keys.</param>
        /// <param name="record">The mod's entry in SMAPI's internal database.</param>
        /// <param name="entry">The mod's entry in the wiki list.</param>
        private IEnumerable <UpdateKey> GetUpdateKeys(string[] specifiedKeys, ModDataRecord record, WikiModEntry entry)
        {
            IEnumerable <string> GetRaw()
            {
                // specified update keys
                if (specifiedKeys != null)
                {
                    foreach (string key in specifiedKeys)
                    {
                        yield return(key?.Trim());
                    }
                }

                // default update key
                string defaultKey = record?.GetDefaultUpdateKey();

                if (defaultKey != null)
                {
                    yield return(defaultKey);
                }

                // wiki metadata
                if (entry != null)
                {
                    if (entry.NexusID.HasValue)
                    {
                        yield return($"{ModRepositoryKey.Nexus}:{entry.NexusID}");
                    }
                    if (entry.ModDropID.HasValue)
                    {
                        yield return($"{ModRepositoryKey.ModDrop}:{entry.ModDropID}");
                    }
                    if (entry.CurseForgeID.HasValue)
                    {
                        yield return($"{ModRepositoryKey.CurseForge}:{entry.CurseForgeID}");
                    }
                    if (entry.ChucklefishID.HasValue)
                    {
                        yield return($"{ModRepositoryKey.Chucklefish}:{entry.ChucklefishID}");
                    }
                }
            }

            HashSet <UpdateKey> seen = new HashSet <UpdateKey>();

            foreach (string rawKey in GetRaw())
            {
                if (string.IsNullOrWhiteSpace(rawKey))
                {
                    continue;
                }

                UpdateKey key = UpdateKey.Parse(rawKey);
                if (seen.Add(key))
                {
                    yield return(key);
                }
            }
        }
Esempio n. 6
0
 /// <inheritdoc />
 public IEnumerable <UpdateKey> GetUpdateKeys(bool validOnly = false)
 {
     foreach (string rawKey in this.Manifest?.UpdateKeys ?? new string[0])
     {
         UpdateKey updateKey = UpdateKey.Parse(rawKey);
         if (updateKey.LooksValid || !validOnly)
         {
             yield return(updateKey);
         }
     }
 }
Esempio n. 7
0
        /// <summary>Get every available update key based on the available mod metadata, including duplicates and keys which should be filtered.</summary>
        /// <param name="specifiedKeys">The specified update keys.</param>
        /// <param name="record">The mod's entry in SMAPI's internal database.</param>
        /// <param name="entry">The mod's entry in the wiki list.</param>
        private IEnumerable <string> GetUnfilteredUpdateKeys(string[] specifiedKeys, ModDataRecord record, WikiModEntry entry)
        {
            // specified update keys
            foreach (string key in specifiedKeys ?? Array.Empty <string>())
            {
                if (!string.IsNullOrWhiteSpace(key))
                {
                    yield return(key.Trim());
                }
            }

            // default update key
            {
                string defaultKey = record?.GetDefaultUpdateKey();
                if (!string.IsNullOrWhiteSpace(defaultKey))
                {
                    yield return(defaultKey);
                }
            }

            // wiki metadata
            if (entry != null)
            {
                if (entry.NexusID.HasValue)
                {
                    yield return(UpdateKey.GetString(ModSiteKey.Nexus, entry.NexusID.ToString()));
                }
                if (entry.ModDropID.HasValue)
                {
                    yield return(UpdateKey.GetString(ModSiteKey.ModDrop, entry.ModDropID.ToString()));
                }
                if (entry.CurseForgeID.HasValue)
                {
                    yield return(UpdateKey.GetString(ModSiteKey.CurseForge, entry.CurseForgeID.ToString()));
                }
                if (entry.ChucklefishID.HasValue)
                {
                    yield return(UpdateKey.GetString(ModSiteKey.Chucklefish, entry.ChucklefishID.ToString()));
                }
            }

            // overrides from wiki
            foreach (string key in entry?.ChangeUpdateKeys ?? Array.Empty <string>())
            {
                if (key.StartsWith('+'))
                {
                    yield return(key.Substring(1));
                }
                else if (!key.StartsWith("-"))
                {
                    yield return(key);
                }
            }
        }
        public void BatchUpdateExisting()
        {
            var updateStrategy = new UpdateKey<string, string>();
            using (var blocks = CreateBlocks(true))
            {
                var gist = CreateGist(blocks, updateStrategy);

                gist.Insert("A", "value for A");
                gist.Insert("A", "new value for A");

                CollectionAssert.AreEqual(new[] {"A"}, gist.Scan().Select(kv => kv.Key).ToArray());
                CollectionAssert.AreEqual(new[] {"new value for A"}, gist.Scan().Select(kv => kv.Value).ToArray());
            }
        }
Esempio n. 9
0
    private void Signal_TreeButtonPressed(TreeItem item, int column, int id)
    {
        if (id == REMOVE_BUTTON_INDEX)
        {
            pendingRemoval = item;
            var confirm = GetNode <ConfirmationDialog>("PendingRemovalDialog");
            confirm.PopupCenteredClamped();
        }
        else if (id == ADD_BUTTON_INDEX)
        {
            if (item == depsRoot)
            {
                Dependency dep;
                ModProject.Dependencies.Add(dep = new Dependency()
                {
                    UniqueID = "mod.id"
                });

                var depItem = ProjectTree.CreateItem(depsRoot);
                depItem.SetText(0, dep.UniqueID);
                depItem.AddButton(0, RemoveIcon, REMOVE_BUTTON_INDEX, tooltip: "Remove this dependency");
                deps.Add(depItem, dep);
            }
            else if (item == updateKeysRoot)
            {
                UpdateKey updateKey;
                ModProject.UpdateKeys.Add(updateKey = new UpdateKey()
                {
                    Platform = "Nexus"
                });

                var updateKeyItem = ProjectTree.CreateItem(updateKeysRoot);
                updateKeyItem.SetText(0, "Nexus:");
                updateKeyItem.AddButton(0, RemoveIcon, REMOVE_BUTTON_INDEX, tooltip: "Remove this update key");
                updateKeys.Add(updateKeyItem, updateKey);
            }
            else if (item == resourcesRoot)
            {
                var import = GetNode <FileDialog>("ResourceImportDialog");
                import.PopupCenteredClamped();
            }
            else if (item.GetMeta(Meta.CorrespondingController) != null)
            {
                var controller = ContentPackController.GetControllerForMod((string)item.GetParent().GetMeta(Meta.CorrespondingController));
                var data       = ModProject.Mods.Find(md => md.ContentPackFor == controller.ModUniqueId);
                controller.OnAdded(this, data, item);
            }
        }
    }
Esempio n. 10
0
        /// <summary>Get an update URL for an update key (if valid).</summary>
        /// <param name="updateKey">The update key.</param>
        public string GetUpdateUrl(string updateKey)
        {
            UpdateKey parsed = UpdateKey.Parse(updateKey);

            if (!parsed.LooksValid)
            {
                return(null);
            }

            if (this.VendorModUrls.TryGetValue(parsed.Site, out string urlTemplate))
            {
                return(string.Format(urlTemplate, parsed.ID));
            }

            return(null);
        }
Esempio n. 11
0
        /// <inheritdoc />
        public IEnumerable <UpdateKey> GetUpdateKeys(bool validOnly = false)
        {
            if (!this.HasManifest())
            {
                yield break;
            }

            foreach (string rawKey in this.Manifest.UpdateKeys)
            {
                UpdateKey updateKey = UpdateKey.Parse(rawKey);
                if (updateKey.LooksValid || !validOnly)
                {
                    yield return(updateKey);
                }
            }
        }
Esempio n. 12
0
        /// <summary>Parse valid mod data override entries.</summary>
        /// <param name="nodes">The HTML mod data override entries.</param>
        private IEnumerable <WikiDataOverrideEntry> ParseOverrideEntries(IEnumerable <HtmlNode> nodes)
        {
            foreach (HtmlNode node in nodes)
            {
                yield return(new WikiDataOverrideEntry
                {
                    Ids = this.GetAttributeAsCsv(node, "data-id"),
                    ChangeLocalVersions = this.GetAttributeAsChangeDescriptor(node, "data-local-version",
                                                                              raw => SemanticVersion.TryParse(raw, out ISemanticVersion version) ? version.ToString() : raw
                                                                              ),
                    ChangeRemoteVersions = this.GetAttributeAsChangeDescriptor(node, "data-remote-version",
                                                                               raw => SemanticVersion.TryParse(raw, out ISemanticVersion version) ? version.ToString() : raw
                                                                               ),

                    ChangeUpdateKeys = this.GetAttributeAsChangeDescriptor(node, "data-update-keys",
                                                                           raw => UpdateKey.TryParse(raw, out UpdateKey key) ? key.ToString() : raw
                                                                           )
                });
Esempio n. 13
0
        /// <summary>Get update keys based on the available mod metadata, while maintaining the precedence order.</summary>
        /// <param name="specifiedKeys">The specified update keys.</param>
        /// <param name="record">The mod's entry in SMAPI's internal database.</param>
        /// <param name="entry">The mod's entry in the wiki list.</param>
        private IEnumerable <UpdateKey> GetUpdateKeys(string[] specifiedKeys, ModDataRecord record, WikiModEntry entry)
        {
            // get unique update keys
            List <UpdateKey> updateKeys = this.GetUnfilteredUpdateKeys(specifiedKeys, record, entry)
                                          .Select(UpdateKey.Parse)
                                          .Distinct()
                                          .ToList();

            // apply remove overrides from wiki
            {
                var removeKeys = new HashSet <UpdateKey>(
                    from key in entry?.ChangeUpdateKeys ?? new string[0]
                    where key.StartsWith('-')
                    select UpdateKey.Parse(key.Substring(1))
                    );
                if (removeKeys.Any())
                {
                    updateKeys.RemoveAll(removeKeys.Contains);
                }
            }

            // if the list has both an update key (like "Nexus:2400") and subkey (like "Nexus:2400@subkey") for the same page, the subkey takes priority
            {
                var removeKeys = new HashSet <UpdateKey>();
                foreach (var key in updateKeys)
                {
                    if (key.Subkey != null)
                    {
                        removeKeys.Add(new UpdateKey(key.Site, key.ID, null));
                    }
                }
                if (removeKeys.Any())
                {
                    updateKeys.RemoveAll(removeKeys.Contains);
                }
            }

            return(updateKeys);
        }
Esempio n. 14
0
        /// <summary>Get the mod info for an update key.</summary>
        /// <param name="updateKey">The namespaced update key.</param>
        public async Task <IModPage> GetModPageAsync(UpdateKey updateKey)
        {
            // get site
            if (!this.ModSites.TryGetValue(updateKey.Site, out IModSiteClient client))
            {
                return(new GenericModPage(updateKey.Site, updateKey.ID).SetError(RemoteModStatus.DoesNotExist, $"There's no mod site with key '{updateKey.Site}'. Expected one of [{string.Join(", ", this.ModSites.Keys)}]."));
            }

            // fetch mod
            IModPage mod;

            try
            {
                mod = await client.GetModData(updateKey.ID);
            }
            catch (Exception ex)
            {
                mod = new GenericModPage(updateKey.Site, updateKey.ID).SetError(RemoteModStatus.TemporaryError, ex.ToString());
            }

            // handle errors
            return(mod ?? new GenericModPage(updateKey.Site, updateKey.ID).SetError(RemoteModStatus.DoesNotExist, $"Found no {updateKey.Site} mod with ID '{updateKey.ID}'."));
        }
Esempio n. 15
0
 static UpdateStrategy()
 {
     UniqueKey = new UniqueKey <TKey, TValue>();
     UpdateKey = new UpdateKey <TKey, TValue>();
     AppendKey = new AppendKey <TKey, TValue>();
 }
        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.DeletePrivateNameTextBox.Text != "" && this.DeleteKeyTextBox.Text != "")
            {
                MessageBox.Show("please enter only one field, byname or by key.");
                UpdateKey.Clear();
                UpdatePrivateNameTextBox.Clear();
                DeleteKeyTextBox.Clear();
                DeletePrivateNameTextBox.Clear();
                //Window UpdateDeleteByWindow = new updeletebyunit(username);
                //UpdateDeleteByWindow.Show();
                //this.Close();
            }

            else if (this.DeletePrivateNameTextBox.Text != "")
            {
                try
                {
                    unit = bl.GetHostingUnitByName(this.DeletePrivateNameTextBox.Text);
                    long tempkey = unit.HostingUnitKey1;
                    bl.DeleteHostingUnit(unit);
                    MessageBox.Show("Unit deleted, Key: " + tempkey);
                    Window GuestRequestWindow = new HostWindow(username);
                    GuestRequestWindow.Show();
                    this.Close();
                }
                catch (Exception exx)
                {
                    if (exx.Message.Contains(':'))
                    {
                        MessageBox.Show("unit does not exist or " + exx.Message.Substring(exx.Message.IndexOf(':')));
                    }
                    else
                    {
                        MessageBox.Show("unit does not exist or " + exx.Message);
                    }
                    Window GuestRequestWindow = new HostWindow(username);
                    GuestRequestWindow.Show();
                    this.Close();
                }
            }
            else if (this.DeleteKeyTextBox.Text != "")
            {
                try
                {
                    unit = bl.GetHostingUnitByKey(long.Parse(this.DeleteKeyTextBox.Text));
                    long tempkey = unit.HostingUnitKey1;
                    bl.DeleteHostingUnit(unit);
                    MessageBox.Show("unit deleted, Key: " + tempkey);
                    Window hostWindow = new HostWindow(username);
                    hostWindow.Show();
                    this.Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("unit does not exist");
                    Window GuestRequestWindow = new HostWindow(username);
                    GuestRequestWindow.Show();
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show("unit does not exist, " +
                                "or you entered info into wrong fields");
            }
        }
Esempio n. 17
0
 void IMasterApplicationSA.PersistNewUpdateKey(string username, User user, UpdateKey key)
 {
 }
Esempio n. 18
0
    public UpdateInforResponseData UpdateOperation(BinaryReader reader)
    {
        List <PlayerProp>                playerPropsList  = new List <PlayerProp>();
        List <ItemInventory>             newItemsList     = new List <ItemInventory>();
        List <ItemMoveVo>                itemMoveOps      = new List <ItemMoveVo>();
        List <ItemCountVo>               itemCountOps     = new List <ItemCountVo>();
        List <ItemAttributeUpdateVoList> itemAttributeOps = new List <ItemAttributeUpdateVoList>();
        List <TattooEquipVo>             tattooOpList     = new List <TattooEquipVo>();
        List <ItemInventory>             updateItemList   = new List <ItemInventory>();

        //parse and save first,update later.
        int changeCount = reader.ReadInt16();

        for (int index = 0; index < changeCount; index++)
        {
            UpdateKey uk = (UpdateKey)reader.ReadByte();
            switch (uk)
            {
            case UpdateKey.RoleProp:    //section 1
                int propmask = reader.ReadInt32();
                for (int key = 0; key < 32; key++)
                {
                    if ((propmask & (1 << key)) != 0)
                    {
                        playerPropsList.Add(new PlayerProp((PlayerPropKey)key, reader.ReadInt32()));
                    }
                }
                break;

            case UpdateKey.RolePropBattle:    //section 2
                int propmaskBattle = reader.ReadInt32();
                for (int key = 0; key < 32; key++)
                {
                    if ((propmaskBattle & (1 << key)) != 0)
                    {
                        playerPropsList.Add(new PlayerProp((PlayerPropKey)key + 32, reader.ReadInt32()));
                    }
                }
                break;

            case UpdateKey.ItemMove:
                itemMoveOps.Add(new ItemMoveVo(reader.ReadInt64(),
                                               (ItemMoveType)reader.ReadByte()));
                break;

            case UpdateKey.ItemCount:
                ItemCountVo iv = new ItemCountVo(reader.ReadInt64(), reader.ReadInt16());
                itemCountOps.Add(iv);

                if (iv.ItemCount > 0)
                {
                    ItemInventory ii = PlayerInfo.Instance.PlayerInventory.GetItem(iv.ItemGuid);
                    updateItemList.Add(ii);
                }
                break;

            case UpdateKey.ItemNew:
                ItemInventory itemInventory = new ItemInventory();
                itemInventory.Parse(reader);
                itemInventory.IsNew = true;
                newItemsList.Add(itemInventory);

                updateItemList.Add(itemInventory);
                break;

            case UpdateKey.ItemPropUpdate:
                Int64 itemGUID = reader.ReadInt64();
                List <ItemAttributeUpdateVo> list = new List <ItemAttributeUpdateVo>();
                byte changeAttributesCount        = reader.ReadByte();
                for (int i = 0; i < changeAttributesCount; i++)
                {
                    list.Add(new ItemAttributeUpdateVo((FC_EQUIP_EXTEND_ATTRIBUTE)reader.ReadInt32(), reader.ReadInt32()));
                }
                itemAttributeOps.Add(new ItemAttributeUpdateVoList(itemGUID, list.ToArray()));
                break;

            case UpdateKey.Tattoo:
                EnumTattooPart part = (EnumTattooPart)reader.ReadByte();

                long itemGUID2 = reader.ReadInt64();

                byte op = reader.ReadByte();

                tattooOpList.Add(new TattooEquipVo(itemGUID2, part, op));

                break;
            }
        }

        UpdateInforResponseData data = new UpdateInforResponseData();

        data.itemCountOps     = itemCountOps;
        data.itemMoveOps      = itemMoveOps;
        data.newItemsList     = newItemsList;
        data.playerPropsList  = playerPropsList;
        data.itemAttributeOps = itemAttributeOps;
        data.tattooOpList     = tattooOpList;
        data.itemUpdateList   = updateItemList;
        return(data);
    }
Esempio n. 19
0
    private void Signal_ImportPack(string file)
    {
        var manifest = JsonConvert.DeserializeObject <ExportManifest>(System.IO.File.ReadAllText(file));

        ContentPackController matchingController = null;

        foreach (var controller in ContentPackController.GetRegisteredControllerTypes())
        {
            if (controller == manifest.ContentPackFor.UniqueID)
            {
                matchingController = ContentPackController.GetControllerForMod(manifest.ContentPackFor.UniqueID);
            }
        }

        if (matchingController == null)
        {
            GetNode <AcceptDialog>("UnsupportedPackTypeDialog").PopupCenteredClamped();
            return;
        }

        foreach (var updateKey in manifest.UpdateKeys)
        {
            int    colon       = updateKey.IndexOf(':');
            string keyPlatform = updateKey.Substring(0, colon);
            string keyId       = updateKey.Substring(colon + 1);
            if (ModProject.UpdateKeys.Find(uk => uk.Platform == keyPlatform) == null)
            {
                var uk = new UpdateKey()
                {
                    Platform = keyPlatform, Id = keyId
                };
                ModProject.UpdateKeys.Add(uk);

                var updateKeyItem = ProjectTree.CreateItem(updateKeysRoot);
                updateKeyItem.SetText(0, updateKey);
                updateKeyItem.AddButton(0, RemoveIcon, REMOVE_BUTTON_INDEX, tooltip: "Remove this update key");
                updateKeys.Add(updateKeyItem, uk);
            }
        }

        foreach (var dep in manifest.Dependencies)
        {
            if (ModProject.Dependencies.Find(d => d.UniqueID == dep.UniqueID) == null)
            {
                ModProject.Dependencies.Add(dep);

                var depItem = ProjectTree.CreateItem(depsRoot);
                depItem.SetText(0, dep.UniqueID);
                depItem.AddButton(0, RemoveIcon, REMOVE_BUTTON_INDEX, tooltip: "Remove this dependency");
                deps.Add(depItem, dep);
            }
        }

        var existingMod = ModProject.Mods.Find(md => md.ContentPackFor == matchingController.ModUniqueId);

        if (existingMod == null)
        {
            var mod = ProjectTree.CreateItem(ProjectRoot);
            mod.SetText(0, $"[{matchingController.ModAbbreviation}] {ModProject.Name}");
            mod.AddButton(0, RemoveIcon, REMOVE_BUTTON_INDEX, tooltip: "Remove this mod");
            mod.SetMeta(Meta.CorrespondingController, matchingController.ModUniqueId);
            ModProject.Mods.Add(existingMod = matchingController.OnModCreated(this, mod));
        }
        matchingController.OnImport(this, existingMod, System.IO.Path.GetDirectoryName(file));
    }
Esempio n. 20
0
        static int Main(string[] args)
        {
            var application = new MasterApplicatonSA();

            IDNP3Manager mgr = DNP3ManagerFactory.CreateManager();

            Console.WriteLine(String.Format("Crypto: {0}", mgr.SSLVersion()));


            mgr.AddLogHandler(PrintingLogAdapter.Instance); //this is optional
            var channel = mgr.AddTCPClient("client", LogLevels.NORMAL, ChannelRetry.Default, "127.0.0.1", 20000);

            //optionally, add a listener for the channel state
            channel.AddStateListener(state => Console.WriteLine("channel state: " + state));

            var config = new MasterStackConfig();

            //setup your stack configuration here.
            config.link.localAddr  = 1;
            config.link.remoteAddr = 10;

            var master = channel.AddMasterSA("master", PrintingSOEHandler.Instance, application, config);

            // define users on the master
            master.AddUser(User.Default, UpdateKey.Demo(0xFF, KeyWrapAlgorithm.AES_128));

            // you a can optionally add various kinds of polls
            var integrityPoll = master.AddClassScan(ClassField.AllClasses, TimeSpan.FromMinutes(1), TaskConfig.Default);
            var rangePoll     = master.AddRangeScan(30, 2, 5, 7, TimeSpan.FromSeconds(20), TaskConfig.Default);
            var classPoll     = master.AddClassScan(ClassField.AllEventClasses, TimeSpan.FromSeconds(5), TaskConfig.Default);

            /* you can also do very custom scans
             * var headers = new Header[] { Header.Range8(1, 2, 7, 8), Header.Count8(2, 3, 7) };
             * var weirdPoll = master.AddScan(headers, TimeSpan.FromSeconds(20));
             */

            master.Enable(); // enable communications

            Console.WriteLine("Enter a command");

            while (true)
            {
                switch (Console.ReadLine())
                {
                case "a":
                    // perform an ad-hoc scan of all analogs
                    master.ScanAllObjects(30, 0, TaskConfig.Default);
                    break;

                case "c":
                    var crob     = new ControlRelayOutputBlock(ControlCode.PULSE_ON, 1, 100, 100);
                    var commands = CommandHeader.From(IndexedValue.From(crob, 0));
                    var task     = master.SelectAndOperate(commands, TaskConfig.With(User.Default));
                    task.ContinueWith((result) => Console.WriteLine("Result: " + result.Result));
                    break;

                case "l":
                    // add interpretation to the current logging level
                    var filters = channel.GetLogFilters();
                    channel.SetLogFilters(filters.Add(LogFilters.TRANSPORT_TX | LogFilters.TRANSPORT_RX));
                    break;

                case "i":
                    integrityPoll.Demand();
                    break;

                case "r":
                    rangePoll.Demand();
                    break;

                case "e":
                    classPoll.Demand();
                    break;

                case "x":
                    return(0);

                default:
                    break;
                }
            }
        }