Esempio n. 1
0
 public Contribution load(Plugin owner, XmlElement e)
 {
     if (e.SelectSingleNode("class") == null)
     {
         // default to ParamTrainImpl
         return(new ParamTrainImpl(e));
     }
     else
     {
         // use the class element
         return((Contribution)PluginUtil.loadObjectFromManifest(e));
     }
 }
        public static MethodBase TargetTMPEMethod <T>()
        {
            string typeName   = "TrafficManager.Custom.AI.Custom" + typeof(T);
            Type   customType =
                PluginUtil.GetTrafficManager().GetMainAssembly()
                .GetType(typeName, throwOnError: false);

            if (customType != null)
            {
                return(DeclaredMethod <SimulationStepDelegate>(customType, "CustomSimulationStep"));
            }
            return(null);
        }
        /// <summary>
        /// Parses a structure contribution from a DOM node.
        /// </summary>
        /// <exception cref="XmlException">If the parsing fails</exception>
        protected FixedSizeStructureContribution(XmlElement e) : base(e)
        {
            _price = int.Parse(XmlUtil.selectSingleNode(e, "price").InnerText);

            SIZE sz     = XmlUtil.parseSize(XmlUtil.selectSingleNode(e, "size").InnerText);
            int  height = int.Parse(XmlUtil.selectSingleNode(e, "height").InnerText);

            this.size = new Distance(sz, height);
            _ppa      = _price / Math.Max(1, size.x * size.y);
            XmlElement spr = (XmlElement)XmlUtil.selectSingleNode(e, "sprite");

            sprites = PluginUtil.getSpriteLoader(spr).load3D(spr, size.x, size.y, height);
        }
Esempio n. 4
0
        /// <summary>
        /// Normalizes path separator for server and local paths.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="pathSeparator"></param>
        /// <param name="altPathSeparator"></param>
        /// <returns></returns>
        public string NormalizeRelativePath(string path, char pathSeparator, char altPathSeparator)
        {
            string relativePath = (path ?? string.Empty).Replace(altPathSeparator, pathSeparator);

            relativePath = relativePath.Trim(pathSeparator, ' ');

            if (relativePath.Contains(":") || relativePath.Contains(".."))
            {
                throw new Exception(PluginUtil.Loc("SvnIncorrectRelativePath", relativePath));
            }

            return(relativePath);
        }
Esempio n. 5
0
        private async Task <string> RunPorcelainCommandAsync(params string[] args)
        {
            // Validation.
            PluginUtil.NotNull(args, nameof(args));
            PluginUtil.NotNull(_context, nameof(_context));

            // Invoke tf.
            var processInvoker = new ProcessInvoker(_context);
            var output         = new List <string>();
            var outputLock     = new object();

            processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
            {
                lock (outputLock)
                {
                    _context.Debug(e.Data);
                    output.Add(e.Data);
                }
            };
            processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
            {
                lock (outputLock)
                {
                    _context.Debug(e.Data);
                    output.Add(e.Data);
                }
            };
            string arguments = FormatArgumentsWithDefaults(args);

            _context.Debug($@"{_svn} {arguments}");
            // TODO: Test whether the output encoding needs to be specified on a non-Latin OS.
            try
            {
                await processInvoker.ExecuteAsync(
                    workingDirectory : _context.Variables.GetValueOrDefault("agent.workfolder")?.Value,
                    fileName : _svn,
                    arguments : arguments,
                    environment : null,
                    requireExitCodeZero : true,
                    cancellationToken : _cancellationToken);
            }
            catch (ProcessExitCodeException)
            {
                // The command failed. Dump the output and throw.
                output.ForEach(x => _context.Output(x ?? string.Empty));
                throw;
            }

            // Note, string.join gracefully handles a null element within the IEnumerable<string>.
            return(string.Join(Environment.NewLine, output));
        }
        public Contribution load(Plugin owner, XmlElement e)
        {
            BGMFactoryContribution contrib =
                (BGMFactoryContribution)PluginUtil.loadObjectFromManifest(e);

            // let the factory load BGMs
            foreach (BGMContribution bgm in contrib.listContributions())
            {
                owner.contributions.Add(bgm);
                bgm.init(owner, new Uri(owner.dirName));
            }

            return(contrib);
        }
