System.IO.File.WriteAllText(string, string, System.Text.Encoding)

Here are the examples of the csharp api System.IO.File.WriteAllText(string, string, System.Text.Encoding) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3325 Examples 7

19 View Source File : ActionRunner.cs
License : MIT License
Project Creator : actions

public async Task RunAsync()
        {
            // Validate args.
            Trace.Entering();
            ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
            ArgUtil.NotNull(Action, nameof(Action));
            var taskManager = HostContext.GetService<IActionManager>();
            var handlerFactory = HostContext.GetService<IHandlerFactory>();

            // Load the task definition and choose the handler.
            Definition definition = taskManager.LoadAction(ExecutionContext, Action);
            ArgUtil.NotNull(definition, nameof(definition));

            ActionExecutionData handlerData = definition.Data?.Execution;
            ArgUtil.NotNull(handlerData, nameof(handlerData));

            List<JobExtensionRunner> localActionContainerSetupSteps = null;
            // Handle Composite Local Actions
            // Need to download and expand the tree of referenced actions
            if (handlerData.ExecutionType == ActionExecutionType.Composite &&
                handlerData is CompositeActionExecutionData compositeHandlerData &&
                Stage == ActionRunStage.Main &&
                Action.Reference is Pipelines.RepositoryPathReference localAction &&
                string.Equals(localAction.RepositoryType, Pipelines.PipelineConstants.SelfAlias, StringComparison.OrdinalIgnoreCase))
            {
                var actionManager = HostContext.GetService<IActionManager>();
                var prepareResult = await actionManager.PrepareActionsAsync(ExecutionContext, compositeHandlerData.Steps, ExecutionContext.Id);

                // Reload definition since post may exist now (from embedded steps that were JIT downloaded)
                definition = taskManager.LoadAction(ExecutionContext, Action);
                ArgUtil.NotNull(definition, nameof(definition));
                handlerData = definition.Data?.Execution;
                ArgUtil.NotNull(handlerData, nameof(handlerData));

                // Save container setup steps so we can reference them later
                localActionContainerSetupSteps = prepareResult.ContainerSetupSteps;
            }

            if (handlerData.HasPre &&
                Action.Reference is Pipelines.RepositoryPathReference repoAction &&
                string.Equals(repoAction.RepositoryType, Pipelines.PipelineConstants.SelfAlias, StringComparison.OrdinalIgnoreCase))
            {
                ExecutionContext.Warning($"`pre` execution is not supported for local action from '{repoAction.Path}'");
            }

            // The action has post cleanup defined.
            // we need to create timeline record for them and add them to the step list that StepRunner is using
            if (handlerData.HasPost && (Stage == ActionRunStage.Pre || Stage == ActionRunStage.Main))
            {
                string postDisplayName = $"Post {this.DisplayName}";
                if (Stage == ActionRunStage.Pre &&
                    this.DisplayName.StartsWith("Pre ", StringComparison.OrdinalIgnoreCase))
                {
                    // Trim the leading `Pre ` from the display name.
                    // Otherwise, we will get `Post Pre xxx` as DisplayName for the Post step.
                    postDisplayName = $"Post {this.DisplayName.Substring("Pre ".Length)}";
                }
                var repositoryReference = Action.Reference as RepositoryPathReference;
                var pathString = string.IsNullOrEmpty(repositoryReference.Path) ? string.Empty : $"/{repositoryReference.Path}";
                var repoString = string.IsNullOrEmpty(repositoryReference.Ref) ? $"{repositoryReference.Name}{pathString}" :
                    $"{repositoryReference.Name}{pathString}@{repositoryReference.Ref}";

                ExecutionContext.Debug($"Register post job cleanup for action: {repoString}");

                var actionRunner = HostContext.CreateService<IActionRunner>();
                actionRunner.Action = Action;
                actionRunner.Stage = ActionRunStage.Post;
                actionRunner.Condition = handlerData.CleanupCondition;
                actionRunner.DisplayName = postDisplayName;

                ExecutionContext.RegisterPostJobStep(actionRunner);
            }

            IStepHost stepHost = HostContext.CreateService<IDefaultStepHost>();

            // Makes directory for event_path data
            var tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp);
            var workflowDirectory = Path.Combine(tempDirectory, "_github_workflow");
            Directory.CreateDirectory(workflowDirectory);

            var gitHubEvent = ExecutionContext.GetGitHubContext("event");

            // adds the GitHub event path/file if the event exists
            if (gitHubEvent != null)
            {
                var workflowFile = Path.Combine(workflowDirectory, "event.json");
                Trace.Info($"Write event payload to {workflowFile}");
                File.WriteAllText(workflowFile, gitHubEvent, new UTF8Encoding(false));
                ExecutionContext.SetGitHubContext("event_path", workflowFile);
            }

            // Set GITHUB_ACTION_REPOSITORY if this Action is from a repository
            if (Action.Reference is Pipelines.RepositoryPathReference repoPathReferenceAction &&
                !string.Equals(repoPathReferenceAction.RepositoryType, Pipelines.PipelineConstants.SelfAlias, StringComparison.OrdinalIgnoreCase))
            {
                ExecutionContext.SetGitHubContext("action_repository", repoPathReferenceAction.Name);
                ExecutionContext.SetGitHubContext("action_ref", repoPathReferenceAction.Ref);
            }
            else
            {
                ExecutionContext.SetGitHubContext("action_repository", null);
                ExecutionContext.SetGitHubContext("action_ref", null);
            }

            // Setup container stephost for running inside the container.
            if (ExecutionContext.Global.Container != null)
            {
                // Make sure required container is already created.
                ArgUtil.NotNullOrEmpty(ExecutionContext.Global.Container.ContainerId, nameof(ExecutionContext.Global.Container.ContainerId));
                var containerStepHost = HostContext.CreateService<IContainerStepHost>();
                containerStepHost.Container = ExecutionContext.Global.Container;
                stepHost = containerStepHost;
            }

            // Setup File Command Manager
            var fileCommandManager = HostContext.CreateService<IFileCommandManager>();
            fileCommandManager.InitializeFiles(ExecutionContext, null);

            // Load the inputs.
            ExecutionContext.Debug("Loading inputs");
            var templateEvaluator = ExecutionContext.ToPipelineTemplateEvaluator();
            var inputs = templateEvaluator.EvaluateStepInputs(Action.Inputs, ExecutionContext.ExpressionValues, ExecutionContext.ExpressionFunctions);

            var userInputs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            foreach (KeyValuePair<string, string> input in inputs)
            {
                userInputs.Add(input.Key);
                string message = "";
                if (definition.Data?.Deprecated?.TryGetValue(input.Key, out message) == true)
                {
                    ExecutionContext.Warning(String.Format("Input '{0}' has been deprecated with message: {1}", input.Key, message));
                }
            }

            var validInputs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            if (handlerData.ExecutionType == ActionExecutionType.Container)
            {
                // container action always accept 'entryPoint' and 'args' as inputs
                // https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idstepswithargs
                validInputs.Add("entryPoint");
                validInputs.Add("args");
            }
            // Merge the default inputs from the definition
            if (definition.Data?.Inputs != null)
            {
                var manifestManager = HostContext.GetService<IActionManifestManager>();
                foreach (var input in definition.Data.Inputs)
                {
                    string key = input.Key.replacedertString("action input name").Value;
                    validInputs.Add(key);
                    if (!inputs.ContainsKey(key))
                    {
                        inputs[key] = manifestManager.EvaluateDefaultInput(ExecutionContext, key, input.Value);
                    }
                }
            }

            // Validate inputs only for actions with action.yml
            if (Action.Reference.Type == Pipelines.ActionSourceType.Repository)
            {
                var unexpectedInputs = new List<string>();
                foreach (var input in userInputs)
                {
                    if (!validInputs.Contains(input))
                    {
                        unexpectedInputs.Add(input);
                    }
                }

                if (unexpectedInputs.Count > 0)
                {
                    ExecutionContext.Warning($"Unexpected input(s) '{string.Join("', '", unexpectedInputs)}', valid inputs are ['{string.Join("', '", validInputs)}']");
                }
            }

            // Load the action environment.
            ExecutionContext.Debug("Loading env");
            var environment = new Dictionary<String, String>(VarUtil.EnvironmentVariableKeyComparer);

#if OS_WINDOWS
            var envContext = ExecutionContext.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = ExecutionContext.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            // Apply environment from env context, env context contains job level env and action's evn block
            foreach (var env in envContext)
            {
                environment[env.Key] = env.Value.ToString();
            }

            // Apply action's intra-action state at last
            foreach (var state in ExecutionContext.IntraActionState)
            {
                environment[$"STATE_{state.Key}"] = state.Value ?? string.Empty;
            }

            // Create the handler.
            IHandler handler = handlerFactory.Create(
                            ExecutionContext,
                            Action.Reference,
                            stepHost,
                            handlerData,
                            inputs,
                            environment,
                            ExecutionContext.Global.Variables,
                            actionDirectory: definition.Directory,
                            localActionContainerSetupSteps: localActionContainerSetupSteps);

            // Print out action details
            handler.PrintActionDetails(Stage);

            // Run the task.
            try
            {
                await handler.RunAsync(Stage);
            }
            finally
            {
                fileCommandManager.ProcessFiles(ExecutionContext, ExecutionContext.Global.Container);
            }

        }

19 View Source File : GenerateSourceOnlyPackageNuspecsTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (PartNuspecFiles == null)
            {
                Log.LogMessage("No source-only packages found");
                return true; //nothing to process
            }

            //process the source files
            foreach (var sourceFile in PartNuspecFiles)
            {
                var partNuspecFileNameFull = sourceFile.GetMetadata("FullPath");

                //Get the partial (partnuspec) file
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = partNuspecFileNameFull + ".tmp.nuspec";
                Log.LogMessage($"Loading {partNuspecFileNameFull}");
                var partNuspecFileContent = File.ReadAllText(partNuspecFileNameFull);
                partNuspecFileContent = partNuspecFileContent.Replace("%%CURRENT_VERSION%%", PackageVersionFull);
                var outXDoc = XDoreplacedent.Parse(partNuspecFileContent);
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                //Check package ID
                var packageId = metadataXElement.Element(ns + "id")?.Value;
                if (packageId == null) throw new Exception($"Can't find the package ID for {partNuspecFileNameFull}");

                //Process version - global version from solution of base version from partial file
                var versionOriginal = GetOrCreateElement(metadataXElement, "version", ns)?.Value;
                var version = PackageVersionFull;
                if (!string.IsNullOrEmpty(versionOriginal))
                {
                    //base version set in NuProp
                    //get ext version from PackageVersionFull
                    //0.1.0-dev.441.181206212308+53.master.37f08fc-dirty
                    //0.1.0+442.181206212418.master.37f08fc-dirty
                    var idx = 0;
                    while (char.IsDigit(PackageVersionFull[idx]) || PackageVersionFull[idx] == '.')
                    {
                        idx++;
                    }

                    version = versionOriginal + PackageVersionFull.Substring(idx);
                }

                //Enrich the NuSpec
                SetOrCreateElement(metadataXElement, "version", ns, version);
                SetOrCreateElement(metadataXElement, "authors", ns, Authors);
                SetOrCreateElement(metadataXElement, "replacedle", ns, packageId);
                SetOrCreateElement(metadataXElement, "owners", ns, Authors);
                SetOrCreateElement(metadataXElement, "description", ns, $"Source only package {packageId}", false); //don't override if exists
                SetOrCreateElement(metadataXElement, "requireLicenseAcceptance", ns, PackageRequireLicenseAcceptance);
                if (!string.IsNullOrEmpty(PackageLicense))
                {
                    SetOrCreateElement(metadataXElement, "license", ns, PackageLicense).
                        Add(new XAttribute("type","expression"));
                }
                else
                {
                    SetOrCreateElement(metadataXElement, "licenseUrl", ns, PackageLicenseUrl);
                }
                SetOrCreateElement(metadataXElement, "projectUrl", ns, PackageProjectUrl);
                SetOrCreateElement(metadataXElement, "iconUrl", ns, PackageIconUrl);
                SetOrCreateElement(metadataXElement, "copyright", ns, Copyright);
                SetOrCreateElement(metadataXElement, "developmentDependency", ns, "true");
                GetEmptyOrCreateElement(metadataXElement, "repository", ns).
                                    Add(new XAttribute("url", RepositoryUrl),
                                        new XAttribute("type", "git"),
                                        new XAttribute("branch", GitBranch),
                                        new XAttribute("commit", GitCommit));

                //Save the temporary NuSpec file
                var outXDocStr = outXDoc.ToString();
                File.WriteAllText(outFile, outXDocStr);
                Log.LogMessage($"Generated source only nuspec file {outFile}");
            }

            return true;
        }

