public async Task <ApiResponse <PatchResult> > Patch(string name, [FromBody] ActorInputDto dto)
        {
            var patched = await _actorService.Patch(name, dto);

            var result = new PatchResult(patched);

            if (patched <= 0)
            {
                return(ApiResponse.NotFound(Response, "actor not found", result));
            }
            return(ApiResponse.OK(result));
        }
        private void ThreadCreatePatchFunction()
        {
            try
            {
                Result = CreatePatch();
            }
            catch (Exception e)
            {
                Result = PatchResult.Failed;
                Log(e.ToString());
            }

            IsRunning = false;
        }
        public override PatchResult Apply(Patcher Patchy)
        {
            var offset       = Patchy.GetSimpleOffset(Pattern);
            var replaceStart = offset + Pattern.Length + 3;
            var bk           = Patchy.PatchData(replaceStart, PatchData);

            var result = new PatchResult()
            {
                Success           = true,
                OverwrittenBackup = new PatchedDataBackup[] { bk }
            };

            return(result);
        }
Exemple #4
0
		private void ProcessPatchResult(IHttpContext context, string docId, PatchResult patchResult, object debug)
		{
				switch (patchResult)
				{
					case PatchResult.DocumentDoesNotExists:
						context.SetStatusToNotFound();
						break;
					case PatchResult.Patched:
						context.Response.AddHeader("Location", Database.Configuration.GetFullUrl("/docs/" + docId));
						context.WriteJson(new {Patched = true, Debug = debug});
						break;
					default:
						throw new ArgumentOutOfRangeException("Value " + patchResult + " is not understood");
				}
		}
        PatchResult Patch(AssemblyInfoFile assemblyInfoFile,
            AssemblyVersion assemblyVersion,
            AssemblyFileVersion assemblyFileVersion, AssemblyMetaData assemblyMetaData = null)
        {
            CheckArguments(assemblyInfoFile, assemblyVersion, assemblyFileVersion);


            var patchResult = new PatchResult();

            AssemblyInfoPatchResult result = PatchAssemblyInfo(assemblyVersion, assemblyFileVersion, assemblyInfoFile, assemblyMetaData);

            patchResult.Add(result);

            return patchResult;
        }
Exemple #6
0
        private void ProcessAureliaPatch(PatchResult f, int templateId, string sourcePath)
        {
            var dRoot = Path.Combine(ContentRootPath, $"Content\\{templateId}\\destination");

            var sRel = $"\\content\\{templateId}\\source\\";
            var dRel = $"\\content\\{templateId}\\destination\\";

            var fromPath = CLICFileUtils.GetTemplatePath(ContentRootPath, templateId.ToString(), TemplatePathType.Destination) + f.DestinationFile.Replace(dRel, "");

            var mappedSourceFile = tfm.MapSourceFile(f.SourceFile);
            var toPath           = Path.Combine(sourcePath, mappedSourceFile.Replace(sRel, ""));//need to map the sourcepath file (which can be of a different name) to the destination (patched) file: Eg/ MyProject1.sln > Site.sln

            var d = Path.GetDirectoryName(toPath);

            if (!Directory.Exists(d))
            {
                Directory.CreateDirectory(d);
            }

            if (f.PatchResultType == PatchResultType.CopyFile && (!File.Exists(toPath)))
            {
                File.Copy(fromPath, toPath, true);
                Console.WriteLine($"Copying: {toPath}");
                return;
            }

            if (f.PatchResultType == PatchResultType.Identical)
            {
                return;
            }

            if (f.PatchList == null)
            {
                return;
            }

            var content = File.ReadAllText(toPath);

            var dmp = new diff_match_patch();
            var r   = dmp.patch_apply(f.PatchList, content);

            //Apply any text transforms

            var newContent = r[0];

            File.WriteAllText(toPath, newContent.ToString());
            Console.WriteLine($"Patched: {toPath}");
        }
        public IEnumerable<PatchResult> Unpatch(PatchResult patchResult)
        {
            _logger.WriteVerbose(string.Format("Unpatching from patch result {0}", string.Join(Environment.NewLine, patchResult.Select(item => item.ToString()))));

            List<PatchResult> result =
                patchResult.Select(
                    file =>
                    {
                        var assemblyInfoFile = new AssemblyInfoFile(file.FullPath);
                        return Patch(assemblyInfoFile, file.OldAssemblyVersion, file.OldAssemblyFileVersion, file.OldAssemblyMetadata);
                    }).ToList();

            DeleteEmptySubDirs(new DirectoryInfo(BackupBasePath()), true);

            return result;
        }