Esempio n. 7
0
        /// <summary>
        /// 安装/更新
        /// </summary>
        public void Install_POST()
        {
            string url    = base.Request["url"];
            bool   result = PluginUtil.InstallPlugin(url, null);

            if (result)
            {
                base.RenderSuccess();
            }
            else
            {
                base.RenderError("升级失败!");
            }
        }
Esempio n. 8
0
        /// <summary>
        /// 安装/更新
        /// </summary>
        public void Install_POST()
        {
            string url    = Request.Query("url");
            var    result = PluginUtil.InstallPlugin(url, null);

            if (result)
            {
                RenderSuccess();
            }
            else
            {
                RenderError("升级失败!");
            }
        }
Esempio n. 9
0
 public static void Preload()
 {
     try {
         Log.Info("LifeCycle.Preload() called");
         PluginUtil.LogPlugins();
         if (!preloadPatchesApplied_)
         {
             HarmonyUtil.InstallHarmony <PreloadPatchAttribute>(HARMONY_ID_MANUAL);
             preloadPatchesApplied_ = true;
         }
     } catch (Exception ex) {
         Log.Exception(ex);
     }
 }
Esempio n. 10
0
        public void Uninstall_POST()
        {
            string workIndent = base.Request["worker_indent"];
            bool   result     = PluginUtil.RemovePlugin(workIndent);

            if (result)
            {
                base.RenderSuccess();
            }
            else
            {
                base.RenderError("卸载失败!");
            }
        }
Esempio n. 11
0
        private void app_OnExtendModuleRequest(HttpContext t, ref bool b)
        {
            int siteId = CmsWebMaster.CurrentManageSite.SiteId;

            if (siteId <= 0)
            {
                b = false; return;
            }
            string filePath = PluginUtil.GetAttribute(this).WorkSpace + "site_" + siteId.ToString() + ".conf";

            t.Handler = new CollectionExtend(Collector.Create(filePath));
            t.Handler.ProcessRequest(t);
            b = true;
        }
Esempio n. 12
0
        /// <summary>
        /// 注册处理事件
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="reqHandler"></param>
        /// <param name="postReqHandler"></param>
        /// <returns></returns>
        public bool Register(IPlugin plugin, PluginHandler <TContext> getHandler, PluginHandler <TContext> postHandler)
        {
            Type type = plugin.GetType();
            PluginPackAttribute attr = PluginUtil.GetAttribute(plugin);
            string indent            = attr.WorkIndent;

            if (postHandler == null || postHandlers.Keys.Contains(indent))
            {
                return(false);
            }
            postHandlers.Add(indent, postHandler);

            return(base.Register(plugin, getHandler));
        }
Esempio n. 13
0
        public void Uninstall_POST()
        {
            string workIndent = Request.Query("worker_indent");
            var    result     = PluginUtil.RemovePlugin(workIndent);

            if (result)
            {
                RenderSuccess();
            }
            else
            {
                RenderError("卸载失败!");
            }
        }