19 View Source File : UMAAvatarLoadSaveMenuItems.cs
License : Apache License 2.0
Project Creator : A7ocin

[MenuItem("UMA/Load and Save/Save Selected Avatar(s) Txt", priority=1)]
      public static void SaveSelectedAvatarsTxt()
      {
         for (int i = 0; i < Selection.gameObjects.Length; i++)
         {
            var selectedTransform = Selection.gameObjects[i].transform;
            var avatar = selectedTransform.GetComponent<UMAAvatarBase>();
            while (avatar == null && selectedTransform.parent != null)
            {
               selectedTransform = selectedTransform.parent;
               avatar = selectedTransform.GetComponent<UMAAvatarBase>();
            }

            if (avatar != null)
            {
               var path = EditorUtility.SaveFilePanel("Save serialized Avatar", "replacedets", avatar.name + ".txt", "txt");
               if (path.Length != 0)
               {
                  var replacedet = ScriptableObject.CreateInstance<UMATextRecipe>();
                  //check if Avatar is DCS
                  if (avatar is UMA.CharacterSystem.DynamicCharacterAvatar)
                  {
                     replacedet.Save(avatar.umaData.umaRecipe, avatar.context, (avatar as DynamicCharacterAvatar).WardrobeRecipes, true);
                  }
                  else
                  {
                     replacedet.Save(avatar.umaData.umaRecipe, avatar.context);
                  }				
                  System.IO.File.WriteAllText(path, replacedet.recipeString);
                  UMAUtils.DestroySceneObject(replacedet);
               }
            }
         }
      }

19 View Source File : SixCloudUser.cs
License : MIT License
Project Creator : Accelerider

private void SaveDownloadingFile(IDownloadingFile result)
        {
            _downloadingFiles.Add(result);
            ArddFilePaths.Add(result.ArddFilePath);

            var disposable1 = Subscribe(result.DownloadInfo.Where(item => item.Status == TransferStatus.Suspended || item.Status == TransferStatus.Faulted));
            var disposable2 = Subscribe(result.DownloadInfo.Sample(TimeSpan.FromMilliseconds(5000)));

            result.DownloadInfo
                .Where(item => item.Status == TransferStatus.Disposed)
                .Subscribe(async _ =>
                {
                    await ClearDownloadInfo(true);

                    Logger.Info($"Download Cancelled: {result.DownloadInfo.Context.LocalPath}. ");
                }, OnCompleted);

            File.WriteAllText(result.ArddFilePath.EnsureFileFolder(), result.ToJsonString());

            if (result.DownloadInfo.Status == TransferStatus.Completed)
            {
                OnCompleted();
            }

            async void OnCompleted()
            {
                await ClearDownloadInfo(false);
                var localDiskFile = LocalDiskFile.Create(result);
                _localDiskFiles.Add(localDiskFile);

                Logger.Info($"Download Completed: {result.DownloadInfo.Context.LocalPath}. ");
            }

            IDisposable Subscribe(IObservable<TransferNotification> observable)
            {
                return observable.Subscribe(_ => File.WriteAllText(result.ArddFilePath, result.ToJsonString()));
            }

            async Task ClearDownloadInfo(bool isCancelled)
            {
                disposable1.Dispose();
                disposable2.Dispose();

                ArddFilePaths.Remove(result.ArddFilePath);
                _downloadingFiles.Remove(result);

                await result.ArddFilePath.TryDeleteAsync();
                if (isCancelled) await result.DownloadInfo.Context.LocalPath.TryDeleteAsync();
            }
        }

19 View Source File : ThingEntry.cs
License : Apache License 2.0
Project Creator : AantCoder

public bool SetFaction(string fractionColonist, Func<string> fractionRoyalty)
        {
            if (string.IsNullOrEmpty(Data) || !Data.Contains(" Clreplaced=\"Pawn\"")) return false;
            if (MainHelper.DebugMode) File.WriteAllText(Loger.PathLog + "MailPawnB" + (++nnnn).ToString() + ".xml", Data);

            //логика коррекции основывается на 3х группыах:
            //колонист, человек не колонист (пират или пленник), животное

            bool col = Data.Contains("<kindDef>Colonist</kindDef>");
            if (!col) col = Data.Contains("ColonistGeneral</kindDef>"); //для мода с андроидами

            bool isAnimal = GameXMLUtils.GetByTag(Data, "def") == GameXMLUtils.GetByTag(Data, "kindDef");

            //для всех людей устанавливаем фракцию игрока (у животных не меняем)

            if (!isAnimal)
            {
                string fraction = fractionColonist; //col ? fractionColonist : fractionPirate;
                Data = GameXMLUtils.ReplaceByTag(Data, "faction", fraction);
                if (!col) Data = GameXMLUtils.ReplaceByTag(Data, "kindDef", "Colonist"); //"Pirate"
                //if (MainHelper.DebugMode) Loger.Log(" Replace faction=>" + fraction);
            }

            //если это гости, то убираем у них это свойство - оно должно выставиться потом

            Data = GameXMLUtils.ReplaceByTag(Data, "guest", @"
    <hostFaction>null</hostFaction>
    <interactionMode>NoInteraction</interactionMode>
    <spotToWaitInsteadOfEscaping>(-1000, -1000, -1000)</spotToWaitInsteadOfEscaping>
    <lastPrisonBreakTicks>-1</lastPrisonBreakTicks>
  ");

            //локализуем фракцию роялти
            var tagRoyalty = GameXMLUtils.GetByTag(Data, "royalty");
            if (tagRoyalty != null)
            {
                string oldTR;
                do
                {
                    oldTR = tagRoyalty;
                    tagRoyalty = GameXMLUtils.ReplaceByTag(tagRoyalty, "faction", fractionRoyalty());
                } while (oldTR != tagRoyalty);
                Data = GameXMLUtils.ReplaceByTag(Data, "royalty", tagRoyalty);
            }

            /*
            Data = GameXMLUtils.ReplaceByTag(Data, "hostFaction", "null", "<guest>");
            Data = GameXMLUtils.ReplaceByTag(Data, "prisoner", "False", "<guest>");*/

            /* попытка передавать заключенных не получилась
            Data = GameXMLUtils.ReplaceByTag(Data, "hostFaction", 
                (val) =>
                {
                    if (MainHelper.DebugMode) Loger.Log(" Replace hostFaction "+ val + "=>" + fractionColonist);
                    return val == "null" ? null : fractionColonist;

                });
                */

            //возвращаем true, если это человек и не колонист (пират или пленник)

            if (MainHelper.DebugMode) File.WriteAllText(Loger.PathLog + "MailPawnA" + nnnn.ToString() + ".xml", Data);
            return !col && !isAnimal;
        }

19 View Source File : SettingsManager.cs
License : MIT License
Project Creator : a1xd

private DriverConfig InitActiveAndGetUserConfig()
        {
            var path = Constants.DefaultSettingsFileName;
            if (File.Exists(path))
            {
                try
                {
                    var (cfg, err) = DriverConfig.Convert(File.ReadAllText(path));

                    if (err == null)
                    {
                        if (GuiSettings.AutoWriteToDriverOnStartup)
                        {
                            if (!TryActivate(cfg, out string _))
                            {
                                throw new Exception("deserialization succeeded but TryActivate failed");
                            }
                        }
                        else
                        {
                            ActiveConfig = DriverConfig.GetActive();
                        }

                        return cfg;
                    }
                }
                catch (JsonException e)
                {
                    System.Diagnostics.Debug.WriteLine($"bad settings: {e}");
                }
            }

            ActiveConfig = DriverConfig.GetActive();
            File.WriteAllText(path, ActiveConfig.ToJSON());
            return ActiveConfig;
        }

19 View Source File : ScriptHandler.cs
License : MIT License
Project Creator : actions

public async Task RunAsync(ActionRunStage stage)
        {
            if (stage == ActionRunStage.Post)
            {
                throw new NotSupportedException("Script action should not have 'Post' job action.");
            }

            // Validate args
            Trace.Entering();
            ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
            ArgUtil.NotNull(Inputs, nameof(Inputs));

            var githubContext = ExecutionContext.ExpressionValues["github"] as GitHubContext;
            ArgUtil.NotNull(githubContext, nameof(githubContext));

            // Add Telemetry to JobContext to send with JobCompleteMessage
            if (stage == ActionRunStage.Main)
            {
                var telemetry = new ActionsStepTelemetry
                {
                    IsEmbedded = ExecutionContext.IsEmbedded,
                    Type = "run",
                };
                ExecutionContext.Root.ActionsStepsTelemetry.Add(telemetry);
            }

            var tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp);

            Inputs.TryGetValue("script", out var contents);
            contents = contents ?? string.Empty;

            string workingDirectory = null;
            if (!Inputs.TryGetValue("workingDirectory", out workingDirectory))
            {
                if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
                {
                    if (runDefaults.TryGetValue("working-directory", out workingDirectory))
                    {
                        ExecutionContext.Debug("Overwrite 'working-directory' base on job defaults.");
                    }
                }
            }
            var workspaceDir = githubContext["workspace"] as StringContextData;
            workingDirectory = Path.Combine(workspaceDir, workingDirectory ?? string.Empty);

            string shell = null;
            if (!Inputs.TryGetValue("shell", out shell) || string.IsNullOrEmpty(shell))
            {
                if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
                {
                    if (runDefaults.TryGetValue("shell", out shell))
                    {
                        ExecutionContext.Debug("Overwrite 'shell' base on job defaults.");
                    }
                }
            }

            var isContainerStepHost = StepHost is ContainerStepHost;

            string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
            string commandPath, argFormat, shellCommand;
            // Set up default command and arguments
            if (string.IsNullOrEmpty(shell))
            {
#if OS_WINDOWS
                shellCommand = "pwsh";
                commandPath = WhichUtil.Which(shellCommand, require: false, Trace, prependPath);
                if (string.IsNullOrEmpty(commandPath))
                {
                    shellCommand = "powershell";
                    Trace.Info($"Defaulting to {shellCommand}");
                    commandPath = WhichUtil.Which(shellCommand, require: true, Trace, prependPath);
                }
                ArgUtil.NotNullOrEmpty(commandPath, "Default Shell");
#else
                shellCommand = "sh";
                commandPath = WhichUtil.Which("bash", false, Trace, prependPath) ?? WhichUtil.Which("sh", true, Trace, prependPath);
#endif
                argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
            }
            else
            {
                var parsed = ScriptHandlerHelpers.ParseShellOptionString(shell);
                shellCommand = parsed.shellCommand;
                // For non-ContainerStepHost, the command must be located on the host by Which
                commandPath = WhichUtil.Which(parsed.shellCommand, !isContainerStepHost, Trace, prependPath);
                argFormat = $"{parsed.shellArgs}".TrimStart();
                if (string.IsNullOrEmpty(argFormat))
                {
                    argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
                }
            }

            // No arg format was given, shell must be a built-in
            if (string.IsNullOrEmpty(argFormat) || !argFormat.Contains("{0}"))
            {
                throw new ArgumentException("Invalid shell option. Shell must be a valid built-in (bash, sh, cmd, powershell, pwsh) or a format string containing '{0}'");
            }

            // We do not not the full path until we know what shell is being used, so that we can determine the file extension
            var scriptFilePath = Path.Combine(tempDirectory, $"{Guid.NewGuid()}{ScriptHandlerHelpers.GetScriptFileExtension(shellCommand)}");
            var resolvedScriptPath = $"{StepHost.ResolvePathForStepHost(scriptFilePath).Replace("\"", "\\\"")}";

            // Format arg string with script path
            var arguments = string.Format(argFormat, resolvedScriptPath);

            // Fix up and write the script
            contents = ScriptHandlerHelpers.FixUpScriptContents(shellCommand, contents);