Exemple #8
0
        private void ProcessPatchResult(IHttpContext context, string docId, PatchResult patchResult, object debug)
        {
            switch (patchResult)
            {
            case PatchResult.DocumentDoesNotExists:
                context.SetStatusToNotFound();
                break;

            case PatchResult.Patched:
                context.Response.AddHeader("Location", Database.Configuration.GetFullUrl("/docs/" + docId));
                context.WriteJson(new { Patched = true, Debug = debug });
                break;

            default:
                throw new ArgumentOutOfRangeException("Value " + patchResult + " is not understood");
            }
        }
Exemple #9
0
        public void Run()
        {
            if (Progress == null)
            {
                Progress = new DummyProgressReporter();
            }

            try {
                Result = FileModExec.ExecuteMods(Path, Storage, Mods, Progress);
            } catch (Exception ex) {
                Progress.Error("Error while patching game files: " + ex.Message);
                Progress.Finish(false);
                return;
            }

            Progress.Message("Successfully patched game files.");
            Progress.Finish(true);
        }
Exemple #10
0
        public async Task <PatchResult> ExecuteAndConvertToResult(PatchRequestArgument argument)
        {
            var response = await ExecuteAsync(argument);

            var result = new PatchResult
            {
                TotalNumberOfPagesToCoverFilteredData = response.TotalNumberOfPagesToCoverFilteredData,
                MaxPatchSize = argument.DataPatchSize,
                PatchNumber  = argument.DataPatchNumber,
                Patch        = response?.SubGrids?.Select(x =>
                {
                    var s = new SubgridDataPatchRecord_ElevationAndTime();
                    s.Populate(x);
                    return(s);
                }).ToArray()
            };

            return(result);
        }
        public void Run(string fileName, JsonPatchTest test)
        {
            var isOptional = test.Disabled;

            PatchResult result = null;

            using (new TestExecutionContext.IsolatedContext())
            {
                try
                {
                    result = test.Patch.Apply(test.Doc);

                    Assert.AreNotEqual(test.ExpectsError, result.IsSuccess);

                    if (test.HasExpectedValue)
                    {
                        Assert.IsTrue(test.ExpectedValue.IsEquivalentTo(result.Result));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine();
                    Console.WriteLine(fileName);
                    Console.WriteLine(JsonSerializer.Serialize(test, _options));
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    if (result != null)
                    {
                        if (result.Result.ValueKind != JsonValueKind.Undefined)
                        {
                            Console.WriteLine(result.Result.GetRawText());
                        }
                        Console.WriteLine(result.Error);
                    }
                    if (isOptional)
                    {
                        Assert.Inconclusive("This is an acceptable failure.  Test case failed, but was marked as 'disabled'.");
                    }
                    throw;
                }
            }
        }
Exemple #12
0
        //Add Conditions to User
        public async Task <bool> AddConditionsToUser(List <int> conditionsIntCollection)
        {
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", Settings.AccessToken);
            var method = new HttpMethod("PATCH");

            var conditionPatch = new PatchResult();

            conditionPatch.conditions = conditionsIntCollection;

            var request = new HttpRequestMessage(method, "http://healthlog-deployment.dbmvyepwfm.us-east-1.elasticbeanstalk.com/api/users/me/")
                          //var request = new HttpRequestMessage(method, "https://foodsafe.requestcatcher.com/test/")

            {
                Content = new StringContent(
                    JsonConvert.SerializeObject(conditionPatch),
                    Encoding.UTF8, "application/json")
            };
            var response = await _client.SendAsync(request);

            return(response.IsSuccessStatusCode);
        }
Exemple #13
0
        public PatchResult Apply(Patch patch)
        {
            CheckNotDisposed();
            Helper.ValidateStream(_stream, true, true);

            foreach (var entry in patch.Entries)
            {
                var validateResult = ValidateEntry(entry);
                if (!validateResult.Item1)
                {
                    return(PatchResult.MakeFail(validateResult.Item2));
                }

                var applyResult = ApplyEntry(entry, validateResult.Item3);
                if (!applyResult.Item1)
                {
                    return(PatchResult.MakeFail(applyResult.Item2));
                }
            }

            return(PatchResult.MakeSuccess());
        }
Exemple #14
0
        private void btnLoad_Click(object sender, EventArgs e)
        {
            PatchResult result = PatchClient();

            switch (result)
            {
            case PatchResult.CouldNotFindClient: toolStripStatusLabel1.Text = "Could not find client!"; break;

            case PatchResult.CouldNotPatchRSA: toolStripStatusLabel1.Text = "Could not patch RSA key!"; break;

            case PatchResult.CouldNotPatchServerList: toolStripStatusLabel1.Text = "Could not patch server list!"; break;

            case PatchResult.CouldNotPatchServer: toolStripStatusLabel1.Text = "Could not patch new server!"; break;

            case PatchResult.AlreadyPatched: toolStripStatusLabel1.Text = "Client already patched!"; break;

            case PatchResult.AlreadyPatchedNotOwned:
            {
                toolStripStatusLabel1.Text = "Client already patched by another instance!";
                toolTip.Show("To use otloader you must restart the client.", btnLoad, 5000);
                break;
            }

            case PatchResult.Success:
            {
                toolStripStatusLabel1.Text = "Client patched.";
                if (checkBoxAutoAdd.Checked)
                {
                    AddFavorite(true);
                }

                isClientPatched = true;
                break;
            }

            default: break;
            }
        }
Exemple #15
0
        private void ThreadCreatePatchFunction()
        {
            try
            {
                Result = CreatePatch();
            }
            catch (Exception e)
            {
                Log(e.ToString());
                Result = PatchResult.Failed;
            }

            try
            {
                if (listener != null)
                {
                    listener.Finished();
                }
            }
            catch { }

            IsRunning = false;
        }
Exemple #16
0
        public async Task Test_patch_should_return_original_doc_if_patch_status_is_not_modified()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    session.Store(new User(), "users/1");
                    session.SaveChanges();
                }

                const string queryString = @"this['@metadata']['@foo'] = 'foo';";

                var rq = store.GetRequestExecutor();

                using (rq.ContextPool.AllocateOperationContext(out var ctx))
                {
                    var cmd = new PatchOperation.PatchCommand(store.Conventions, ctx, "users/1", changeVector: null,
                                                              new PatchRequest
                    {
                        Script = queryString
                    }, patchIfMissing: null, skipPatchIfChangeVectorMismatch: false, returnDebugInformation: false,
                                                              test: true);

                    await rq.ExecuteAsync(cmd, ctx);

                    PatchResult commandResult = cmd.Result;

                    Assert.True(commandResult.Status == PatchStatus.NotModified);

                    var metadata = commandResult.ModifiedDocument.GetMetadata();
                    Assert.NotNull(metadata);

                    Assert.False(metadata.TryGet("@foo", out object _));
                }
            }
        }