Esempio n. 14
0
        protected async Task <TfsVCPorcelainCommandResult> TryRunPorcelainCommandAsync(FormatFlags formatFlags, params string[] args)
        {
            // Validation.
            PluginUtil.NotNull(args, nameof(args));
            PluginUtil.NotNull(ExecutionContext, nameof(ExecutionContext));

            // Invoke tf.
            var processInvoker = new ProcessInvoker(ExecutionContext);
            var result         = new TfsVCPorcelainCommandResult();
            var outputLock     = new object();

            processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
            {
                lock (outputLock)
                {
                    ExecutionContext.Debug(e.Data);
                    result.Output.Add(e.Data);
                }
            };
            processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
            {
                lock (outputLock)
                {
                    ExecutionContext.Debug(e.Data);
                    result.Output.Add(e.Data);
                }
            };
            string arguments = FormatArguments(formatFlags, args);

            ExecutionContext.Debug($@"tf {arguments}");
            // TODO: Test whether the output encoding needs to be specified on a non-Latin OS.
            try
            {
                await processInvoker.ExecuteAsync(
                    workingDirectory : SourcesDirectory,
                    fileName : "tf",
                    arguments : arguments,
                    environment : AdditionalEnvironmentVariables,
                    requireExitCodeZero : true,
                    outputEncoding : OutputEncoding,
                    cancellationToken : CancellationToken);
            }
            catch (ProcessExitCodeException ex)
            {
                result.Exception = ex;
            }

            return(result);
        }
Esempio n. 15
0
        public VssConnection InitializeVssConnection()
        {
            var headerValues = new List <ProductInfoHeaderValue>();

            headerValues.Add(new ProductInfoHeaderValue($"VstsAgentCore-Plugin", Variables.GetValueOrDefault("agent.version")?.Value ?? "Unknown"));
            headerValues.Add(new ProductInfoHeaderValue($"({RuntimeInformation.OSDescription.Trim()})"));

            if (VssClientHttpRequestSettings.Default.UserAgent != null && VssClientHttpRequestSettings.Default.UserAgent.Count > 0)
            {
                headerValues.AddRange(VssClientHttpRequestSettings.Default.UserAgent);
            }

            VssClientHttpRequestSettings.Default.UserAgent = headerValues;

            var certSetting = GetCertConfiguration();

            if (certSetting != null)
            {
                if (!string.IsNullOrEmpty(certSetting.ClientCertificateArchiveFile))
                {
                    VssClientHttpRequestSettings.Default.ClientCertificateManager = new CommandPluginClientCertificateManager(certSetting.ClientCertificateArchiveFile, certSetting.ClientCertificatePassword);
                }

                if (certSetting.SkipServerCertificateValidation)
                {
                    VssClientHttpRequestSettings.Default.ServerCertificateValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                }
            }

            var proxySetting = GetProxyConfiguration();

            if (proxySetting != null)
            {
                if (!string.IsNullOrEmpty(proxySetting.ProxyAddress))
                {
                    VssHttpMessageHandler.DefaultWebProxy = new CommandPluginWebProxy(proxySetting.ProxyAddress, proxySetting.ProxyUsername, proxySetting.ProxyPassword, proxySetting.ProxyBypassList);
                }
            }

            ServiceEndpoint systemConnection = this.Endpoints.FirstOrDefault(e => string.Equals(e.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));

            PluginUtil.NotNull(systemConnection, nameof(systemConnection));
            PluginUtil.NotNull(systemConnection.Url, nameof(systemConnection.Url));

            VssCredentials credentials = PluginUtil.GetVssCredential(systemConnection);

            PluginUtil.NotNull(credentials, nameof(credentials));
            return(PluginUtil.CreateConnection(systemConnection.Url, credentials));
        }