#if OS_WINDOWS
            // Normalize Windows line endings
            contents = contents.Replace("\r\n", "\n").Replace("\n", "\r\n");
            var encoding = ExecutionContext.Global.Variables.Retain_Default_Encoding && Console.InputEncoding.CodePage != 65001
                ? Console.InputEncoding
                : new UTF8Encoding(false);
#else
            // Don't add a BOM. It causes the script to fail on some operating systems (e.g. on Ubuntu 14).
            var encoding = new UTF8Encoding(false);
#endif
            // Script is written to local path (ie host) but executed relative to the StepHost, which may be a container
            File.WriteAllText(scriptFilePath, contents, encoding);

            // Prepend PATH
            AddPrependPathToEnvironment();

            // expose context to environment
            foreach (var context in ExecutionContext.ExpressionValues)
            {
                if (context.Value is IEnvironmentContextData runtimeContext && runtimeContext != null)
                {
                    foreach (var env in runtimeContext.GetRuntimeEnvironmentVariables())
                    {
                        Environment[env.Key] = env.Value;
                    }
                }
            }

            // dump out the command
            var fileName = isContainerStepHost ? shellCommand : commandPath;
#if OS_OSX
            if (Environment.ContainsKey("DYLD_INSERT_LIBRARIES"))  // We don't check `isContainerStepHost` because we don't support container on macOS
            {
                // launch `node macOSRunInvoker.js shell args` instead of `shell args` to avoid macOS SIP remove `DYLD_INSERT_LIBRARIES` when launch process
                string node12 = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), "node12", "bin", $"node{IOUtil.ExeExtension}");
                string macOSRunInvoker = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), "macos-run-invoker.js");
                arguments = $"\"{macOSRunInvoker.Replace("\"", "\\\"")}\" \"{fileName.Replace("\"", "\\\"")}\" {arguments}";
                fileName = node12;
            }
#endif
            var systemConnection = ExecutionContext.Global.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
            if (systemConnection.Data.TryGetValue("GenerateIdTokenUrl", out var generateIdTokenUrl) && !string.IsNullOrEmpty(generateIdTokenUrl))
            {
                Environment["ACTIONS_ID_TOKEN_REQUEST_URL"] = generateIdTokenUrl;
                Environment["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken];
            }

            ExecutionContext.Debug($"{fileName} {arguments}");

            using (var stdoutManager = new OutputManager(ExecutionContext, ActionCommandManager))
            using (var stderrManager = new OutputManager(ExecutionContext, ActionCommandManager))
            {
                StepHost.OutputDataReceived += stdoutManager.OnDataReceived;
                StepHost.ErrorDataReceived += stderrManager.OnDataReceived;

                // Execute
                int exitCode = await StepHost.ExecuteAsync(workingDirectory: StepHost.ResolvePathForStepHost(workingDirectory),
                                            fileName: fileName,
                                            arguments: arguments,
                                            environment: Environment,
                                            requireExitCodeZero: false,
                                            outputEncoding: null,
                                            killProcessOnCancel: false,
                                            inheritConsoleHandler: !ExecutionContext.Global.Variables.Retain_Default_Encoding,
                                            cancellationToken: ExecutionContext.CancellationToken);

                // Error
                if (exitCode != 0)
                {
                    ExecutionContext.Error($"Process completed with exit code {exitCode}.");
                    ExecutionContext.Result = TaskResult.Failed;
                }
            }
        }

19 View Source File : GenericProjectSettings.cs
License : MIT License
Project Creator : 5argon

public void Save()
        {
            if (cachedSettings != null)
            {
                this.SerializedVersion = dummy.DataVersion;
                File.WriteAllText(settingsPath, JsonUtility.ToJson(cachedSettings, prettyPrint: true));
            }
        }