Exemple #17
0
            public static List <PatchResult> DiffPatch(string[] file1, string[] file2)
            {
                // We apply the LCD to build a JSON representation of a
                // diff(1)-style patch.

                var result = new List <PatchResult>();
                var tail1  = file1.Length;
                var tail2  = file2.Length;

                for (var candidate = Diff.LongestCommonSubsequence(file1, file2);
                     candidate != null;
                     candidate = candidate.Chain)
                {
                    var mismatchLength1 = tail1 - candidate.File1Index - 1;
                    var mismatchLength2 = tail2 - candidate.File2Index - 1;
                    tail1 = candidate.File1Index;
                    tail2 = candidate.File2Index;

                    if (mismatchLength1 > 0 || mismatchLength2 > 0)
                    {
                        PatchResult thisResult = new PatchResult
                        {
                            File1 = new PatchDescriptionThing(file1,
                                                              candidate.File1Index + 1,
                                                              mismatchLength1),
                            File2 = new PatchDescriptionThing(file2,
                                                              candidate.File2Index + 1,
                                                              mismatchLength2)
                        };
                        result.Add(thisResult);
                    }
                }

                result.Reverse();
                return(result);
            }
Exemple #18
0
        private HttpResponseMessage ProcessPatchResult(string docId, PatchResult patchResult, object debug, RavenJObject document)
        {
            switch (patchResult)
            {
            case PatchResult.DocumentDoesNotExists:
                return(GetEmptyMessage(HttpStatusCode.NotFound));

            case PatchResult.Patched:
                var msg = GetMessageWithObject(new { Patched = true, Debug = debug });
                msg.Headers.Location = Database.Configuration.GetFullUrl("docs/" + docId);
                return(msg);

            case PatchResult.Tested:
                return(GetMessageWithObject(new
                {
                    Patched = false,
                    Debug = debug,
                    Document = document
                }));

            default:
                throw new ArgumentOutOfRangeException("Value " + patchResult + " is not understood");
            }
        }
        public PatchResult Patch(IReadOnlyCollection<AssemblyInfoFile> assemblyInfoFiles, AssemblyVersion assemblyVersion, AssemblyFileVersion assemblyFileVersion, AssemblyMetaData assemblyMetaData = null)
        {
            CheckArguments(assemblyInfoFiles, assemblyVersion, assemblyFileVersion);

            if (!assemblyInfoFiles.Any())
            {
                return new PatchResult();
            }

            var patchResult = new PatchResult();


            List<AssemblyInfoPatchResult> patchResults = assemblyInfoFiles
                .Select(assemblyInfoFile =>
                    PatchAssemblyInfo(assemblyVersion, assemblyFileVersion, assemblyInfoFile, assemblyMetaData))
                .ToList();

            patchResults.Where(result => result.Succeeded).ToList().ForEach(patchResult.Add);

            return patchResult;
        }
		private HttpResponseMessage ProcessPatchResult(string docId, PatchResult patchResult, object debug, RavenJObject document)
		{
			switch (patchResult)
			{
				case PatchResult.DocumentDoesNotExists:
					return GetEmptyMessage(HttpStatusCode.NotFound);
				case PatchResult.Patched:
					var msg = GetMessageWithObject(new { Patched = true, Debug = debug });
					msg.Headers.Location = Database.Configuration.GetFullUrl("docs/" + docId);
					return msg;
				case PatchResult.Tested:
					return GetMessageWithObject(new
					{
						Patched = false,
						Debug = debug,
						Document = document
					});
				default:
					throw new ArgumentOutOfRangeException("Value " + patchResult + " is not understood");
			}
		}
        /// <exception cref = "DirectoryNotFoundException">Root path does not exist</exception>
        /// <exception cref = "UnauthorizedAccessException">A path needs admin priviledges to write</exception>
        /// <exception cref = "IOException">Output path is not empty</exception>
        /// <exception cref = "ArgumentException">An argument is empty</exception>
        /// <exception cref = "FormatException">Version is invalid</exception>
        public PatchCreator(string rootPath, string outputPath, string projectName, VersionCode version)
        {
            rootPath    = rootPath.Trim();
            outputPath  = outputPath.Trim();
            projectName = projectName.Trim();

            if (string.IsNullOrEmpty(rootPath))
            {
                throw new ArgumentException(Localization.Get(StringId.E_XCanNotBeEmpty, "'rootPath'"));
            }

            if (string.IsNullOrEmpty(outputPath))
            {
                throw new ArgumentException(Localization.Get(StringId.E_XCanNotBeEmpty, "'outputPath'"));
            }

            if (string.IsNullOrEmpty(projectName))
            {
                throw new ArgumentException(Localization.Get(StringId.E_XCanNotBeEmpty, "'projectName'"));
            }

            if (!version.IsValid)
            {
                throw new FormatException(Localization.Get(StringId.E_VersionCodeXIsInvalid, version));
            }

            if (!Directory.Exists(rootPath))
            {
                throw new DirectoryNotFoundException(Localization.Get(StringId.E_XDoesNotExist, rootPath));
            }

            if (!PatchUtils.CheckWriteAccessToFolder(rootPath))
            {
                throw new UnauthorizedAccessException(Localization.Get(StringId.E_AccessToXIsForbiddenRunInAdminMode, rootPath));
            }

            if (!PatchUtils.CheckWriteAccessToFolder(outputPath))
            {
                throw new UnauthorizedAccessException(Localization.Get(StringId.E_AccessToXIsForbiddenRunInAdminMode, outputPath));
            }

            if (Directory.Exists(outputPath))
            {
                if (Directory.GetFiles(outputPath).Length > 0 || Directory.GetDirectories(outputPath).Length > 0)
                {
                    throw new IOException(Localization.Get(StringId.E_DirectoryXIsNotEmpty, outputPath));
                }
            }

            previousVersionRoot = null;
            generateRepairPatch = false;

            this.previousVersion = null;
            this.version         = version;

            this.rootPath    = PatchUtils.GetPathWithTrailingSeparatorChar(rootPath);
            this.outputPath  = PatchUtils.GetPathWithTrailingSeparatorChar(outputPath);
            this.projectName = projectName;

            repairPatchOutputPath      = this.outputPath + PatchParameters.REPAIR_PATCH_DIRECTORY + Path.DirectorySeparatorChar;
            incrementalPatchOutputPath = this.outputPath + PatchParameters.INCREMENTAL_PATCH_DIRECTORY + Path.DirectorySeparatorChar;
            incrementalPatchTempPath   = this.outputPath + "Temp" + Path.DirectorySeparatorChar;

            ignoredPaths      = new HashSet <string>();
            ignoredPathsRegex = new List <Regex>()
            {
                PatchUtils.WildcardToRegex("*" + PatchParameters.VERSION_HOLDER_FILENAME_POSTFIX)
            };                                                                                                                                         // Ignore any version holder files

            logs = new Queue <string>();

            cancel     = false;
            silentMode = false;

            IsRunning = false;
            Result    = PatchResult.Failed;
        }