Esempio n. 16
0
        /// <summary>
        /// Finds a local path the provided server path is mapped to.
        /// </summary>
        /// <param name="serverPath"></param>
        /// <param name="rootPath"></param>
        /// <returns></returns>
        public string ResolveServerPath(string serverPath, string rootPath)
        {
            PluginUtil.Equal(true, serverPath.StartsWith(@"^/"), nameof(serverPath));

            foreach (string workingDirectoryPath in GetSvnWorkingCopyPaths(rootPath))
            {
                try
                {
                    _context.Debug($@"Get SVN info for the working directory path '{workingDirectoryPath}'.");
                    string xml = RunPorcelainCommandAsync(
                        "info",
                        workingDirectoryPath,
                        "--depth", "empty",
                        "--xml").GetAwaiter().GetResult();

                    // Deserialize the XML.
                    // The command returns a non-zero exit code if the local path is not a working copy.
                    // The assertions performed here should never fail.
                    XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo));
                    PluginUtil.NotNullOrEmpty(xml, nameof(xml));

                    using (StringReader reader = new StringReader(xml))
                    {
                        SvnInfo info = serializer.Deserialize(reader) as SvnInfo;
                        PluginUtil.NotNull(info, nameof(info));
                        PluginUtil.NotNull(info.Entries, nameof(info.Entries));
                        PluginUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length));

                        if (serverPath.Equals(info.Entries[0].RelativeUrl, StringComparison.Ordinal) || serverPath.StartsWith(info.Entries[0].RelativeUrl + '/', StringComparison.Ordinal))
                        {
                            // We've found the mapping the serverPath belongs to.
                            int    n            = info.Entries[0].RelativeUrl.Length;
                            string relativePath = serverPath.Length <= n + 1 ? string.Empty : serverPath.Substring(n + 1);

                            return(Path.Combine(workingDirectoryPath, relativePath));
                        }
                    }
                }
                catch (ProcessExitCodeException)
                {
                    _context.Debug($@"The path '{workingDirectoryPath}' is not an SVN working directory path.");
                }
            }

            _context.Debug($@"Haven't found any suitable mapping for '{serverPath}'");

            // Since the server path starts with the "^/" prefix we return the original path without these two characters.
            return(serverPath.Substring(2));
        }
Esempio n. 17
0
        static string GenerateID(XmlElement contrib)
        {
            string short_id = XmlUtil.getAttributeValue(contrib, "id", null);

            if (short_id == null)
            {
                string templ = Core.resources["xml.attribute_not_found"].stringValue;
                throw new PluginXmlException(contrib, string.Format(
                                                 templ, contrib.Name, "name", contrib.OwnerDocument.BaseURI));
            }

            string pname = PluginUtil.GetPruginDirName(contrib);

            return(pname + ":" + short_id);
        }
Esempio n. 18
0
        public override async Task <bool> TryWorkspaceDeleteAsync(ITfsVCWorkspace workspace)
        {
            PluginUtil.NotNull(workspace, nameof(workspace));
            try
            {
                await RunCommandAsync("workspace", "-delete", $"{workspace.Name};{workspace.Owner}");

                return(true);
            }
            catch (Exception ex)
            {
                ExecutionContext.Warning(ex.Message);
                return(false);
            }
        }
Esempio n. 19
0
        public async Task ShelveAsync(string shelveset, string commentFile, bool move)
        {
            PluginUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
            PluginUtil.NotNullOrEmpty(commentFile, nameof(commentFile));

            // TODO: Remove parameter move after last-saved-checkin-metadata problem is fixed properly.
            if (move)
            {
                await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "shelve", $"-workspace:{WorkspaceName}", "-move", "-replace", "-recursive", $"-comment:@{commentFile}", shelveset);

                return;
            }

            await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "shelve", $"-workspace:{WorkspaceName}", "-saved", "-replace", "-recursive", $"-comment:@{commentFile}", shelveset);
        }