19 View Source File : ProcessNuPropsTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (SourceFiles == null)
            {
                Log.LogMessage("No source code available");
                return true; //nothing to process
            }

            //process the source files
            var anyPackageAvailable = false;
            foreach (var sourceFile in SourceFiles)
            {
                var fileNameFull = sourceFile.GetMetadata("FullPath");
                var fileName = new FileInfo(fileNameFull).Name;

                //Get the NuProps from XML Doreplacedentation Comments <NuProp.xxxx>
                var sourceContent = File.ReadAllText(fileNameFull);
                var sourceLines = sourceContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                //Extract all comments
                var stringBuilder = new StringBuilder();
                foreach (var contentLine in sourceLines)
                {
                    var sourceLine = contentLine.Trim();
                    if (sourceLine.StartsWith("///"))
                    {
                        stringBuilder.AppendLine(sourceLine.Substring(3));
                    }
                }

                //Get all comments in single XML - encapsulate the whole bunch with dummy tag "doc" allowing the XDoreplacedent to parse it
                var xDoreplacedent = XDoreplacedent.Parse("<doc>" + stringBuilder + "</doc>");
                //Get NuProp comments
                var nuPropElements = xDoreplacedent.Descendants()
                    .Where(n => n is XElement e && e.Name.LocalName.StartsWith("NuProp.")).ToList();

                if (nuPropElements.Count <= 0) continue; //no NuProps - continue with the next file

                //Has some NuProp -> process
                //<NuProp.Id></NuProp.Id> - package ID (mandatory)
                //<NuProp.Version></NuProp.Version>   - package version base (major.minor.patch) - optional          
                //<NuProp.Description></NuProp.Description> - package description (optional)
                //<NuProp.Tags></NuProp.Tags> - package tags (optional)
                //<NuProp.Using id = "" version=""/> - package imports (optional). Version is optional
                //<NuProp.Needs id="" /> - "external" imports needed (optional) - not included in package, just info when consuming!!!

                var nuPropId = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Id")?.Value.Trim();
                var nuPropVersion = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Version")?.Value.Trim();
                var nuPropDescription = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Description")?.Value.Trim();
                var nuPropTags = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Tags")?.Value.Trim();

                var nuPropsIncludes = IncludesEnum.None;
                var nuPropIncludesStr = nuPropElements
                    .FirstOrDefault(e => e.Name.LocalName == "NuProp.Includes" && e.Attribute("type")?.Value != null)?
                    .Attribute("type")?.Value;
                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (nuPropIncludesStr)
                {
                    case "Folder": nuPropsIncludes = IncludesEnum.Folder; break;
                    case "FolderRecursive": nuPropsIncludes = IncludesEnum.FolderRecursive; break;
                }

                var nuPropUsings = nuPropElements.Where(e => e.Name.LocalName == "NuProp.Using" && e.Attribute("id")?.Value != null).ToList();

                if (string.IsNullOrEmpty(nuPropId))
                {
                    Log.LogWarning($"NuProp.Id not found for {fileName}");
                    continue;
                }

                //Build the partial NuSpec file
                anyPackageAvailable = true;
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = fileNameFull + ".partnuspec";
                var outXDoc = File.Exists(outFile) ? XDoreplacedent.Load(outFile) : new XDoreplacedent();
                var outXDocStrOriginal = outXDoc.ToString();
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                SetOrCreateElement(metadataXElement, "id", ns, nuPropId);
                SetOrCreateElement(metadataXElement, "version", ns, nuPropVersion, false); //don't create if the nuPropVersion is empty/not set
                SetOrCreateElement(metadataXElement, "description", ns, nuPropDescription, false); //don't create if the nuPropDescription is empty/not set
                SetOrCreateElement(metadataXElement, "tags", ns, nuPropTags, false); //don't create if the nuPropTags is empty/not set

                GetEmptyOrCreateElement(metadataXElement, "contentFiles", ns)
                    .Add(new XElement(ns + "files", //<files include="cs/**/*.*" buildAction="Compile" />
                        new XAttribute("include", "cs/**/*.*"),
                        new XAttribute("buildAction", "Compile")));


                //Dependencies
                var dependenciesXElement = GetEmptyOrCreateElement(metadataXElement, "dependencies", ns);
                if (nuPropUsings.Count > 0)
                {
                    //have some dependencies
                    foreach (var nuPropUsing in nuPropUsings)
                    {
                        // ReSharper disable once PossibleNullReferenceException - should not be null based on Where clause for nuPropUsings
                        var depId = nuPropUsing.Attribute("id").Value;
                        var depVersion = nuPropUsing.Attribute("version")?.Value;
                        var dependencyXElement = new XElement(ns + "dependency", new XAttribute("id", depId), new XAttribute("include", "all"));
                        if (string.IsNullOrEmpty(depVersion)) depVersion = "%%CURRENT_VERSION%%";
                        dependencyXElement.Add(new XAttribute("version", depVersion));
                        dependenciesXElement.Add(dependencyXElement);
                    }
                }
                else
                {
                    //Clean dependencies
                    dependenciesXElement.Remove();
                }

                //<files>
                //    < file src = "src.cs" target = "content\App_Packages\pkg_id\src.cs" />
                //    < file src = "src.cs" target = "contentFiles\cs\any\App_Packages\pkg_id\src.cs" />
                //</ files >
                var files = GetEmptyOrCreateElement(packageXElement, "files", ns);
                files.Add(
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{fileName}")),
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{fileName}")));

                if (nuPropsIncludes != IncludesEnum.None)
                {
                    var mainItemDir = sourceFile.GetMetadata("RootDir") + sourceFile.GetMetadata("Directory");
                    Log.LogMessage($"MainItemDir:{mainItemDir}");
                    IEnumerable<ITaskItem> itemsToAdd;
                    switch (nuPropsIncludes)
                    {
                        case IncludesEnum.Folder:
                            itemsToAdd = SourceFiles.Where(itm =>
                                itm.GetMetadata("RootDir") + itm.GetMetadata("Directory") == mainItemDir &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        case IncludesEnum.FolderRecursive:
                            itemsToAdd = SourceFiles.Where(itm =>
                                (itm.GetMetadata("RootDir") + itm.GetMetadata("Directory")).StartsWith(mainItemDir) &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }

                    foreach (var item in itemsToAdd)
                    {
                        var itemFileFull = item.GetMetadata("FullPath");
                        Log.LogMessage($"itemFileFull:{itemFileFull}");
                        var itemFileRel = itemFileFull.Substring(mainItemDir.Length);
                        files.Add(
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{itemFileRel}")),
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{itemFileRel}")));
                    }
                }

                var outXDocStrNew = outXDoc.ToString();
                if (outXDocStrNew == outXDocStrOriginal) continue;

                //change - > save
                File.WriteAllText(outFile, outXDocStrNew);
                Log.LogMessage($"Generated/updated {outFile}");
            }

            if (!anyPackageAvailable)
            {
                Log.LogMessage("No source-only packages found");
            }
            return true;
        }

19 View Source File : FlightPlan.cs
License : MIT License
Project Creator : 8bitbytes

public void Save(string path)
        {
            if (Name == null)
            {
                Name = $"FP_{System.DateTime.Now.ToString().Replace("/","-").Replace(":","")}_{System.Guid.NewGuid().ToString().Replace("-", "").Substring(0, 8)}";
            }
            var contents = JsonConvert.SerializeObject(this);
            var dir = [email protected]"{System.IO.Directory.GetCurrentDirectory()}\{this.Name}.json.fp";
            System.IO.File.WriteAllText(dir, contents);
        }

19 View Source File : ControllerPopupWindow.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private void RenderInteractionList(SerializedProperty interactionList, bool useCustomInteractionMapping)
        {
            if (interactionList == null) { throw new Exception(); }

            bool noInteractions = interactionList.arraySize == 0;

            if (currentControllerOption != null && (currentControllerOption.IsLabelFlipped == null || currentControllerOption.IsLabelFlipped.Length != interactionList.arraySize))
            {
                currentControllerOption.IsLabelFlipped = new bool[interactionList.arraySize];
            }

            GUILayout.BeginVertical();

            if (useCustomInteractionMapping)
            {
                horizontalScrollPosition = EditorGUILayout.BeginScrollView(horizontalScrollPosition, false, false, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true));
            }

            if (useCustomInteractionMapping)
            {
                if (GUILayout.Button(InteractionAddButtonContent))
                {
                    interactionList.arraySize += 1;
                    var interaction = interactionList.GetArrayElementAtIndex(interactionList.arraySize - 1);
                    var axisType = interaction.FindPropertyRelative("axisType");
                    axisType.enumValueIndex = 0;
                    var inputType = interaction.FindPropertyRelative("inputType");
                    inputType.enumValueIndex = 0;
                    var action = interaction.FindPropertyRelative("inputAction");
                    var actionId = action.FindPropertyRelative("id");
                    var actionDescription = action.FindPropertyRelative("description");
                    actionDescription.stringValue = "None";
                    actionId.intValue = 0;
                }

                if (noInteractions)
                {
                    EditorGUILayout.HelpBox("Create an Interaction Mapping.", MessageType.Warning);
                    EditorGUILayout.EndScrollView();
                    GUILayout.EndVertical();
                    return;
                }
            }
            else if (EnableWysiwyg)
            {
                EditorGUI.BeginChangeCheck();
                editInputActionPositions = EditorGUILayout.Toggle("Edit Input Action Positions", editInputActionPositions);

                if (EditorGUI.EndChangeCheck())
                {
                    string editorWindowOptionsPath = ResolveEditorWindowOptionsPath();
                    if (!editInputActionPositions)
                    {
                        File.WriteAllText(editorWindowOptionsPath, JsonUtility.ToJson(controllerInputActionOptions, true));
                    }
                    else
                    {
                        if (!controllerInputActionOptions.Controllers.Any(
                            option => option.Controller == currentControllerMapping.SupportedControllerType && option.Handedness == currentControllerMapping.Handedness))
                        {
                            currentControllerOption = new ControllerInputActionOption
                            {
                                Controller = currentControllerMapping.SupportedControllerType,
                                Handedness = currentControllerMapping.Handedness,
                                InputLabelPositions = new Vector2[currentInteractionList.arraySize],
                                IsLabelFlipped = new bool[currentInteractionList.arraySize]
                            };

                            controllerInputActionOptions.Controllers.Add(currentControllerOption);
                            isMouseInRects = new bool[currentInteractionList.arraySize];

                            if (controllerInputActionOptions.Controllers.Any(option => option.Controller == 0))
                            {
                                controllerInputActionOptions.Controllers.Remove(
                                    controllerInputActionOptions.Controllers.Find(option =>
                                        option.Controller == 0));
                            }

                            File.WriteAllText(editorWindowOptionsPath, JsonUtility.ToJson(controllerInputActionOptions, true));
                        }
                    }
                }
            }

            GUILayout.BeginHorizontal();

            if (useCustomInteractionMapping)
            {
                EditorGUILayout.LabelField("Id", GUILayout.Width(32f));
                EditorGUIUtility.labelWidth = 24f;
                EditorGUIUtility.fieldWidth = 24f;
                EditorGUILayout.LabelField(ControllerInputTypeContent, GUILayout.Width(InputActionLabelWidth));
                EditorGUILayout.LabelField(AxisTypeContent, GUILayout.Width(InputActionLabelWidth));
                EditorGUILayout.LabelField(ActionContent, GUILayout.Width(InputActionLabelWidth));
                EditorGUILayout.LabelField(KeyCodeContent, GUILayout.Width(InputActionLabelWidth));
                EditorGUILayout.LabelField(XAxisContent, GUILayout.Width(InputActionLabelWidth));
                EditorGUILayout.LabelField(YAxisContent, GUILayout.Width(InputActionLabelWidth));
                GUILayout.FlexibleSpace();
                EditorGUILayout.LabelField(string.Empty, GUILayout.Width(24f));

                EditorGUIUtility.labelWidth = defaultLabelWidth;
                EditorGUIUtility.fieldWidth = defaultFieldWidth;
            }

            GUILayout.EndHorizontal();

            for (int i = 0; i < interactionList.arraySize; i++)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    SerializedProperty interaction = interactionList.GetArrayElementAtIndex(i);

                    if (useCustomInteractionMapping)
                    {
                        EditorGUILayout.LabelField($"{i + 1}", GUILayout.Width(32f));
                        var inputType = interaction.FindPropertyRelative("inputType");
                        EditorGUILayout.PropertyField(inputType, GUIContent.none, GUILayout.Width(InputActionLabelWidth));
                        var axisType = interaction.FindPropertyRelative("axisType");
                        EditorGUILayout.PropertyField(axisType, GUIContent.none, GUILayout.Width(InputActionLabelWidth));
                        var invertXAxis = interaction.FindPropertyRelative("invertXAxis");
                        var invertYAxis = interaction.FindPropertyRelative("invertYAxis");
                        var interactionAxisConstraint = interaction.FindPropertyRelative("axisType");

                        var action = interaction.FindPropertyRelative("inputAction");
                        var actionId = action.FindPropertyRelative("id");
                        var actionDescription = action.FindPropertyRelative("description");
                        var actionConstraint = action.FindPropertyRelative("axisConstraint");

                        GUIContent[] labels;
                        int[] ids;

                        switch ((AxisType)interactionAxisConstraint.intValue)
                        {
                            default:
                            case AxisType.None:
                                labels = actionLabels;
                                ids = actionIds;
                                break;
                            case AxisType.Raw:
                                labels = rawActionLabels;
                                ids = rawActionIds;
                                break;
                            case AxisType.Digital:
                                labels = digitalActionLabels;
                                ids = digitalActionIds;
                                break;
                            case AxisType.SingleAxis:
                                labels = singleAxisActionLabels;
                                ids = singleAxisActionIds;
                                break;
                            case AxisType.DualAxis:
                                labels = dualAxisActionLabels;
                                ids = dualAxisActionIds;
                                break;
                            case AxisType.ThreeDofPosition:
                                labels = threeDofPositionActionLabels;
                                ids = threeDofPositionActionIds;
                                break;
                            case AxisType.ThreeDofRotation:
                                labels = threeDofRotationActionLabels;
                                ids = threeDofRotationActionIds;
                                break;
                            case AxisType.SixDof:
                                labels = sixDofActionLabels;
                                ids = sixDofActionIds;
                                break;
                        }

                        EditorGUI.BeginChangeCheck();
                        actionId.intValue = EditorGUILayout.IntPopup(GUIContent.none, actionId.intValue, labels, ids, GUILayout.Width(InputActionLabelWidth));

                        if (EditorGUI.EndChangeCheck())
                        {
                            var inputAction = actionId.intValue == 0 ? MixedRealityInputAction.None : MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionsProfile.InputActions[actionId.intValue - 1];
                            actionDescription.stringValue = inputAction.Description;
                            actionConstraint.enumValueIndex = (int)inputAction.AxisConstraint;
                        }

                        if ((AxisType)axisType.intValue == AxisType.Digital)
                        {
                            var keyCode = interaction.FindPropertyRelative("keyCode");
                            EditorGUILayout.PropertyField(keyCode, GUIContent.none, GUILayout.Width(InputActionLabelWidth));
                        }
                        else
                        {
                            if ((AxisType)axisType.intValue == AxisType.DualAxis)
                            {
                                EditorGUIUtility.labelWidth = InputActionLabelWidth * 0.5f;
                                EditorGUIUtility.fieldWidth = InputActionLabelWidth * 0.5f;

                                int currentAxisSetting = 0;

                                if (invertXAxis.boolValue)
                                {
                                    currentAxisSetting += 1;
                                }

                                if (invertYAxis.boolValue)
                                {
                                    currentAxisSetting += 2;
                                }

                                EditorGUI.BeginChangeCheck();
                                currentAxisSetting = EditorGUILayout.IntPopup(InvertContent, currentAxisSetting, InvertAxisContent, InvertAxisValues, GUILayout.Width(InputActionLabelWidth));

                                if (EditorGUI.EndChangeCheck())
                                {
                                    switch (currentAxisSetting)
                                    {
                                        case 0:
                                            invertXAxis.boolValue = false;
                                            invertYAxis.boolValue = false;
                                            break;
                                        case 1:
                                            invertXAxis.boolValue = true;
                                            invertYAxis.boolValue = false;
                                            break;
                                        case 2:
                                            invertXAxis.boolValue = false;
                                            invertYAxis.boolValue = true;
                                            break;
                                        case 3:
                                            invertXAxis.boolValue = true;
                                            invertYAxis.boolValue = true;
                                            break;
                                    }
                                }

                                EditorGUIUtility.labelWidth = defaultLabelWidth;
                                EditorGUIUtility.fieldWidth = defaultFieldWidth;
                            }
                            else if ((AxisType)axisType.intValue == AxisType.SingleAxis)
                            {
                                invertXAxis.boolValue = EditorGUILayout.ToggleLeft("Invert X", invertXAxis.boolValue, GUILayout.Width(InputActionLabelWidth));
                                EditorGUIUtility.labelWidth = defaultLabelWidth;
                            }
                            else
                            {
                                EditorGUILayout.LabelField(GUIContent.none, GUILayout.Width(InputActionLabelWidth));
                            }
                        }

                        if ((AxisType)axisType.intValue == AxisType.SingleAxis ||
                            (AxisType)axisType.intValue == AxisType.DualAxis)
                        {
                            var axisCodeX = interaction.FindPropertyRelative("axisCodeX");
                            RenderAxisPopup(axisCodeX, InputActionLabelWidth);
                        }
                        else
                        {
                            EditorGUILayout.LabelField(GUIContent.none, GUILayout.Width(InputActionLabelWidth));
                        }

                        if ((AxisType)axisType.intValue == AxisType.DualAxis)
                        {
                            var axisCodeY = interaction.FindPropertyRelative("axisCodeY");
                            RenderAxisPopup(axisCodeY, InputActionLabelWidth);
                        }
                        else
                        {
                            EditorGUILayout.LabelField(GUIContent.none, GUILayout.Width(InputActionLabelWidth));
                        }

                        if (GUILayout.Button(InteractionMinusButtonContent, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(true)))
                        {
                            interactionList.DeleteArrayElementAtIndex(i);
                        }
                    }
                    else
                    {
                        var interactionDescription = interaction.FindPropertyRelative("description");
                        var interactionAxisConstraint = interaction.FindPropertyRelative("axisType");
                        var action = interaction.FindPropertyRelative("inputAction");
                        var actionId = action.FindPropertyRelative("id");
                        var actionDescription = action.FindPropertyRelative("description");
                        var actionConstraint = action.FindPropertyRelative("axisConstraint");

                        GUIContent[] labels;
                        int[] ids;

                        switch ((AxisType)interactionAxisConstraint.intValue)
                        {
                            default:
                            case AxisType.None:
                                labels = actionLabels;
                                ids = actionIds;
                                break;
                            case AxisType.Raw:
                                labels = rawActionLabels;
                                ids = rawActionIds;
                                break;
                            case AxisType.Digital:
                                labels = digitalActionLabels;
                                ids = digitalActionIds;
                                break;
                            case AxisType.SingleAxis:
                                labels = singleAxisActionLabels;
                                ids = singleAxisActionIds;
                                break;
                            case AxisType.DualAxis:
                                labels = dualAxisActionLabels;
                                ids = dualAxisActionIds;
                                break;
                            case AxisType.ThreeDofPosition:
                                labels = threeDofPositionActionLabels;
                                ids = threeDofPositionActionIds;
                                break;
                            case AxisType.ThreeDofRotation:
                                labels = threeDofRotationActionLabels;
                                ids = threeDofRotationActionIds;
                                break;
                            case AxisType.SixDof:
                                labels = sixDofActionLabels;
                                ids = sixDofActionIds;
                                break;
                        }

                        EditorGUI.BeginChangeCheck();

                        if (currentControllerOption == null || currentControllerTexture == null)
                        {
                            bool skip = false;
                            var description = interactionDescription.stringValue;
                            if (currentControllerMapping.SupportedControllerType == SupportedControllerType.GGVHand
                                && currentControllerMapping.Handedness == Handedness.None)
                            {
                                if (description != "Select")
                                {
                                    skip = true;
                                }
                            }

                            if (!skip)
                            {
                                actionId.intValue = EditorGUILayout.IntPopup(GUIContent.none, actionId.intValue, labels, ids, GUILayout.Width(80f));
                                EditorGUILayout.LabelField(description, GUILayout.ExpandWidth(true));
                            }
                        }
                        else
                        {
                            var rectPosition = currentControllerOption.InputLabelPositions[i];
                            var rectSize = InputActionLabelPosition + InputActionDropdownPosition + new Vector2(currentControllerOption.IsLabelFlipped[i] ? 0f : 8f, EditorGUIUtility.singleLineHeight);
                            GUI.Box(new Rect(rectPosition, rectSize), GUIContent.none, EditorGUIUtility.isProSkin ? "ObjectPickerBackground" : "ObjectPickerResultsEven");
                            var offset = currentControllerOption.IsLabelFlipped[i] ? InputActionLabelPosition : Vector2.zero;
                            var popupRect = new Rect(rectPosition + offset, new Vector2(InputActionDropdownPosition.x, EditorGUIUtility.singleLineHeight));

                            actionId.intValue = EditorGUI.IntPopup(popupRect, actionId.intValue, labels, ids);
                            offset = currentControllerOption.IsLabelFlipped[i] ? Vector2.zero : InputActionDropdownPosition;
                            var labelRect = new Rect(rectPosition + offset, new Vector2(InputActionLabelPosition.x, EditorGUIUtility.singleLineHeight));
                            EditorGUI.LabelField(labelRect, interactionDescription.stringValue, currentControllerOption.IsLabelFlipped[i] ? flippedLabelStyle : EditorStyles.label);

                            if (editInputActionPositions)
                            {
                                offset = currentControllerOption.IsLabelFlipped[i] ? InputActionLabelPosition + InputActionDropdownPosition + HorizontalSpace : InputActionFlipTogglePosition;
                                var toggleRect = new Rect(rectPosition + offset, new Vector2(-InputActionFlipTogglePosition.x, EditorGUIUtility.singleLineHeight));

                                EditorGUI.BeginChangeCheck();
                                currentControllerOption.IsLabelFlipped[i] = EditorGUI.Toggle(toggleRect, currentControllerOption.IsLabelFlipped[i]);

                                if (EditorGUI.EndChangeCheck())
                                {
                                    if (currentControllerOption.IsLabelFlipped[i])
                                    {
                                        currentControllerOption.InputLabelPositions[i] -= InputActionLabelPosition;
                                    }
                                    else
                                    {
                                        currentControllerOption.InputLabelPositions[i] += InputActionLabelPosition;
                                    }
                                }

                                if (!isMouseInRects.Any(value => value) || isMouseInRects[i])
                                {
                                    if (Event.current.type == EventType.MouseDrag && labelRect.Contains(Event.current.mousePosition) && !isMouseInRects[i])
                                    {
                                        isMouseInRects[i] = true;
                                        mouseDragOffset = Event.current.mousePosition - currentControllerOption.InputLabelPositions[i];
                                    }
                                    else if (Event.current.type == EventType.Repaint && isMouseInRects[i])
                                    {
                                        currentControllerOption.InputLabelPositions[i] = Event.current.mousePosition - mouseDragOffset;
                                    }
                                    else if (Event.current.type == EventType.DragUpdated && isMouseInRects[i])
                                    {
                                        currentControllerOption.InputLabelPositions[i] = Event.current.mousePosition - mouseDragOffset;
                                    }
                                    else if (Event.current.type == EventType.MouseUp && isMouseInRects[i])
                                    {
                                        currentControllerOption.InputLabelPositions[i] = Event.current.mousePosition - mouseDragOffset;
                                        mouseDragOffset = Vector2.zero;
                                        isMouseInRects[i] = false;
                                    }
                                }
                            }
                        }

                        if (EditorGUI.EndChangeCheck())
                        {
                            MixedRealityInputAction inputAction = actionId.intValue == 0 ?
                                MixedRealityInputAction.None :
                                MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionsProfile.InputActions[actionId.intValue - 1];
                            actionId.intValue = (int)inputAction.Id;
                            actionDescription.stringValue = inputAction.Description;
                            actionConstraint.enumValueIndex = (int)inputAction.AxisConstraint;
                            interactionList.serializedObject.ApplyModifiedProperties();
                        }
                    }
                }
            }

            if (useCustomInteractionMapping)
            {
                EditorGUILayout.EndScrollView();
                interactionList.serializedObject.ApplyModifiedProperties();
            }

            GUILayout.EndVertical();
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : AantCoder

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var date = DateTime.Now.ToString("yyyy-MM-dd-hh-mm");
            var fileName = Path.Combine(Directory.GetCurrentDirectory(), "!UnhandledException" + date + ".log");
            File.WriteAllText(fileName, e.ExceptionObject.ToString(), Encoding.UTF8);
        }