Exemple #22
0
        private PatchResult PatchClient()
        {
            UInt32 client = Utils.GetClientProcessId();

            if (client == 0)
            {
                return(PatchResult.CouldNotFindClient);
            }

            if (client != prevPatchedClient)
            {
                isClientPatched = false;
            }

            UInt16 port = UInt16.Parse(editPort.Text);

            if (!isClientPatched)
            {
                if (checkBoxMultiClientPatch.Checked)
                {
                    if (!Utils.PatchMultiClient())
                    {
                        toolTip.Show("Unable to patch multi client.", checkBoxMultiClientPatch, 5000);
                    }
                }

                if (Utils.isClientUsingRSA())
                {
                    PatchResult result = PatchResult.Dummy;
                    foreach (string RSAKey in clientRSAKeys)
                    {
                        if ((result = Utils.PatchClientRSAKey(RSAKey, otservKey)) == PatchResult.Success)
                        {
                            break;
                        }
                    }

                    if (result == PatchResult.AlreadyPatched)
                    {
                        return(PatchResult.AlreadyPatchedNotOwned);
                    }
                    else if (result != PatchResult.Success)
                    {
                        return(PatchResult.CouldNotPatchRSA);
                    }
                }

                bool patched = false;
                foreach (string server in clientServerList)
                {
                    if (Utils.PatchClientServer(server, editServer.Text, port) == PatchResult.Success)
                    {
                        patched = true;
                    }
                }

                if (!patched)
                {
                    return(PatchResult.CouldNotPatchServerList);
                }
            }
            else if (editServer.Text == prevPatchedServer.name && port == prevPatchedServer.port)
            {
                return(PatchResult.AlreadyPatched);
            }
            else if (Utils.PatchClientServer(prevPatchedServer.name, editServer.Text, port, true) != PatchResult.Success)
            {
                return(PatchResult.CouldNotPatchServer);
            }

            prevPatchedServer.name = editServer.Text;
            prevPatchedServer.port = port;
            prevPatchedClient      = client;

            isClientPatched = true;
            return(PatchResult.Success);
        }