Esempio n. 20
0
        public void SetupClientCertificate(string clientCert, string clientCertKey, string clientCertArchive, string clientCertPassword)
        {
            ExecutionContext.Debug("Convert client certificate from 'pkcs' format to 'jks' format.");
            string toolPath = PluginUtil.Which("keytool", true);
            string jksFile  = Path.Combine(ExecutionContext.Variables.GetValueOrDefault("agent.tempdirectory")?.Value, $"{Guid.NewGuid()}.jks");
            string argLine;

            if (!string.IsNullOrEmpty(clientCertPassword))
            {
                argLine = $"-importkeystore -srckeystore \"{clientCertArchive}\" -srcstoretype pkcs12 -destkeystore \"{jksFile}\" -deststoretype JKS -srcstorepass \"{clientCertPassword}\" -deststorepass \"{clientCertPassword}\"";
            }
            else
            {
                argLine = $"-importkeystore -srckeystore \"{clientCertArchive}\" -srcstoretype pkcs12 -destkeystore \"{jksFile}\" -deststoretype JKS";
            }

            ExecutionContext.Command($"{toolPath} {argLine}");

            var processInvoker = new ProcessInvoker(ExecutionContext);

            processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs args) =>
            {
                if (!string.IsNullOrEmpty(args.Data))
                {
                    ExecutionContext.Output(args.Data);
                }
            };
            processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs args) =>
            {
                if (!string.IsNullOrEmpty(args.Data))
                {
                    ExecutionContext.Output(args.Data);
                }
            };

            processInvoker.ExecuteAsync(ExecutionContext.Variables.GetValueOrDefault("system.defaultworkingdirectory")?.Value, toolPath, argLine, null, true, CancellationToken.None).GetAwaiter().GetResult();

            if (!string.IsNullOrEmpty(clientCertPassword))
            {
                ExecutionContext.Debug($"Set TF_ADDITIONAL_JAVA_ARGS=-Djavax.net.ssl.keyStore={jksFile} -Djavax.net.ssl.keyStorePassword={clientCertPassword}");
                AdditionalEnvironmentVariables["TF_ADDITIONAL_JAVA_ARGS"] = $"-Djavax.net.ssl.keyStore={jksFile} -Djavax.net.ssl.keyStorePassword={clientCertPassword}";
            }
            else
            {
                ExecutionContext.Debug($"Set TF_ADDITIONAL_JAVA_ARGS=-Djavax.net.ssl.keyStore={jksFile}");
                AdditionalEnvironmentVariables["TF_ADDITIONAL_JAVA_ARGS"] = $"-Djavax.net.ssl.keyStore={jksFile}";
            }
        }
Esempio n. 21
0
        /// <summary>
        /// 切换状态
        /// </summary>
        public void ChangeState_POST()
        {
            string workIndent = base.Request["worker_indent"];
            PluginPackAttribute attr;

            PluginUtil.GetPlugin(workIndent, out attr);

            attr.State = attr.State == PluginState.Normal?PluginState.Stop:PluginState.Normal;

            //Cms.Plugins.Manager.Pause(workIndent);

            //更新元数据
            Cms.Plugins.Manager.SavePluginMetadataToXml();

            base.RenderSuccess();
        }
        public FixedSizeStructureContribution(AbstractExStructure master, XmlElement pic, XmlElement main, bool opposite) : base(main)
        {
            _price = master.unitPrice;
            int height = master.maxHeight;

            if (opposite)
            {
                size = new Distance(master.size.y, master.size.x, height);
            }
            else
            {
                this.size = new Distance(master.size, height);
            }
            _ppa    = _price / Math.Max(1, size.x * size.y);
            sprites = PluginUtil.getSpriteLoader(pic).load3D(pic, size.x, size.y, height);
        }
Esempio n. 23
0
 /// <summary>
 /// 数据库访问对象
 /// </summary>
 public DataBaseAccess New()
 {
     if (_connString == null)
     {
         _connString = Conf.PluginAttrs.Settings["db_conn"];
         if (_connString.Contains("$ROOT"))
         {
             string dir = PluginUtil.GetAttribute <Main>().WorkSpace;
             _connString = _connString.Replace("$ROOT", dir.Substring(0, dir.Length - 1));
         }
     }
     return(new DataBaseAccess(
                DataBaseType.SQLServer,
                _connString
                ));
 }