19 View Source File : FrmDoublePageReader.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private void FrmReader_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (File.Exists(root.FullName + "\\tracker"))
            {
                File.WriteAllText(root.FullName + "\\tracker", String.Empty);
                File.WriteAllText(root.FullName + "\\tracker", cmboChapter.SelectedItem.ToString() + "|" + cmboPage.SelectedItem.ToString());
            }
            startPage.RefreshContents();
        }

19 View Source File : HatchEditor.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public static bool SaveToFile(string filePath, Hatch hatch)
        {
            try {
                File.WriteAllText(filePath, hatch.PatFileString, Encoding.ASCII);
            } catch {
                //// add proper exceptions here...
            }
            return true;
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static void WriteSuricataFileResult(Options o, Dictionary<string, List<string>> techniques)
        {
            try
            {

                var entries = techniques
                    .ToList()
                    .Select(entry => new
                    {
                        techniqueID = entry.Key,
                        score = entry.Value.Count,
                        comment = (o.NoComment) ? null : string.Join(Environment.NewLine, entry.Value.Select(x => x.Split("/").Last()))
                    });

                string filename = o.OutFile.EndsWith(".json") ? "suricata-coverage.json" : $"{o.OutFile}.json";
                File.WriteAllText(filename, JsonConvert.SerializeObject(new
                {
                    domain = "mitre-enterprise",
                    name = "Suricata rules coverage",
                    gradient = new
                    {
                        colors = new[] { "#a0eab5", "#0f480f" },
                        maxValue = techniques
                            .Values
                            .Max(x => x.Count),
                        minValue = 0
                    },
                    version = "4.2",
                    techniques = entries
                }, Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
                Console.WriteLine($"[*] Layer file written in {filename} ({entries.Count()} techniques covered)");
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem writing to file: " + e.Message);
            }
        }

19 View Source File : RepositoryPlugin.cs
License : MIT License
Project Creator : actions

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            // register problem matcher
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, GitHubSourceProvider.ProblemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().CleanupAsync(executionContext);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

19 View Source File : SettingsManager.cs
License : MIT License
Project Creator : a1xd

public bool TryActivate(DriverConfig settings, out string errors)
        {
            errors = settings.Errors();

            if (errors == null)
            {
                GuiSettings = MakeGUISettingsFromFields();
                GuiSettings.Save();

                UserConfig = settings;
                ActiveConfig = settings;
                File.WriteAllText(Constants.DefaultSettingsFileName, settings.ToJSON());

                new Thread(() => ActiveConfig.Activate()).Start();
            }

            return errors == null;
        }

19 View Source File : ProjectSet.cs
License : MIT License
Project Creator : adamant

private static bool CompileCode(
            Project project,
            string cacheDir,
            string codePath,
            object consoleLock)
        {
            var compiler = new CLangCompiler();

            var runtimeLibrarySourcePath = System.IO.Path.Combine(cacheDir, CodeEmitter.RuntimeLibraryCodeFileName);
            File.WriteAllText(runtimeLibrarySourcePath, CodeEmitter.RuntimeLibraryCode, Encoding.UTF8);
            var runtimeLibraryHeaderPath = System.IO.Path.Combine(cacheDir, CodeEmitter.RuntimeLibraryHeaderFileName);
            File.WriteAllText(runtimeLibraryHeaderPath, CodeEmitter.RuntimeLibraryHeader, Encoding.UTF8);

            var sourceFiles = new[] { codePath, runtimeLibrarySourcePath };
            var headerSearchPaths = new[] { cacheDir };
            string outputPath = project.Template switch
            {
                ProjectTemplate.App => Path.ChangeExtension(codePath, "exe"),
                ProjectTemplate.Lib => Path.ChangeExtension(codePath, "dll"),
                _ => throw ExhaustiveMatch.Failed(project.Template)
            };

19 View Source File : ConfigManager.cs
License : MIT License
Project Creator : 1ZouLTReX1

private void CreateConfigFile()
    {
        string json = JsonUtility.ToJson(defaultConfig, true);
        File.WriteAllText(Application.dataPath + FILE_NAME, json);
        Debug.Log("File Created successfully");
    }

19 View Source File : ConformanceTests.cs
License : MIT License
Project Creator : adamant

private static void EmitCode(PackageIL package, PackageIL stdLibPackage, string path)
        {
            var codeEmitter = new CodeEmitter();
            codeEmitter.Emit(package);
            codeEmitter.Emit(stdLibPackage);
            File.WriteAllText(path, codeEmitter.GetEmittedCode(), Encoding.UTF8);
        }

19 View Source File : UI.cs
License : MIT License
Project Creator : aaaddress1

private void refreshUi(object sender, EventArgs e)
        {
            /* i'm too lazy to make a editor for C/C++ :P,
             * and this editor is really useful!!
             * https://github.com/PavelTorgashov/FastColoredTextBox */
            fastColoredTextBox.Language = FastColoredTextBoxNS.Language.CSharp;

            if (srcPath == "")
                srcPath = Path.Combine(Application.StartupPath, "main.cpp");

            if (!File.Exists(srcPath))
                File.WriteAllText(srcPath, Properties.Resources.templateSrc);

            fastColoredTextBox.InsertText(File.ReadAllText(srcPath));

            asmPath = Path.Combine(Path.GetDirectoryName(srcPath), Path.GetFileNameWithoutExtension(srcPath) + ".s");
            obfAsmPath = Path.Combine(Path.GetDirectoryName(srcPath), Path.GetFileNameWithoutExtension(srcPath) + "_obf.s");
            exePath = Path.Combine(Path.GetDirectoryName(srcPath), Path.GetFileNameWithoutExtension(srcPath) + ".exe");
            this.Text = string.Format("puzzCode [{0}] by [email protected]", new FileInfo(srcPath).Name);

            logBox.Clear();
            logMsg(demostr, Color.Blue);

            compiler.logText = this.logBox;
            obfuscator.logText = this.logBox;

            this.splitContainer.Panel2Collapsed = true;

            if (!new DirectoryInfo(Properties.Settings.Default.gwPath).Exists)
            {
                MessageBox.Show("please choose your MinGW path.");
                (new config()).ShowDialog();
                if (!new DirectoryInfo(Properties.Settings.Default.gwPath).Exists)
                {
                    MessageBox.Show("sorry, MinGW not found :(");
                    Application.Exit();
                }
            }
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : AantCoder

private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;
            var date = DateTime.Now.ToString("yyyy-MM-dd-hh-mm");
            var fileName = Path.Combine(path, "!UnhandledException" + date + ".log");
            File.WriteAllText(fileName, e.ExceptionObject.ToString(), Encoding.UTF8);
        }

19 View Source File : UCEditor.cs
License : MIT License
Project Creator : 2881099

private void command_save_Executed(object sender, EventArgs e)
        {
            File.WriteAllText(_path, editor.Text);
            ToastNotification.ToastBackColor = Color.Green;
            ToastNotification.ToastForeColor = Color.White;
            ToastNotification.ToastFont = new Font("微软雅黑", 22);
            ToastNotification.Show(this,"编辑成功", null, 3000, eToastGlowColor.Green, eToastPosition.TopCenter);
        }

19 View Source File : CallIncident.cs
License : Apache License 2.0
Project Creator : AantCoder

public static void IncidentLogAppend(string record, ModelMailStartIncident mail, string data, int fromWorth = 0, int toWorth = 0)
        {
            Func<DateTime, string> dateTimeToStr = dt => dt == DateTime.MinValue ? "" : dt.ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);

            var fileName = Path.Combine(Path.GetDirectoryName(Repository.Get.SaveFileName)
                , $"Incidents_{DateTime.Now.ToString("yyyy-MM")}.csv");
            if (!File.Exists(fileName))
            { 
                File.WriteAllText(fileName, $"time;record" +
                    $";fromLogin;toLogin;fromDay;toDay;fromWorth;toWorth;paramIncident;serverId" +
                    //структура data:
                    $";worthTarget;delayAfterMail;numberOrder;countInOrder" + 
                    Environment.NewLine, Encoding.UTF8);
            }

            if (fromWorth == 0) fromWorth = (int)Repository.GetPlayerByLogin(mail.From.Login).AllCostWorldObjects();
            if (toWorth == 0) toWorth = (int)Repository.GetPlayerByLogin(mail.To.Login).AllCostWorldObjects();

            var param = $"{mail.IncidentType} lvl:{mail.IncidentMult} mode:{mail.IncidentArrivalMode} who:{mail.IncidentFaction}";

            var contentLog = dateTimeToStr(DateTime.Now) + ";" + record
                + $";{mail.From.Login};{mail.To.Login};{mail.From.LastTick / 60000};{mail.To.LastTick / 60000};{fromWorth};{toWorth};{param};{mail.PlaceServerId}"
                + ";" + data + Environment.NewLine;

            Loger.Log("IncidentLogAppend. " + contentLog);

            try
            {
                File.AppendAllText(fileName, contentLog, Encoding.UTF8);
            }
            catch
            {
                try
                {
                    File.AppendAllText(fileName + "add", contentLog, Encoding.UTF8);
                }
                catch
                {
                    Loger.Log("IncidentLogAppend. Error write file " + fileName);
                }
            }
        }

19 View Source File : C4Directory.cs
License : MIT License
Project Creator : 8T4

private static void LoadResource(string resourcesPath, string resourceName)
        {
            try
            {
                var path = Path.Join(resourcesPath, $"{resourceName}.puml");

                if (File.Exists(path))
                {
                    return;
                }

                var stream = ResourceMethods.GetResource($"{resourceName}.puml");
                Directory.CreateDirectory(resourcesPath);
                File.WriteAllText(path, stream);
            }
            catch (Exception e)
            {
                throw new C4FileException("An exception occured while the package try loading the resource files", e);
            }
        }

19 View Source File : ControllerPopupWindow.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static void Show(MixedRealityControllerMapping controllerMapping, SerializedProperty interactionsList, Handedness handedness = Handedness.None)
        {
            if (window != null)
            {
                window.Close();
            }

            window = null;

            window = CreateInstance<ControllerPopupWindow>();
            window.thisWindow = window;
            window.replacedleContent = new GUIContent($"{controllerMapping.Description} - Input Action replacedignment");
            window.currentControllerMapping = controllerMapping;
            window.currentInteractionList = interactionsList;
            isMouseInRects = new bool[interactionsList.arraySize];

            string editorWindowOptionsPath = ResolveEditorWindowOptionsPath();
            if (!File.Exists(editorWindowOptionsPath))
            {
                var empty = new ControllerInputActionOptions
                {
                    Controllers = new List<ControllerInputActionOption>
                    {
                        new ControllerInputActionOption
                        {
                            Controller = 0,
                            Handedness = Handedness.None,
                            InputLabelPositions = new[] {new Vector2(0, 0)},
                            IsLabelFlipped = new []{false}
                        }
                    }
                };

                File.WriteAllText(editorWindowOptionsPath, JsonUtility.ToJson(empty, true));
                replacedetDatabase.Refresh(ImportreplacedetOptions.ForceUpdate);
            }
            else
            {
                controllerInputActionOptions = JsonUtility.FromJson<ControllerInputActionOptions>(File.ReadAllText(editorWindowOptionsPath));

                if (controllerInputActionOptions.Controllers.Any(option => option.Controller == controllerMapping.SupportedControllerType && option.Handedness == handedness))
                {
                    window.currentControllerOption = controllerInputActionOptions.Controllers.FirstOrDefault(option => option.Controller == controllerMapping.SupportedControllerType && option.Handedness == handedness);

                    if (window.currentControllerOption != null && window.currentControllerOption.IsLabelFlipped == null)
                    {
                        window.currentControllerOption.IsLabelFlipped = new bool[interactionsList.arraySize];
                    }
                }
            }

            var windowSize = new Vector2(controllerMapping.HasCustomInteractionMappings ? 896f : 768f, 512f);
            window.maxSize = windowSize;
            window.minSize = windowSize;
            window.CenterOnMainWin();
            window.ShowUtility();

            defaultLabelWidth = EditorGUIUtility.labelWidth;
            defaultFieldWidth = EditorGUIUtility.fieldWidth;
        }

19 View Source File : ServerManager.cs
License : Apache License 2.0
Project Creator : AantCoder

public void SavePlayerStatisticsFile()
        {
            try
            {
                var msg = "Command SaveListPlayerFileStats";
                Loger.Log(msg);

                Func<DateTime, string> dateTimeToStr = dt => dt == DateTime.MinValue ? "" : dt.ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);

                var content = $"Login;LastOnlineTime;LastOnlineDay;GameDays;BaseCount;CaravanCount;MarketValue;MarketValuePawn" +
                    $";AttacksWonCount;AttacksInitiatorCount;ColonistsCount;ColonistsDownCount;ColonistsBleedCount;PawnMaxSkill" +
                    $";KillsHumanlikes;KillsMechanoids;KillsBestPawnHN;KillsBestPawnH;KillsBestPawnMN;KillsBestPawnM" +
                    $";Grants;EnablePVP;EMail;DiscordUserName;IntruderKeys;StartMarketValue;StartMarketValuePawn" +
                    $";MarketValueBy15Day;MarketValuePawnBy15Day;MarketValueByHour;MarketValuePawnByHour;TicksByHour;HourInGame" + Environment.NewLine;
                foreach (var player in Repository.GetData.PlayersAll)
                {
                    var costAll = player.CostWorldObjects();

                    var newLine = $"{player.Public.Login};" +
                        $"{dateTimeToStr(player.Public.LastOnlineTime)};" +
                        $"{(int)(DateTime.UtcNow - player.Public.LastOnlineTime).TotalDays};" +
                        $"{(int)(player.Public.LastTick / 60000)};" +
                        $"{costAll.BaseCount};" +
                        $"{costAll.CaravanCount};" +
                        $"{costAll.MarketValue};" +
                        $"{costAll.MarketValuePawn};" +
                        $"{player.AttacksWonCount};" +
                        $"{player.AttacksInitiatorCount};" +
                        $"{player.GameProgress?.ColonistsCount};" +
                        $"{player.GameProgress?.ColonistsDownCount};" +
                        $"{player.GameProgress?.ColonistsBleedCount};" +
                        $"{player.GameProgress?.PawnMaxSkill};" +
                        $"{player.GameProgress?.KillsHumanlikes};" +
                        $"{player.GameProgress?.KillsMechanoids};" +
                        $"{player.GameProgress?.KillsBestHumanlikesPawnName};" +
                        $"{player.GameProgress?.KillsBestHumanlikes};" +
                        $"{player.GameProgress?.KillsBestMechanoidsPawnName};" +
                        $"{player.GameProgress?.KillsBestMechanoids};" +
                        $"{player.Public.Grants.ToString()};" +
                        $"{(player.Public.EnablePVP ? 1 : 0)};" +
                        $"{player.Public.EMail};" +
                        $"{player.Public.DiscordUserName};" +
                        $"{player.IntruderKeys};" +
                        $"{player.StartMarketValue};" +
                        $"{player.StartMarketValuePawn};" +
                        $"{player.StatMaxDeltaGameMarketValue};" +
                        $"{player.StatMaxDeltaGameMarketValuePawn};" +
                        $"{player.StatMaxDeltaRealMarketValue};" +
                        $"{player.StatMaxDeltaRealMarketValuePawn};" +
                        $"{player.StatMaxDeltaRealTicks};" +
                        $"{player.TotalRealSecond / 60f / 60f};"
                        ;
                    newLine = newLine.Replace(Environment.NewLine, " ")
                        .Replace("/r", "").Replace("/n", "");

                    content += newLine + Environment.NewLine;
                }

                var fileName = Path.Combine(Path.GetDirectoryName(Repository.Get.SaveFileName)
                    , $"Players_{DateTime.Now.ToString("yyyy-MM-dd_hh-mm")}.csv");
                File.WriteAllText(fileName, content, Encoding.UTF8);
            }
            catch (Exception e)
            {
                Loger.Log("Command Exception " + e.ToString());
            }
        }

19 View Source File : PlantumlFile.cs
License : MIT License
Project Creator : 8T4

private static void Save(Diagram diagram, string path, PlantumlSession session)
        {
            try
            {
                C4Directory.LoadResources(path);
                var filePath = Path.Combine(path, $"{diagram.Slug()}.puml");
                File.WriteAllText(filePath, diagram.ToPumlString(session.StandardLibraryBaseUrl));
            }
            catch (Exception e)
            {
                throw new PlantumlException($"{nameof(PlantumlException)}: Could not save puml file.", e);
            }
        }

19 View Source File : DevicePortal.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static async Task<string> DownloadLogFileAsync(string packageName, DeviceInfo targetDevice, ApplicationInfo appInfo = null)
        {
            Debug.replacedert(!string.IsNullOrEmpty(packageName));

            if (appInfo == null)
            {
                appInfo = await GetApplicationInfoAsync(packageName, targetDevice);
            }

            if (appInfo == null)
            {
                Debug.LogWarning($"Application '{packageName}' not found");
                return string.Empty;
            }

            string logFile = $"{Application.temporaryCachePath}/{targetDevice.MachineName}_{DateTime.Now.Year}{DateTime.Now.Month}{DateTime.Now.Day}{DateTime.Now.Hour}{DateTime.Now.Minute}{DateTime.Now.Second}_player.txt";
            var response = await Rest.GetAsync(string.Format(FileQuery, FinalizeUrl(targetDevice.IP), appInfo.PackageFullName), targetDevice.Authorization, readResponseData: true);

            if (!response.Successful)
            {
                if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
                {
                    return await DownloadLogFileAsync(packageName, targetDevice);
                }

                Debug.LogError(response.ResponseBody);
                return string.Empty;
            }

            File.WriteAllText(logFile, response.ResponseBody);
            return logFile;

        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static void WriteSigmaFileResult(Options o, int gradientMax, int ruleCount, Dictionary<string, List<string>> techniques)
        {
            try
            {
                var entries = techniques
                    .ToList()
                    .Select(entry => new
                    {
                        techniqueID = entry.Key,
                        score = entry.Value.Count,
                        comment = (o.NoComment) ? null : string.Join(Environment.NewLine, entry.Value.Select(x => x.Split("/").Last()))
                    });

                string filename = o.OutFile.EndsWith(".json") ? "sigma-coverage.json" : $"{o.OutFile}.json";
                File.WriteAllText(filename, JsonConvert.SerializeObject(new
                {
                    domain = "mitre-enterprise",
                    name = "Sigma signatures coverage",
                    gradient = new
                    {
                        colors = new[] { "#a0eab5", "#0f480f" },
                        maxValue = gradientMax,
                        minValue = 0
                    },
                    version = "4.2",
                    techniques = entries
                }, Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
                Console.WriteLine($"[*] Layer file written in {filename} ({ruleCount} rules)");
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem writing to file: " + e.Message);
            }
        }

19 View Source File : RunScriptViewModel.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public void SaveAs()
        {
            var b = SCaddinsApp.WindowManager.ShowSaveFileDialog(defaultFileName: "script.cs", defaultExtension: "*.cs", filter: "cs-script | *.cs", savePath: out var path);
            if (b.HasValue && b.Value)
            {
                File.WriteAllText(path: path, contents: Script);
                CurrentFileName = path;
            }
        }

19 View Source File : FrmHentaiSettings.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private void Save()
        {
            if (txtName.Text != "")
            {
                File.WriteAllText(m.mangaDirectory.FullName + "\\replacedle", txtName.Text);
            }
            DialogResult = DialogResult.OK;
        }

19 View Source File : RepositoryPlugin.cs
License : MIT License
Project Creator : actions

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;

                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string problemMatcher = @"    
{
    ""problemMatcher"": [
        {
            ""owner"": ""checkout-git"",
            ""pattern"": [
                {
                    ""regexp"": ""^fatal: (.*)$"",
                    ""message"": 1
                }
            ]
        }
    ]
}";
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, problemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

19 View Source File : X86Assembly.cs
License : MIT License
Project Creator : 20chan

public static byte[] CompileToMachineCode(string asmcode)
        {
            var fullcode = $".intel_syntax noprefix\n_main:\n{asmcode}";
            var path = Path.Combine(Directory.GetCurrentDirectory(), "temp");
            var asmfile = $"{path}.s";
            var objfile = $"{path}.o";
            File.WriteAllText(asmfile, fullcode, new UTF8Encoding(false));
            var psi = new ProcessStartInfo("gcc", $"-m32 -c {asmfile} -o {objfile}")
            {
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            var gcc = Process.Start(psi);
            gcc.WaitForExit();
            if (gcc.ExitCode == 0)
            {
                psi.FileName = "objdump";
                psi.Arguments = $"-z -M intel -d {objfile}";
                var objdump = Process.Start(psi);
                objdump.WaitForExit();
                if (objdump.ExitCode == 0)
                {
                    var output = objdump.StandardOutput.ReadToEnd();
                    var matches = Regex.Matches(output, @"\b[a-fA-F0-9]{2}(?!.*:)\b");
                    var result = new List<byte>();
                    foreach (Match match in matches)
                    {
                        result.Add((byte)Convert.ToInt32(match.Value, 16));
                    }

                    return result.TakeWhile(b => b != 0x90).ToArray();
                }
            }
            else
            {
                var err = gcc.StandardError.ReadToEnd();
            }

            throw new ArgumentException();
        }

19 View Source File : RepositoryPlugin.cs
License : MIT License
Project Creator : actions

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;
                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, GitHubSourceProvider.ProblemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

19 View Source File : GUISettings.cs
License : MIT License
Project Creator : a1xd

public void Save()
        {
            File.WriteAllText(Constants.GuiConfigFileName, JsonConvert.SerializeObject(this));
        }

19 View Source File : IOUtil.cs
License : MIT License
Project Creator : actions

public static void SaveObject(object obj, string path)
        {
            File.WriteAllText(path, StringUtil.ConvertToJson(obj), Encoding.UTF8);
        }

19 View Source File : BeatmapConverter.cs
License : MIT License
Project Creator : 39M

static void Convert()
    {
        Debug.Log(string.Format("Source path: {0}", beatmapPath));

        // 每个目录代表一首歌,里面按字典序放置至多三个谱面,依次为 Easy, Normal, Hard
        string[] sourceDirectories = Directory.GetDirectories(beatmapPath);
        foreach (string directoryPath in sourceDirectories)
        {
            Music music = new Music();

            // 遍历单个目录下的所有 osu 文件,对每个文件创建一个 Beatmap 对象,加到 Music 对象里面
            string[] sourceFiles = Directory.GetFiles(directoryPath, "*.osu");
            int count = 0;
            foreach (string filepath in sourceFiles)
            {
                string[] lines = File.ReadAllLines(filepath);

                Beatmap beatmap = new Beatmap();
                music.beatmapList.Add(beatmap);

                #region Set Difficulty
                beatmap.difficultyName = difficultyNames[Mathf.Min(count, difficultyNames.Length - 1)];
                beatmap.difficultyDisplayColor = new SimpleColor(difficultyColors[Mathf.Min(count, difficultyNames.Length - 1)]);
                count++;
                #endregion

                #region Processing file line by line
                bool startProcessNotes = false;
                foreach (string line in lines)
                {
                    if (line.StartsWith("[HitObjects]"))
                    {
                        startProcessNotes = true;
                        continue;
                    }

                    if (!startProcessNotes)
                    {
                        // 处理谱面信息

                        int lastIndex = line.LastIndexOf(':');
                        if (lastIndex < 0)
                        {
                            // 如果不是有效信息行则跳过
                            continue;
                        }

                        string value = line.Substring(lastIndex + 1).Trim();

                        if (line.StartsWith("replacedle"))
                        {
                            music.replacedle = value;
                        }
                        else if (line.StartsWith("Artist"))
                        {
                            music.artist = value;
                        }
                        else if (line.StartsWith("AudioFilename"))
                        {
                            value = value.Remove(value.LastIndexOf('.'));
                            music.audioFilename = value;
                            music.bannerFilename = value;
                            music.soundEffectFilename = value;
                        }
                        else if (line.StartsWith("PreviewTime"))
                        {
                            music.previewTime = float.Parse(value) / 1000;
                        }
                        else if (line.StartsWith("Creator"))
                        {
                            beatmap.creator = value;
                        }
                        else if (line.StartsWith("Version"))
                        {
                            beatmap.version = value;
                        }
                    }
                    else
                    {
                        // 开始处理 HitObject

                        string[] noteInfo = line.Split(',');
                        int type = int.Parse(noteInfo[3]);

                        if ((type & 0x01) != 0)
                        {
                            // Circle
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Circle 相关的处理
                            });
                        }
                        else if ((type & 0x02) != 0)
                        {
                            // Slider
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Slider 相关的处理
                            });
                        }
                        else if ((type & 0x08) != 0)
                        {
                            // Spinner
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Spinner 相关的处理
                            });

                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[5]) / 1000,
                                // 其他 Spinner 相关的处理
                            });
                        }
                    }
                }
                #endregion
            }

            string targetPath = directoryPath + ".json";
            if (File.Exists(targetPath))
            {
                File.Delete(targetPath);
            }
            File.WriteAllText(targetPath, music.ToJson());

            Debug.Log(string.Format("Converted osu! beatmap\n[{0}]\nto json file\n[{1}]", directoryPath, targetPath));
        }

        Debug.Log(string.Format("All done, converted {0} files.", sourceDirectories.Length));
    }