Exemple #23
0
        /// <exception cref = "DirectoryNotFoundException">Root path does not exist</exception>
        /// <exception cref = "UnauthorizedAccessException">A path needs admin priviledges to write</exception>
        /// <exception cref = "IOException">Output path is not empty</exception>
        /// <exception cref = "ArgumentException">An argument is empty</exception>
        /// <exception cref = "FormatException">Version is invalid</exception>
        public PatchCreator(string rootPath, string outputPath, string projectName, VersionCode version)
        {
            rootPath    = rootPath.Trim();
            outputPath  = outputPath.Trim();
            projectName = projectName.Trim();

            if (string.IsNullOrEmpty(rootPath))
            {
                throw new ArgumentException(Localization.Get(StringId.E_XCanNotBeEmpty, "'rootPath'"));
            }

            if (string.IsNullOrEmpty(outputPath))
            {
                throw new ArgumentException(Localization.Get(StringId.E_XCanNotBeEmpty, "'outputPath'"));
            }

            if (string.IsNullOrEmpty(projectName))
            {
                throw new ArgumentException(Localization.Get(StringId.E_XCanNotBeEmpty, "'projectName'"));
            }

            if (!version.IsValid)
            {
                throw new FormatException(Localization.Get(StringId.E_VersionCodeXIsInvalid, version));
            }

            if (!Directory.Exists(rootPath))
            {
                throw new DirectoryNotFoundException(Localization.Get(StringId.E_XDoesNotExist, rootPath));
            }

            if (!PatchUtils.CheckWriteAccessToFolder(rootPath))
            {
                throw new UnauthorizedAccessException(Localization.Get(StringId.E_AccessToXIsForbiddenRunInAdminMode, rootPath));
            }

            if (!PatchUtils.CheckWriteAccessToFolder(outputPath))
            {
                throw new UnauthorizedAccessException(Localization.Get(StringId.E_AccessToXIsForbiddenRunInAdminMode, outputPath));
            }

            if (Directory.Exists(outputPath))
            {
                if (Directory.GetFileSystemEntries(outputPath).Length > 0)
                {
                    throw new IOException(Localization.Get(StringId.E_DirectoryXIsNotEmpty, outputPath));
                }
            }

            Localization.Get(StringId.Done);               // Force the localization system to be initialized with the current culture/language

            previousPatchFilesRoot = null;
            previousVersionInfo    = null;
            dontCreatePatchFilesForUnchangedFiles = false;

            generateRepairPatch    = true;
            generateInstallerPatch = true;

            previousVersionRoot = null;
            diffQuality         = 0;

            this.previousVersion = null;
            this.version         = version;

            this.rootPath    = PatchUtils.GetPathWithTrailingSeparatorChar(rootPath);
            this.outputPath  = PatchUtils.GetPathWithTrailingSeparatorChar(outputPath);
            this.projectName = projectName;

            repairPatchOutputPath      = this.outputPath + PatchParameters.REPAIR_PATCH_DIRECTORY + Path.DirectorySeparatorChar;
            installerPatchOutputPath   = this.outputPath + PatchParameters.INSTALLER_PATCH_DIRECTORY + Path.DirectorySeparatorChar;
            incrementalPatchOutputPath = this.outputPath + PatchParameters.INCREMENTAL_PATCH_DIRECTORY + Path.DirectorySeparatorChar;
            incrementalPatchTempPath   = this.outputPath + "Temp" + Path.DirectorySeparatorChar;

            ignoredPaths      = new HashSet <string>();
            ignoredPathsRegex = new List <Regex>()
            {
                PatchUtils.WildcardToRegex("*" + PatchParameters.VERSION_HOLDER_FILENAME_POSTFIX), // Ignore any version holder files
                PatchUtils.WildcardToRegex("*" + PatchParameters.LOG_FILE_NAME)                    // Or log files
            };

            compressionFormatRepairPatch      = CompressionFormat.LZMA;
            compressionFormatInstallerPatch   = CompressionFormat.LZMA;
            compressionFormatIncrementalPatch = CompressionFormat.LZMA;

            baseDownloadURL     = "";
            maintenanceCheckURL = "";

            logs = new Queue <string>();

            cancel     = false;
            silentMode = false;

            IsRunning = false;
            Result    = PatchResult.Failed;
        }
        public void Unpatch(string sourceBase)
        {
            var patcher = new AssemblyPatcher(sourceBase, _logger);
            string resultFilePath = Path.Combine(patcher.BackupBasePath(), "Patched.txt");

            if (!File.Exists(resultFilePath))
            {
                Console.WriteLine("Could not find any file '{0}'. No files were patched.", resultFilePath);
                return;
            }

            string json = File.ReadAllText(resultFilePath, Encoding.UTF8);
            var deserialized = JsonConvert.DeserializeObject<List<AssemblyInfoPatchResult>>(json);

            var patchResult = new PatchResult();

            deserialized.ForEach(patchResult.Add);

            List<AssemblyInfoPatchResult> unpatched =
                patcher.Unpatch(patchResult)
                    .SelectMany(
                        results =>
                            results.Where(
                                result =>
                                    result.AssemblyVersion.Version != result.OldAssemblyVersion.Version ||
                                    result.AssemblyFileVersion.Version != result.OldAssemblyFileVersion.Version))
                    .ToList();

            string verb = unpatched.Count == 1 ? "was" : "were";

            Console.WriteLine("{0} items {1} patched", unpatched.Count, verb);

            foreach (AssemblyInfoPatchResult result in unpatched)
            {
                Console.WriteLine("{0} changed from version {1} to version {2}", result.FullPath,
                    result.OldAssemblyVersion, result.AssemblyVersion);
            }
        }