Esempio n. 24
0
        public static void Postfix()
        {
            if (ToolsModifierControl.toolController.m_templatePrefabInfo is NetInfo)
            {
                if (PluginUtil.GetNetworkSkins().IsActive())
                {
                    Log.ShowModalException(
                        "Incompatible mod",
                        "NS2 is incompatible with AR in Road editor.",
                        error: true);
                }

                // don't know why but the lods do not load the first time i load an asset.
                NetManager.instance.RebuildLods();
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Load a color map from the XML manifest of the format:
        ///		&lt;map from="100,200, 50" to="50,30,20" />
        ///		&lt;map from="  0, 10,100" to="..." />
        ///		...
        /// </summary>
        /// <param name="e">
        /// The parent of &lt;map> elements.
        /// </param>
        public ColorMappedSpriteFactory(XmlElement e)
        {
            XmlNodeList lst = e.SelectNodes("map");

            srcColors = new Color[lst.Count];
            dstColors = new Color[lst.Count];

            int i = 0;

            foreach (XmlElement map in lst)
            {
                srcColors[i] = PluginUtil.parseColor(map.Attributes["from"].Value);
                dstColors[i] = PluginUtil.parseColor(map.Attributes["to"].Value);
                i++;
            }
        }
Esempio n. 26
0
        private void CombatEnded(bool isImport, CombatToggleEventArgs encounterInfo)
        {
            if (PluginUtil.IsPluginEnabled())
            {
                try
                {
                    //PluginControl.LogInfo(PluginSettings.GetSetting<string>("MaxPlayers"));
                    //Log Log = PluginUtil.ACTEncounterToModel(encounterInfo.encounter);
                    List <Log> LogList = PluginUtil.ACTEncounterToModelList(encounterInfo.encounter);
                    LogList.ForEach(Log =>
                    {
                        //PluginControl.LogInfo(PluginSettings.GetSetting<string>("MaxPlayers"));
                        if (Log != null)
                        {
                            if (PluginSettings.GetSetting <bool>("TimeEnabled") == true && PluginUtil.TimeBetween(DateTime.Now, DateTime.Parse(PluginSettings.GetSetting <string>("StartTime")).TimeOfDay, DateTime.Parse(PluginSettings.GetSetting <string>("EndTime")).TimeOfDay) == false)
                            {
                                PluginControl.LogInfo("Parse *not* sent to your Discord channel due to time lock rules.");
                                PluginControl.LogInfo("Waiting for the next encounter...");
                                return;
                            }

                            string Json = PluginUtil.ToJson(Log);
                            bool Sent   = Service.PostDiscord(Json, PluginSettings.GetSetting <string>("Token"));
                            if (Sent)
                            {
                                PluginControl.LogInfo("Parse sent to your Discord channel.");
                                PluginControl.LogInfo("Waiting for the next encounter...");
                            }
                            else
                            {
                                PluginControl.LogInfo("Could not send the parse to your Discord channel. Check your token and permissions.");
                            }

                            //PluginControl.LogInfo(Json);
                        }
                        else
                        {
                            PluginControl.LogInfo("Nothing to be sent. Waiting for the next encounter...");
                        }
                    });
                }
                catch (Exception e)
                {
                    PluginControl.LogInfo("Something went wrong. Debug info:" + Environment.NewLine + e.ToString());
                }
            }
        }
Esempio n. 27
0
        public async Task <ITfsVCWorkspace[]> WorkspacesAsync(bool matchWorkspaceNameOnAnyComputer = false)
        {
            // Build the args.
            var args = new List <string>();

            args.Add("workspaces");
            if (matchWorkspaceNameOnAnyComputer)
            {
                args.Add(WorkspaceName);
                args.Add($"-computer:*");
            }

            args.Add("-format:xml");

            // Run the command.
            TfsVCPorcelainCommandResult result = await TryRunPorcelainCommandAsync(FormatFlags.None, args.ToArray());

            PluginUtil.NotNull(result, nameof(result));
            if (result.Exception != null)
            {
                // Check if the workspace name was specified and the command returned exit code 1.
                if (matchWorkspaceNameOnAnyComputer && result.Exception.ExitCode == 1)
                {
                    // Ignore the error. This condition can indicate the workspace was not found.
                    return(new ITfsVCWorkspace[0]);
                }

                // Dump the output and throw.
                result.Output?.ForEach(x => ExecutionContext.Output(x ?? string.Empty));
                throw result.Exception;
            }

            // Note, string.join gracefully handles a null element within the IEnumerable<string>.
            string output = string.Join(Environment.NewLine, result.Output ?? new List <string>()) ?? string.Empty;
            string xml    = ExtractXml(output);

            // Deserialize the XML.
            var serializer = new XmlSerializer(typeof(TeeWorkspaces));

            using (var reader = new StringReader(xml))
            {
                return((serializer.Deserialize(reader) as TeeWorkspaces)
                       ?.Workspaces
                       ?.Cast <ITfsVCWorkspace>()
                       .ToArray());
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Removes unused and duplicate mappings.
        /// </summary>
        /// <param name="allMappings"></param>
        /// <returns></returns>
        public Dictionary <string, SvnMappingDetails> NormalizeMappings(List <SvnMappingDetails> allMappings)
        {
            // We use Ordinal comparer because SVN is case sensetive and keys in the dictionary are URLs.
            Dictionary <string, SvnMappingDetails> distinctMappings = new Dictionary <string, SvnMappingDetails>(StringComparer.Ordinal);
            HashSet <string> localPaths = new HashSet <string>(StringComparer.Ordinal);

            foreach (SvnMappingDetails map in allMappings)
            {
                string localPath  = NormalizeRelativePath(map.LocalPath, Path.DirectorySeparatorChar, '/');
                string serverPath = NormalizeRelativePath(map.ServerPath, '/', '\\');

                if (string.IsNullOrEmpty(serverPath))
                {
                    _context.Debug(PluginUtil.Loc("SvnEmptyServerPath", localPath));
                    _context.Debug(PluginUtil.Loc("SvnMappingIgnored"));

                    distinctMappings.Clear();
                    distinctMappings.Add(string.Empty, map);
                    break;
                }

                if (localPaths.Contains(localPath))
                {
                    _context.Debug(PluginUtil.Loc("SvnMappingDuplicateLocal", localPath));
                    continue;
                }
                else
                {
                    localPaths.Add(localPath);
                }

                if (distinctMappings.ContainsKey(serverPath))
                {
                    _context.Debug(PluginUtil.Loc("SvnMappingDuplicateServer", serverPath));
                    continue;
                }

                // Put normalized values of the local and server paths back into the mapping.
                map.LocalPath  = localPath;
                map.ServerPath = serverPath;

                distinctMappings.Add(serverPath, map);
            }

            return(distinctMappings);
        }
Esempio n. 29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="master"></param>
        /// <param name="pic"></param>
        /// <param name="main"></param>
        /// <param name="opposite"></param>
        public FixedSizeStructureContribution(IAbstractStructure master, XmlElement pic, XmlElement main, bool opposite)
            : base(main)
        {
            this.Price = master.UnitPrice;
            int height = master.MaxHeight;

            if (opposite)
            {
                size = new Distance(master.Size.Height, master.Size.Width, height);
            }
            else
            {
                this.size = new Distance(master.Size, height);
            }
            this.PricePerArea = this.Price / Math.Max(1, size.x * size.y);
            sprites           = PluginUtil.getSpriteLoader(pic).load3D(pic, size.x, size.y, height);
        }
Esempio n. 30
0
        public string ResolvePath(string serverPath)
        {
            PluginUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
            string localPath = RunPorcelainCommandAsync("resolvePath", $"-workspace:{WorkspaceName}", serverPath).GetAwaiter().GetResult();

            localPath = localPath?.Trim();

            // Paths outside of the root mapping return empty.
            // Paths within a cloaked directory return "null".
            if (string.IsNullOrEmpty(localPath) ||
                string.Equals(localPath, "null", StringComparison.OrdinalIgnoreCase))
            {
                return(string.Empty);
            }

            return(localPath);
        }