19 View Source File : SetEnvFileCommandL0.cs
License : MIT License
Project Creator : actions

private void WriteContent(
            string path,
            List<string> content,
            string newline = null)
        {
            if (string.IsNullOrEmpty(newline))
            {
                newline = Environment.NewLine;
            }

            var encoding = new UTF8Encoding(true); // Emit BOM
            var contentStr = string.Join(newline, content);
            File.WriteAllText(path, contentStr, encoding);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : a1xd

static void Main(string[] args)
        {
            try
            {
                VersionHelper.ValidOrThrow();
            }
            catch (InteropException e)
            {
                Exit(e.Message);
            }

            try
            {
                if (args.Length != 1)
                {
                    if (File.Exists(DefaultPath))
                    {
                        Exit(Usage);
                    }
                    else
                    {
                        File.WriteAllText(DefaultPath, DriverConfig.GetDefault().ToJSON());
                        Exit($"{Usage}\n(generated default settings file '{DefaultPath}')");
                    }
                }
                else
                {
                    var result = DriverConfig.Convert(File.ReadAllText(args[0]));
                    if (result.Item2 == null)
                    {
                        result.Item1.Activate();
                    }
                    else
                    {
                        Exit($"Bad settings:\n\n{result.Item2}");
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                Exit(e.Message);
            }
            catch (JsonException e)
            {
                Exit($"Settings format invalid:\n\n{e.Message}");
            }
            catch (Exception e)
            {
                Exit($"Error:\n\n{e}");
            }
        }

19 View Source File : MainWindow.cs
License : MIT License
Project Creator : adainrivers

public void SaveConfiguration()
        {
            var configuration = new Configuration
            {
                WindowLocation = Location,
                WindowState = WindowState,
                GameUILanguage = LanguageDropdown.Text,
                Size = Size,
                UploadToServer = UploadToServer.Checked,
                Server = Server.Text,
                Region = Region.Text

            };
            File.WriteAllText(ConfigurationFile, JsonConvert.SerializeObject(configuration));
        }

19 View Source File : RouteGeneratorTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public void TestApiRouteGenerator()
        {
            try
            {
                var routeInfos = new TestSite(nameof(Api)).GetAllRouteInfo();
                var json = JsonConvert.SerializeObject(routeInfos, Formatting.Indented);
                Console.WriteLine(json);
                DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory);

                var file = Directory.GetFiles(di.Parent.Parent.Parent.Parent.FullName, "json.json", SearchOption.AllDirectories).FirstOrDefault();
                File.WriteAllText(file, json);
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

19 View Source File : ProjectSet.cs
License : MIT License
Project Creator : adamant

private static string EmitCode(Project project, PackageIL package, string cacheDir)
        {
            var emittedPackages = new HashSet<PackageIL>();
            var packagesToEmit = new Queue<PackageIL>();
            packagesToEmit.Enqueue(package);

            var codeEmitter = new CodeEmitter();
            while (packagesToEmit.TryDequeue(out var currentPackage))
            {
                if (!emittedPackages.Contains(currentPackage))
                {
                    codeEmitter.Emit(currentPackage);
                    emittedPackages.Add(currentPackage);
                    packagesToEmit.EnqueueRange(currentPackage.References);
                }
            }

            string outputPath;
            switch (project.Template)
            {
                case ProjectTemplate.App:
                {
                    outputPath = Path.Combine(cacheDir, "program.c");
                }
                break;
                case ProjectTemplate.Lib:
                {
                    outputPath = Path.Combine(cacheDir, "lib.c");
                }
                break;
                default:
                    throw ExhaustiveMatch.Failed(project.Template);
            }

            File.WriteAllText(outputPath, codeEmitter.GetEmittedCode(), Encoding.UTF8);

            return outputPath;
        }

19 View Source File : UI.cs
License : MIT License
Project Creator : aaaddress1

private void compile_Click(object sender, EventArgs e)
        {

            (new System.Threading.Thread(() =>
            {
                this.Invoke((MethodInvoker)delegate () {
                    compile.Enabled = false;
                    logBox.Clear();
                    logMsg(demostr, Color.Blue);
                    this.splitContainer.Panel2Collapsed = false;
                    this.logPanelBtn.Text = "x";
                });
                File.WriteAllText(srcPath, this.fastColoredTextBox.Text);
                File.Delete(exePath);
                File.Delete(asmPath);
                File.Delete(obfAsmPath);

                logMsg(" --- \n", Color.Blue);
                logMsg(string.Format(
                        "[\tInfo\t] current compile info... \n" +
                        " - source: {0}\n" +
                        " - asm path: {1}\n" +
                        " - obfuscated asm path: {2}\n" +
                        " - output exe path: {3}\n", srcPath, asmPath, obfAsmPath, exePath), Color.Blue);

                if (compiler.geneateAsmSource(srcPath, asmPath))
                    logMsg("[\tOK\t] generate replacedembly code of source code.", Color.Green);
                else
                {
                    logMsg("[\tFail\t] generate replacedembly code of sorce code failure ...", Color.Red);
                    this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
                    return;
                }

                if (obfuscator.obfuscaAsm(asmPath, obfAsmPath))
                    logMsg("[\tOK\t] generate obfuscated replacedembly code of source code.", Color.Green);
                else
                {
                    logMsg("[\tFail\t] generate obfuscated replacedembly code of sorce code failure ...", Color.Red);
                    this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
                    return;
                }
                if (compiler.generateExe(obfAsmPath, exePath))
                {
                    var arr = System.IO.File.ReadAllBytes(exePath);
                    var size = arr.Length;
                    var md5 = BitConverter.ToString(MD5.Create().ComputeHash(arr)).Replace("-", "");
                    var sha256 = BitConverter.ToString(SHA256.Create().ComputeHash(arr)).Replace("-", "");
                    logMsg("[\tInfo\t] exe size: " + size + " bytes", Color.Blue);
                    logMsg("[\tInfo\t] MD5: " + md5, Color.Blue);
                    logMsg("[\tInfo\t] SHA256: " + sha256, Color.Blue);
                    logMsg("[\tOK\t] generate executable file successfully :)", Color.Green);
                }
                else
                    logMsg("[\tFail\t] generate executable file failure ... o___O", Color.Red);
 
                if (Properties.Settings.Default.clnAftCompile)
                {
                    File.Delete(asmPath);
                    File.Delete(obfAsmPath);
                }
                this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
            })
            { IsBackground = true }).Start();
        }

19 View Source File : NotchSolutionDebugger.cs
License : MIT License
Project Creator : 5argon

void Update()
    {
        sb.Clear();
        ClearRects();

        switch (menu)
        {
            case Menu.Home:
                export.gameObject.SetActive(true);
                sb.AppendLine($"<b>-- PLEASE ROTATE THE DEVICE TO GET BOTH ORIENTATION'S DETAILS! --</b>\n");

                var safeArea = RelativeToReal(NotchSolutionUtility.ShouldUseNotchSimulatorValue ? storedSimulatedSafeAreaRelative : NotchSolutionUtility.ScreenSafeAreaRelative);

                PlaceRect(safeArea, Color.red);
                if (Screen.orientation != NotchSolutionUtility.GetCurrentOrientation())
                    safeArea.Set(Screen.width - safeArea.x, Screen.height - safeArea.y, safeArea.width, safeArea.height);
                sb.AppendLine($"Safe area : {safeArea}\n");

#if UNITY_2019_2_OR_NEWER
#if UNITY_EDITOR
                var relativeCutouts = NotchSolutionUtility.ShouldUseNotchSimulatorValue ? storedSimulatedCutoutsRelative : NotchSolutionUtility.ScreenCutoutsRelative;
                List<Rect> rectCutouts = new List<Rect>();
                foreach (Rect rect in relativeCutouts) rectCutouts.Add(RelativeToReal(rect));
                var cutouts = rectCutouts.ToArray();
#else
                var cutouts = Screen.cutouts;
#endif
                foreach (Rect r in cutouts) PlaceRect(r, Color.blue);

                if (Screen.orientation != NotchSolutionUtility.GetCurrentOrientation())
                {
                    foreach (Rect rect in cutouts) rect.Set(Screen.width - rect.x, Screen.height - rect.y, rect.width, rect.height);
                }
                sb.AppendLine($"Cutouts : {string.Join(" / ", cutouts.Select(x => x.ToString()))} \n");
#endif

                sb.AppendLine($"Current resolution : {Screen.currentResolution}\n");
                sb.AppendLine($"All Resolutions : {string.Join(" / ", Screen.resolutions.Select(x => x.ToString()))}\n");
                sb.AppendLine($"DPI : {Screen.dpi} WxH : {Screen.width}x{Screen.height} Orientation : {Screen.orientation}\n");
                var joinedProps = string.Join(" / ", typeof(SystemInfo).GetProperties(BindingFlags.Public | BindingFlags.Static).Select(x => $"{x.Name} : {x.GetValue(null)}"));
                sb.AppendLine(joinedProps);

                break;
            case Menu.Extracting:
                var screen = device.Screens.FirstOrDefault();
                export.gameObject.SetActive(false);

                if (screen.orientations.Count == 4)
                {
                    string path = Application.persistentDataPath + "/" + device.Meta.friendlyName + ".device.json";
                    System.IO.File.WriteAllText(path, JsonUtility.ToJson(device));
                    sb.AppendLine("<b>Done</b>");
                    sb.AppendLine("");
                    sb.AppendLine($"File saved at <i>{path}</i>");
                    StartCoroutine(exportDone());
                }
                else sb.AppendLine("Extracting...");

                break;
        }
        debugText.text = sb.ToString();
    }

19 View Source File : CodeGenerator.cs
License : MIT License
Project Creator : 188867052

public bool Generate(CommondConfig config)
        {
            var context = this.modelGenerator.GenerateCodeAsync(config).Result;
            if (string.IsNullOrEmpty(context))
            {
                return false;
            }

            Console.WriteLine(context);

            string fullPath = Path.Combine(config.ProjectPath, config.OutPutFile);

            Console.WriteLine($"Writing file to {fullPath}...");
            File.WriteAllText(fullPath, context);
            Console.WriteLine("Completed.");

            return true;
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n

private void button1_Click(object sender, EventArgs e)
        {
            if ((textBox2.Enabled) && (textBox2.Text.Trim() == ""))
            {
                MessageBox.Show("注入进程时应按照要求填写进程名或 pid", "警告");
                return;
            }
            string file_type = comboBox1.Text;
            string target_arch = null;
            Compiler compiler = new Compiler();
            target_arch = " /platform:x86 /optimize ";

            switch (file_type)
            {
                case ".exe":
                    saveFileDialog1.Filter = "可执行文件|*.exe";
                    break;
                case ".js":
                    saveFileDialog1.Filter = "js脚本|*.js";
                    break;
                case ".xsl":
                    saveFileDialog1.Filter = "xsl文件|*.xsl";
                    break;
            }
            DialogResult dr = saveFileDialog1.ShowDialog();

            if (dr == DialogResult.OK && saveFileDialog1.FileName.Length > 0)
            {
                switch (file_type)
                {
                    case ".exe":
                        if (radioButton2.Checked)
                        {
                            target_arch = " /platform:x64 /optimize";
                        }

                        if (checkBox2.Checked)
                        {
                            target_arch += "/target:winexe ";
                        }

                        if (ico_filename != null)
                        {
                            target_arch += " /win32icon:" + ico_filename;
                        }

                        KEY = Random_Key();
                        List<string> temp_list = new List<string>();
                        foreach (byte i in KEY)
                        {
                            temp_list.Add("0x" + i.ToString("X2"));
                        }
                        KEY_String = string.Join(",", temp_list); //生成key的字符串形式,用于写入到文件


                        switch (comboBox4.Text)
                        {
                            case "直接执行(VirtualAlloc)":
                                TP_VirtualAlloc va = new TP_VirtualAlloc(KEY_String, Handle_Payload());
                                compiler.compileToExe(va.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "直接执行(VirtualProtect)":
                                TP_VirtualProtect vp = new TP_VirtualProtect(KEY_String, Handle_Payload());
                                compiler.compileToExe(vp.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "[x64]新进程注入(SYSCALL)":
                                TP_Syscall_New scn = new TP_Syscall_New(KEY_String, Handle_Payload(), textBox2.Text.Trim());
                                target_arch += " /unsafe"; //必需,因为包含了不安全代码
                                compiler.compileToExe(scn.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "新进程注入(VirtualAllocEx)":
                                TP_VirtualAllocEx vaex = new TP_VirtualAllocEx(KEY_String, Handle_Payload(), textBox2.Text);
                                compiler.compileToExe(vaex.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "注入现有进程(VirtualAllocEx)":
                                TP_VirtualAllocEx_Exist vaee = new TP_VirtualAllocEx_Exist(KEY_String, Handle_Payload(), Convert.ToInt32(textBox2.Text.Trim()));
                                compiler.compileToExe(vaee.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "[x64]注入现有进程(SYSCALL)":
                                TP_Syscall_Exist sce = new TP_Syscall_Exist(KEY_String, Handle_Payload(), Convert.ToInt32(textBox2.Text.Trim()));
                                target_arch += " /unsafe"; //必需,因为包含了不安全代码
                                compiler.compileToExe(sce.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "进程镂空(Process Hollowing)":
                                TP_Process_Hollowing ph = new TP_Process_Hollowing(KEY_String, Handle_Payload(), textBox2.Text);
                                target_arch += " /unsafe"; //必需,因为包含了不安全代码
                                compiler.compileToExe(ph.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                        }
                        break;
                    default:
                        string temp = Generate_JS_XSL(file_type);
                        System.IO.File.WriteAllText(saveFileDialog1.FileName, temp);
                        break;
                }
                MessageBox.Show("All seems fine. Lets Hack the Plant!\r\n\r\nWARNING: 不要将生成的程序上传到在线杀毒网站!", "ALL SUCCESS!");
            }
        }

19 View Source File : Admin.cs
License : MIT License
Project Creator : 2881099

static void MakeTemplateFile(string tplName, string tplCode) {
			var tplPath = _tplViewDir + [email protected]"{tplName}";
			if (newTpl.ContainsKey(tplPath) == false) {
				var lck = newTplLock.GetOrAdd(tplPath, ent => new object());
				lock (lck) {
					if (newTpl.ContainsKey(tplPath) == false) {
						if (File.Exists(tplPath)) File.Delete(tplPath);
						File.WriteAllText(tplPath, tplCode, Encoding.UTF8);
						newTpl.TryAdd(tplPath, true);
					}
				}
			}
		}

19 View Source File : Manga.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private void CreateSettings()
        {
            Logger.Log("Creating settings for manga '" + name + "'");
            File.WriteAllText(mangaDirectory.FullName + "\\settings",
                Properties.Settings.Default["languageCode"].ToString() + "|{Any}");
            LoadSettings();
        }

19 View Source File : DataBaseManager.cs
License : MIT License
Project Creator : Abdesol

private void UpdatePref()
        {
            var json = JsonConvert.SerializeObject(prefModel);
            File.WriteAllText(prefpath, json);
        }

See More Examples