Exemple #25
0
        public void Creation()
        {
            var result = new PatchResult();

            result.Should().NotBeNull();
        }
Exemple #26
0
        private static void CheckPublicKeyTokens(byte[] assemblyPublicKeyToken, byte[] configurationPublicKeyToken, PatchResult expectedPatchResult)
        {
            var assemblyNameDefinition = CreateMockFor <AssemblyNameDefinition>();

            assemblyNameDefinition.Setup(assemblyName => assemblyName.PublicKeyToken).Returns(assemblyPublicKeyToken);

            var assembly = FakeCommonAssemblyBuilder.Create();

            assembly.MainMonoCecilAssemblyMock.Setup(mainMonoCecilAssembly => mainMonoCecilAssembly.Name).Returns(assemblyNameDefinition.Object);

            var applicationPatcherSelfConfiguration = new ApplicationPatcherSelfConfiguration {
                MonoCecilNewPublicKeyToken = configurationPublicKeyToken
            };
            var checkAssemblyPublicKeyPatcher = new CheckAssemblyPublicKeyPatcher(applicationPatcherSelfConfiguration);
            var patchResult = checkAssemblyPublicKeyPatcher.Patch(assembly.CommonAssembly);

            patchResult.Should().Be(expectedPatchResult);
        }
        public void SavePatchResult(PatchResult patchResult)
        {
            string backupBasePath = BackupBasePath();

            if (!Directory.Exists(backupBasePath))
            {
                Directory.CreateDirectory(backupBasePath);
            }

            string resultFilePath = Path.Combine(backupBasePath, "Patched.txt");

            if (!File.Exists(resultFilePath))
            {
                using (File.Create(resultFilePath))
                {
                }
            }

            DeleteEmptySubDirs(new DirectoryInfo(backupBasePath));

            string json = JsonConvert.SerializeObject(patchResult.ToArray(), Formatting.Indented);

            File.WriteAllText(resultFilePath, json, Encoding.UTF8);
        }