public override async Task Update( IPatch patch, string correlationIdentifier) { if (null == patch) { throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNamePatch); } if (string.IsNullOrWhiteSpace(correlationIdentifier)) { throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameCorrelationIdentifier); } if (null == patch.ResourceIdentifier) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.Identifier)) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } if (null == patch.PatchRequest) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } string informationStarting = string.Format( CultureInfo.InvariantCulture, AmazonProvisioningAgentResources.InformationPatching, patch.ResourceIdentifier.SchemaIdentifier, patch.ResourceIdentifier.Identifier); ProvisioningAgentMonitor.Instance.Inform(informationStarting, true, correlationIdentifier); PatchRequest2 patchRequest = patch.PatchRequest as PatchRequest2; if (null == patchRequest) { string unsupportedPatchTypeName = patch.GetType().FullName; throw new NotSupportedException(unsupportedPatchTypeName); } if (null == patchRequest.Operations) { return; } PatchOperation operation; operation = patchRequest .Operations .SingleOrDefault( (PatchOperation item) => OperationName.Replace == item.Name && item.Path != null && string.Equals(item.Path.AttributePath, AttributeNames.ExternalIdentifier, StringComparison.Ordinal)); if (operation != null) { string externalIdentifierValue = operation.Value.Single().Value; await this.UpdateExternalIdentifier(patch.ResourceIdentifier, correlationIdentifier, externalIdentifierValue); return; } if ( !string.Equals( patch.ResourceIdentifier.SchemaIdentifier, SchemaIdentifiers.WindowsAzureActiveDirectoryGroup, StringComparison.Ordinal) ) { return; } operation = patchRequest .Operations .SingleOrDefault( (PatchOperation item) => item.Path != null && string.Equals(item.Path.AttributePath, AttributeNames.Members, StringComparison.Ordinal)); if (null == operation) { return; } await this.UpdateMembers(patch.ResourceIdentifier, operation, correlationIdentifier); }
public override async Task UpdateAsync(IPatch patch, string correlationIdentifier) { if (null == patch) { throw new ArgumentNullException(nameof(patch)); } if (null == patch.ResourceIdentifier) { throw new ArgumentException(FileProviderResources.ExceptionInvalidPatch); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.Identifier)) { throw new ArgumentException(FileProviderResources.ExceptionInvalidPatch); } if (null == patch.PatchRequest) { throw new ArgumentException(FileProviderResources.ExceptionInvalidPatch); } IInformationNotification notification = VerboseInformationNotificationFactory.Instance.FormatNotification( FileProviderResources.InformationPatching, correlationIdentifier, FileProvider.NotificationIdentifierUpdateStarting, patch.ResourceIdentifier.SchemaIdentifier, patch.ResourceIdentifier.Identifier); this.Monitor.Inform(notification); PatchRequest2Base <PatchOperation2> patchRequest = patch.PatchRequest as PatchRequest2Base <PatchOperation2>; if (null == patchRequest) { string unsupportedPatchTypeName = patch.GetType().FullName; throw new NotSupportedException(unsupportedPatchTypeName); } IRow row = await this.file.ReadRow(patch.ResourceIdentifier.Identifier); string rowSchema = null; if ( !row.Columns.TryGetValue(AttributeNames.Schemas, out rowSchema) || !string.Equals(rowSchema, patch.ResourceIdentifier.SchemaIdentifier, StringComparison.Ordinal) ) { return; } IReadOnlyDictionary <string, string> columns = FileProvider.Apply(patchRequest, rowSchema, row); IRow rowReplacement = new Row(row.Key, columns); await this.file.ReplaceRow(rowReplacement); if (string.Equals(SchemaIdentifiers.WindowsAzureActiveDirectoryGroup, rowSchema, StringComparison.OrdinalIgnoreCase)) { WindowsAzureActiveDirectoryGroup group = new GroupFactory(row).Create(); await this.UpdateMembersAsync(group, patch); } }
void Update() { base.Update(); if (updateLandscape == true) { m_terrainGrid[curCyclicIndexX, curCyclicIndexZ].GetComponent<Collider>().enabled = true; //Slow operation m_terrainGrid[prevCyclicIndexX, prevCyclicIndexZ].GetComponent<Collider>().enabled = false; UpdateTerrainNeighbors(); UpdateTerrainPositions(); } if (PatchManager.patchQueue.Count != 0) { terrainIsFlushed = false; if (patchIsFilling == false) { patchToBeFilled = PatchManager.patchQueue.Dequeue(); StartCoroutine(CountdownForPatch()); } if (patchToBeFilled != null) { patchToBeFilled.ExecutePatch(); patchToBeFilled = null; } } else if (PatchManager.patchQueue.Count == 0 && terrainIsFlushed == false) { StartCoroutine(FlushTerrain()); terrainIsFlushed = true; } }
public bool IsInstalled(IPatch patch){ return TargetPathResolver.Exists("usr/patch/.inst/" + patch.Code + ".installed"); }
/********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="indexPath">The path of indexes from the root <c>content.json</c> to this patch; see <see cref="IPatch.IndexPath"/>.</param> /// <param name="path">The path to the patch from the root content file.</param> /// <param name="assetName">The normalized asset name to intercept.</param> /// <param name="conditions">The conditions which determine whether this patch should be applied.</param> /// <param name="fromAsset">The asset key to load from the content pack instead.</param> /// <param name="fromArea">The map area from which to read tiles.</param> /// <param name="patchMode">Indicates how the map should be patched.</param> /// <param name="toArea">The map area to overwrite.</param> /// <param name="mapProperties">The map properties to change when editing a map, if any.</param> /// <param name="mapTiles">The map tiles to change when editing a map.</param> /// <param name="addWarps">The warps to add to the location.</param> /// <param name="textOperations">The text operations to apply to existing values.</param> /// <param name="updateRate">When the patch should be updated.</param> /// <param name="contentPack">The content pack which requested the patch.</param> /// <param name="parentPatch">The parent patch for which this patch was loaded, if any.</param> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="reflection">Simplifies access to private code.</param> /// <param name="normalizeAssetName">Normalize an asset name.</param> public EditMapPatch(int[] indexPath, LogPathBuilder path, IManagedTokenString assetName, IEnumerable <Condition> conditions, IManagedTokenString fromAsset, TokenRectangle fromArea, TokenRectangle toArea, PatchMapMode patchMode, IEnumerable <EditMapPatchProperty> mapProperties, IEnumerable <EditMapPatchTile> mapTiles, IEnumerable <IManagedTokenString> addWarps, IEnumerable <TextOperation> textOperations, UpdateRate updateRate, IContentPack contentPack, IPatch parentPatch, IMonitor monitor, IReflectionHelper reflection, Func <string, string> normalizeAssetName) : base( indexPath: indexPath, path: path, type: PatchType.EditMap, assetName: assetName, fromAsset: fromAsset, conditions: conditions, updateRate: updateRate, contentPack: contentPack, parentPatch: parentPatch, normalizeAssetName: normalizeAssetName ) { this.FromArea = fromArea; this.ToArea = toArea; this.PatchMode = patchMode; this.MapProperties = mapProperties?.ToArray() ?? new EditMapPatchProperty[0]; this.MapTiles = mapTiles?.ToArray() ?? new EditMapPatchTile[0]; this.AddWarps = addWarps?.Reverse().ToArray() ?? new IManagedTokenString[0]; // reversing the warps allows later ones to 'overwrite' earlier ones, since the game checks them in the listed order this.TextOperations = textOperations?.ToArray() ?? new TextOperation[0]; this.Monitor = monitor; this.Reflection = reflection; this.Contextuals .Add(this.FromArea) .Add(this.ToArea) .Add(this.MapProperties) .Add(this.MapTiles) .Add(this.AddWarps) .Add(this.TextOperations); }
/********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="indexPath">The path of indexes from the root <c>content.json</c> to this patch; see <see cref="IPatch.IndexPath"/>.</param> /// <param name="path">The path to the patch from the root content file.</param> /// <param name="assetName">The normalized asset name to intercept.</param> /// <param name="conditions">The conditions which determine whether this patch should be applied.</param> /// <param name="fromAsset">The asset key to load from the content pack instead.</param> /// <param name="fromArea">The sprite area from which to read an image.</param> /// <param name="toArea">The sprite area to overwrite.</param> /// <param name="patchMode">Indicates how the image should be patched.</param> /// <param name="updateRate">When the patch should be updated.</param> /// <param name="contentPack">The content pack which requested the patch.</param> /// <param name="parentPatch">The parent patch for which this patch was loaded, if any.</param> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="normalizeAssetName">Normalize an asset name.</param> public EditImagePatch(int[] indexPath, LogPathBuilder path, IManagedTokenString assetName, IEnumerable <Condition> conditions, IManagedTokenString fromAsset, TokenRectangle fromArea, TokenRectangle toArea, PatchImageMode patchMode, UpdateRate updateRate, IContentPack contentPack, IPatch parentPatch, IMonitor monitor, Func <string, string> normalizeAssetName) : base( indexPath: indexPath, path: path, type: PatchType.EditImage, assetName: assetName, conditions: conditions, normalizeAssetName: normalizeAssetName, fromAsset: fromAsset, updateRate: updateRate, contentPack: contentPack, parentPatch: parentPatch ) { this.FromArea = fromArea; this.ToArea = toArea; this.PatchMode = patchMode; this.Monitor = monitor; this.Contextuals .Add(fromArea) .Add(toArea); }
public void Test__Lifecycle() { IPatch[] patches = new IPatch[] { Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), }; UrlDir.UrlConfig urlConfig = UrlBuilder.CreateConfig("abc/def", new ConfigNode("NODE")); patches[00].PassSpecifier.Returns(new FirstPassSpecifier()); patches[01].PassSpecifier.Returns(new FirstPassSpecifier()); patches[02].PassSpecifier.Returns(new LegacyPassSpecifier()); patches[03].PassSpecifier.Returns(new LegacyPassSpecifier()); patches[04].PassSpecifier.Returns(new BeforePassSpecifier("mod1", urlConfig)); patches[05].PassSpecifier.Returns(new BeforePassSpecifier("MOD1", urlConfig)); patches[06].PassSpecifier.Returns(new ForPassSpecifier("mod1", urlConfig)); patches[07].PassSpecifier.Returns(new ForPassSpecifier("MOD1", urlConfig)); patches[08].PassSpecifier.Returns(new AfterPassSpecifier("mod1", urlConfig)); patches[09].PassSpecifier.Returns(new AfterPassSpecifier("MOD1", urlConfig)); patches[10].PassSpecifier.Returns(new BeforePassSpecifier("mod2", urlConfig)); patches[11].PassSpecifier.Returns(new BeforePassSpecifier("MOD2", urlConfig)); patches[12].PassSpecifier.Returns(new ForPassSpecifier("mod2", urlConfig)); patches[13].PassSpecifier.Returns(new ForPassSpecifier("MOD2", urlConfig)); patches[14].PassSpecifier.Returns(new AfterPassSpecifier("mod2", urlConfig)); patches[15].PassSpecifier.Returns(new AfterPassSpecifier("MOD2", urlConfig)); patches[16].PassSpecifier.Returns(new FinalPassSpecifier()); patches[17].PassSpecifier.Returns(new FinalPassSpecifier()); IPatchProgress progress = Substitute.For <IPatchProgress>(); PatchList patchList = new PatchList(new[] { "mod1", "mod2" }, patches, progress); IPass[] passes = patchList.ToArray(); Assert.Equal(":FIRST", passes[0].Name); Assert.Equal(new[] { patches[0], patches[1] }, passes[0]); Assert.Equal(":LEGACY (default)", passes[1].Name); Assert.Equal(new[] { patches[2], patches[3] }, passes[1]); Assert.Equal(":BEFORE[MOD1]", passes[2].Name); Assert.Equal(new[] { patches[4], patches[5] }, passes[2]); Assert.Equal(":FOR[MOD1]", passes[3].Name); Assert.Equal(new[] { patches[6], patches[7] }, passes[3]); Assert.Equal(":AFTER[MOD1]", passes[4].Name); Assert.Equal(new[] { patches[8], patches[9] }, passes[4]); Assert.Equal(":BEFORE[MOD2]", passes[5].Name); Assert.Equal(new[] { patches[10], patches[11] }, passes[5]); Assert.Equal(":FOR[MOD2]", passes[6].Name); Assert.Equal(new[] { patches[12], patches[13] }, passes[6]); Assert.Equal(":AFTER[MOD2]", passes[7].Name); Assert.Equal(new[] { patches[14], patches[15] }, passes[7]); Assert.Equal(":FINAL", passes[8].Name); Assert.Equal(new[] { patches[16], patches[17] }, passes[8]); progress.Received(patches.Length).PatchAdded(); }
private void PerformPatch() { patch = GetPatch(); patch.CurrentMessageChanged += patch_CurrentMessageChanged; patch.CurrentProgressChanged += patch_CurrentProgressChanged; string resultFile = patch.PerformPatch(); patch.CurrentMessageChanged -= patch_CurrentMessageChanged; patch.CurrentProgressChanged -= patch_CurrentProgressChanged; patch = null; SaveDFUAndTetherFiles(); SafeFile.Copy(resultFile, firmwareVersionModel.PatchedFirmwarePath, true); if (Finished != null) Finished(this, EventArgs.Empty); }
/********* ** Protected methods *********/ /// <summary>Construct an instance.</summary> /// <param name="path">The path to the patch from the root content file.</param> /// <param name="type">The patch type.</param> /// <param name="assetName">The normalized asset name to intercept.</param> /// <param name="conditions">The conditions which determine whether this patch should be applied.</param> /// <param name="updateRate">When the patch should be updated.</param> /// <param name="normalizeAssetName">Normalize an asset name.</param> /// <param name="contentPack">The content pack which requested the patch.</param> /// <param name="parentPatch">The parent <see cref="PatchType.Include"/> patch for which this patch was loaded, if any.</param> /// <param name="fromAsset">The normalized asset key from which to load the local asset (if applicable), including tokens.</param> protected Patch(LogPathBuilder path, PatchType type, IManagedTokenString assetName, IEnumerable <Condition> conditions, UpdateRate updateRate, IContentPack contentPack, IPatch parentPatch, Func <string, string> normalizeAssetName, IManagedTokenString fromAsset = null) { this.Path = path; this.Type = type; this.ManagedRawTargetAsset = assetName; this.Conditions = conditions.ToArray(); this.UpdateRate = updateRate; this.NormalizeAssetNameImpl = normalizeAssetName; this.PrivateContext = new LocalContext(scope: contentPack.Manifest.UniqueID); this.ManagedRawFromAsset = fromAsset; this.ContentPack = contentPack; this.ParentPatch = parentPatch; this.Contextuals .Add(this.Conditions) .Add(assetName) .Add(fromAsset); this.ManuallyUpdatedTokens.Add(assetName); this.ManuallyUpdatedTokens.Add(fromAsset); }
/********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="path">The path to the patch from the root content file.</param> /// <param name="assetName">The normalized asset name to intercept.</param> /// <param name="conditions">The conditions which determine whether this patch should be applied.</param> /// <param name="fromFile">The normalized asset key from which to load entries (if applicable), including tokens.</param> /// <param name="records">The data records to edit.</param> /// <param name="fields">The data fields to edit.</param> /// <param name="moveRecords">The records to reorder, if the target is a list asset.</param> /// <param name="textOperations">The text operations to apply to existing values.</param> /// <param name="updateRate">When the patch should be updated.</param> /// <param name="contentPack">The content pack which requested the patch.</param> /// <param name="parentPatch">The parent patch for which this patch was loaded, if any.</param> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="normalizeAssetName">Normalize an asset name.</param> /// <param name="tryParseFields">Parse the data change fields for an <see cref="PatchType.EditData"/> patch.</param> public EditDataPatch(LogPathBuilder path, IManagedTokenString assetName, IEnumerable <Condition> conditions, IManagedTokenString fromFile, IEnumerable <EditDataPatchRecord> records, IEnumerable <EditDataPatchField> fields, IEnumerable <EditDataPatchMoveRecord> moveRecords, IEnumerable <TextOperation> textOperations, UpdateRate updateRate, ManagedContentPack contentPack, IPatch parentPatch, IMonitor monitor, Func <string, string> normalizeAssetName, TryParseFieldsDelegate tryParseFields) : base( path: path, type: PatchType.EditData, assetName: assetName, conditions: conditions, updateRate: updateRate, contentPack: contentPack, parentPatch: parentPatch, normalizeAssetName: normalizeAssetName, fromAsset: fromFile ) { // set fields this.Records = records?.ToArray(); this.Fields = fields?.ToArray(); this.MoveRecords = moveRecords?.ToArray(); this.TextOperations = textOperations?.ToArray() ?? new TextOperation[0]; this.Monitor = monitor; this.TryParseFields = tryParseFields; // track contextuals this.Contextuals .Add(this.Records) .Add(this.Fields) .Add(this.MoveRecords) .Add(this.TextOperations) .Add(this.Conditions); }
public override Task UpdateAsync(IPatch patch, string correlationIdentifier) { if (null == patch) { throw new ArgumentNullException(nameof(patch)); } if (null == patch.ResourceIdentifier) { throw new ArgumentException(SampleServiceResources.ExceptionInvalidPatch); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.Identifier)) { throw new ArgumentException(SampleServiceResources.ExceptionInvalidPatch); } if (null == patch.PatchRequest) { throw new ArgumentException(SampleServiceResources.ExceptionInvalidPatch); } PatchRequest2 patchRequest = patch.PatchRequest as PatchRequest2; if (null == patchRequest) { string unsupportedPatchTypeName = patch.GetType().FullName; throw new NotSupportedException(unsupportedPatchTypeName); } // call service TargetUser target; try { // get user target = _storageService.RetrieveUser(new Guid(patch.ResourceIdentifier.Identifier)); // patch user Core2EnterpriseUser patched = (Core2EnterpriseUser)target; patched.Apply(patchRequest); // update user _storageService.UpdateUser((TargetUser)patched); } catch (Exception err) { switch (err.Message) { case "Conflict": throw new HttpResponseException(HttpStatusCode.Conflict); case "NotFound": throw new HttpResponseException(HttpStatusCode.NotFound); default: throw new HttpResponseException(HttpStatusCode.InternalServerError); } } return(Task.CompletedTask); }
/// <summary> /// /// </summary> /// <param name="combi"></param> /// <returns></returns> private string GenerateCombiWindowTitle(IPatch combi) { return ($"{Strings.TimbresOf} {PcgViewModel.SelectedPcgMemory.FileName}, {Strings.Combi.ToLower()} {combi.Id}: {combi.Name}"); }
private async Task UpdateMembersAsync(Resource resource, IPatch patch) { if (null == resource) { throw new ArgumentNullException(nameof(resource)); } if (null == patch) { throw new ArgumentNullException(nameof(patch)); } if (null == patch.ResourceIdentifier) { throw new ArgumentException(FileProviderResources.ExceptionInvalidPatch); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.Identifier)) { throw new ArgumentException(FileProviderResources.ExceptionInvalidPatch); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.SchemaIdentifier)) { throw new ArgumentException(FileProviderResources.ExceptionInvalidPatch); } if (null == patch.PatchRequest) { throw new ArgumentException(FileProviderResources.ExceptionInvalidPatch); } PatchRequest2Legacy patchRequest = patch.PatchRequest as PatchRequest2Legacy; if (null == patchRequest) { string unsupportedPatchTypeName = patch.GetType().FullName; throw new NotSupportedException(unsupportedPatchTypeName); } if ( !FileProvider .SchemaIdentifiersGroup .Value .Any( (string item) => string.Equals(item, patch.ResourceIdentifier.SchemaIdentifier, StringComparison.Ordinal)) ) { return; } IReadOnlyCollection <PatchOperation2> memberOperations = patchRequest .Operations .Where( (PatchOperation2 item) => item.Path != null && string.Equals(item.Path.AttributePath, AttributeNames.Members, StringComparison.Ordinal)) .ToArray(); if (!memberOperations.Any()) { return; } foreach (PatchOperation2 memberOperation in memberOperations) { if (null == memberOperation.Value) { continue; } foreach (OperationValue value in memberOperation.Value) { if (string.IsNullOrWhiteSpace(value.Value)) { continue; } Dictionary <string, string> columnsQuery = new Dictionary <string, string>() { { AttributeNames.Schemas, patch.ResourceIdentifier.SchemaIdentifier }, { AttributeNames.Identifier, patch.ResourceIdentifier.Identifier }, { AttributeNames.Members, value.Value } }; IRow[] rows = await this.file.Query(columnsQuery); switch (memberOperation.Name) { case OperationName.Add: if (rows.Any()) { break; } Member member = new Member() { Value = value.Value }; MemberColumnsFactory memberColumnsFactory = new MemberColumnsFactory(resource, member); IReadOnlyDictionary <string, string> columnsMember = memberColumnsFactory.CreateColumns(); await this.file.InsertRow(columnsMember); break; case OperationName.Remove: foreach (IRow row in rows) { await this.file.RemoveRow(row.Key); } break; } } } }
/// <summary> /// /// </summary> /// <param name="patch"></param> /// <returns></returns> public override string GetCategoryName(IPatch patch) { throw new NotSupportedException(); }
public override async Task Update(IPatch patch, string correlationIdentifier) { if (null == patch) { throw new ArgumentNullException(FileProvider.ArgumentNamePatch); } if (null == patch.ResourceIdentifier) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.Identifier)) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } if (null == patch.PatchRequest) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } string informationStarting = string.Format( CultureInfo.InvariantCulture, AzureTestProvisioningResources.InformationPatching, patch.ResourceIdentifier.SchemaIdentifier, patch.ResourceIdentifier.Identifier); ProvisioningAgentMonitor.Instance.Inform(informationStarting, true, correlationIdentifier); PatchRequest2 patchRequest = patch.PatchRequest as PatchRequest2; if (null == patchRequest) { string unsupportedPatchTypeName = patch.GetType().FullName; throw new NotSupportedException(unsupportedPatchTypeName); } IRow row = await this.file.ReadRow(patch.ResourceIdentifier.Identifier); string rowSchema = null; if ( !row.Columns.TryGetValue(AttributeNames.Schemas, out rowSchema) || !string.Equals(rowSchema, patch.ResourceIdentifier.SchemaIdentifier, StringComparison.Ordinal) ) { return; } IReadOnlyDictionary<string, string> columns; WindowsAzureActiveDirectoryGroup group = null; switch (rowSchema) { case SchemaIdentifiers.Core2EnterpriseUser: ResourceFactory<Core2EnterpriseUser> userFactory = new UserFactory(row); Core2EnterpriseUser user = userFactory.Create(); user.Apply(patchRequest); ColumnsFactory<Core2EnterpriseUser> userColumnsFactory = new UserColumnsFactory(user); columns = userColumnsFactory.CreateColumns(); break; case SchemaIdentifiers.WindowsAzureActiveDirectoryGroup: ResourceFactory<WindowsAzureActiveDirectoryGroup> groupFactory = new GroupFactory(row); group = groupFactory.Create(); group.Apply(patchRequest); ColumnsFactory<WindowsAzureActiveDirectoryGroup> groupColumnsFactory = new GroupColumnsFactory(group); columns = groupColumnsFactory.CreateColumns(); break; default: throw new NotSupportedException(patch.ResourceIdentifier.SchemaIdentifier); } IRow rowReplacement = new Row(row.Key, columns); await this.file.ReplaceRow(rowReplacement); if (group != null) { await this.UpdateMembers(group, patch); } }
/********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="path">The path to the patch from the root content file.</param> /// <param name="assetName">The normalized asset name to intercept.</param> /// <param name="conditions">The conditions which determine whether this patch should be applied.</param> /// <param name="fromAsset">The asset key to load from the content pack instead.</param> /// <param name="fromArea">The map area from which to read tiles.</param> /// <param name="toArea">The map area to overwrite.</param> /// <param name="mapProperties">The map properties to change when editing a map, if any.</param> /// <param name="mapTiles">The map tiles to change when editing a map.</param> /// <param name="updateRate">When the patch should be updated.</param> /// <param name="contentPack">The content pack which requested the patch.</param> /// <param name="parentPatch">The parent patch for which this patch was loaded, if any.</param> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="reflection">Simplifies access to private code.</param> /// <param name="normalizeAssetName">Normalize an asset name.</param> public EditMapPatch(LogPathBuilder path, IManagedTokenString assetName, IEnumerable <Condition> conditions, IManagedTokenString fromAsset, TokenRectangle fromArea, TokenRectangle toArea, IEnumerable <EditMapPatchProperty> mapProperties, IEnumerable <EditMapPatchTile> mapTiles, UpdateRate updateRate, ManagedContentPack contentPack, IPatch parentPatch, IMonitor monitor, IReflectionHelper reflection, Func <string, string> normalizeAssetName) : base( path: path, type: PatchType.EditMap, assetName: assetName, fromAsset: fromAsset, conditions: conditions, updateRate: updateRate, contentPack: contentPack, parentPatch: parentPatch, normalizeAssetName: normalizeAssetName ) { this.FromArea = fromArea; this.ToArea = toArea; this.MapProperties = mapProperties?.ToArray() ?? new EditMapPatchProperty[0]; this.MapTiles = mapTiles?.ToArray() ?? new EditMapPatchTile[0]; this.Monitor = monitor; this.Reflection = reflection; this.Contextuals .Add(this.FromArea) .Add(this.ToArea) .Add(this.MapProperties) .Add(this.MapTiles); }
private async Task UpdateMembers(Resource resource, IPatch patch) { if (null == resource) { throw new ArgumentNullException(FileProvider.ArgumentNameResource); } if (null == patch) { throw new ArgumentNullException(FileProvider.ArgumentNamePatch); } if (null == patch.ResourceIdentifier) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.Identifier)) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.SchemaIdentifier)) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } if (null == patch.PatchRequest) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch); } PatchRequest2 patchRequest = patch.PatchRequest as PatchRequest2; if (null == patchRequest) { string unsupportedPatchTypeName = patch.GetType().FullName; throw new NotSupportedException(unsupportedPatchTypeName); } if ( !FileProvider .SchemaIdentifiersGroup .Value .Any( (string item) => string.Equals(item, patch.ResourceIdentifier.SchemaIdentifier, StringComparison.Ordinal)) ) { return; } IReadOnlyCollection<PatchOperation> memberOperations = patchRequest .Operations .Where( (PatchOperation item) => item.Path != null && string.Equals(item.Path.AttributePath, AttributeNames.Members, StringComparison.Ordinal)) .ToArray(); if (!memberOperations.Any()) { return; } foreach (PatchOperation memberOperation in memberOperations) { if (null == memberOperation.Value) { continue; } foreach (OperationValue value in memberOperation.Value) { if (string.IsNullOrWhiteSpace(value.Value)) { continue; } Dictionary<string, string> columnsQuery = new Dictionary<string,string>() { { AttributeNames.Schemas, patch.ResourceIdentifier.SchemaIdentifier }, { AttributeNames.Identifier, patch.ResourceIdentifier.Identifier }, { AttributeNames.Members, value.Value } }; IRow[] rows = await this.file.Query(columnsQuery); switch (memberOperation.Name) { case OperationName.Add: if (rows.Any()) { break; } Member member = new Member() { Value = value.Value }; MemberColumnsFactory memberColumnsFactory = new MemberColumnsFactory(resource, member); IReadOnlyDictionary<string, string> columnsMember = memberColumnsFactory.CreateColumns(); await this.file.InsertRow(columnsMember); break; case OperationName.Remove: foreach (IRow row in rows) { await this.file.RemoveRow(row.Key); } break; } } } }
public static async void ApplyPatches() { Assembly assembly = Assembly.Load(new AssemblyName("Patches")); IEnumerable <Type> types = assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IPatch))); int currentVersion = 0; bool failed = false; int index = 0; KeyValuePair <string, object> settingValue = ApplicationData.Current.LocalSettings.Values.FirstOrDefault(v => v.Key == VERSION_KEY); if (settingValue.Key != null) { int.TryParse(settingValue.Value.ToString(), out currentVersion); } else { ApplicationData.Current.LocalSettings.Values[VERSION_KEY] = currentVersion; } Type lastPatch = types.OrderByDescending(t => t.Name).FirstOrDefault(); if (lastPatch != null) { string[] parts = lastPatch.Name.Split('_'); int lastVersion = int.Parse(parts[parts.Length - 2]); if (lastVersion > currentVersion) { while (!failed && index < types.Count()) { Type type = types.ElementAt(index); parts = type.Name.Split('_'); int version = int.Parse(parts[parts.Length - 2]); if (version > currentVersion) { IPatch patch = (IPatch)Activator.CreateInstance(type); failed = await patch.Apply(); failed = !failed; if (!failed) { currentVersion = version; ApplicationData.Current.LocalSettings.Values[VERSION_KEY] = currentVersion; } } index++; } if (failed) { // TODO: Add logging and notification to user. } } } }
/********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="indexPath">The path of indexes from the root <c>content.json</c> to this patch; see <see cref="IPatch.IndexPath"/>.</param> /// <param name="path">The path to the patch from the root content file.</param> /// <param name="assetName">The normalized asset name to intercept.</param> /// <param name="conditions">The conditions which determine whether this patch should be applied.</param> /// <param name="fromFile">The normalized asset key from which to load entries (if applicable), including tokens.</param> /// <param name="updateRate">When the patch should be updated.</param> /// <param name="contentPack">The content pack which requested the patch.</param> /// <param name="parentPatch">The parent patch for which this patch was loaded, if any.</param> /// <param name="normalizeAssetName">Normalize an asset name.</param> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="patchLoader">Handles loading and unloading patches for content packs.</param> public IncludePatch(int[] indexPath, LogPathBuilder path, IManagedTokenString assetName, IEnumerable <Condition> conditions, IManagedTokenString fromFile, UpdateRate updateRate, RawContentPack contentPack, IPatch parentPatch, Func <string, string> normalizeAssetName, IMonitor monitor, PatchLoader patchLoader) : base( indexPath: indexPath, path: path, type: PatchType.Include, assetName: assetName, conditions: conditions, fromAsset: fromFile, updateRate: updateRate, parentPatch: parentPatch, contentPack: contentPack.ContentPack, normalizeAssetName: normalizeAssetName ) { this.RawContentPack = contentPack; this.Monitor = monitor; this.PatchLoader = patchLoader; }
public async Task <IHttpActionResult> ExecuteAsync(int id, IPatch <CommentResource> patch) { await Task.CompletedTask; return(NoContent()); }
/// <inheritdoc /> public override bool UpdateContext(IContext context) { // update context if (!this.UpdateContext(context, out string previousFilePath)) { return(false); } // unload previous patches if (!string.IsNullOrWhiteSpace(previousFilePath)) { this.PatchLoader.UnloadPatchesLoadedBy(this, reindex: false); } // load new patches this.AttemptedDataLoad = this.Conditions.All(p => p.IsMatch); this.IsApplied = false; if (this.AttemptedDataLoad) { string errorPrefix = $"Error loading patch '{this.Path}'"; try { // validate file existence if (!this.FromAssetExists()) { this.Monitor.Log($"{errorPrefix}: file '{this.FromAsset}' doesn't exist."); return(true); } // prevent circular reference { List <string> loopPaths = new List <string>(); for (IPatch parent = this.ParentPatch; parent != null; parent = parent.ParentPatch) { if (parent.Type == PatchType.Include) { loopPaths.Add(parent.FromAsset); if (this.IsSameFilePath(parent.FromAsset, this.FromAsset)) { loopPaths.Reverse(); loopPaths.Add(this.FromAsset); this.Monitor.Log($"{errorPrefix}: patch skipped because it would cause an infinite loop ({string.Join(" > ", loopPaths)}).", LogLevel.Warn); return(true); } } } } // load raw file var content = this.ContentPack.LoadAsset <ContentConfig>(this.FromAsset); if (!content.Changes.Any()) { this.Monitor.Log($"{errorPrefix}: file '{this.FromAsset}' doesn't have anything in the {nameof(content.Changes)} field. Is the file formatted correctly?", LogLevel.Warn); return(true); } // validate fields string[] invalidFields = this.GetInvalidFields(content).ToArray(); if (invalidFields.Any()) { this.Monitor.Log($"{errorPrefix}: file contains fields which aren't allowed for a secondary file ({string.Join(", ", invalidFields.OrderByHuman())}).", LogLevel.Warn); return(true); } // load patches this.PatchLoader.LoadPatches( contentPack: this.RawContentPack, rawPatches: content.Changes, rootIndexPath: this.IndexPath, path: this.GetIncludedLogPath(this.FromAsset), reindex: true, parentPatch: this ); this.IsApplied = true; } catch (Exception ex) { this.Monitor.Log($"{errorPrefix}. Technical details:\n{ex}", LogLevel.Error); return(true); } } return(true); }
public void TestApplyPatches() { IBasicLogger logger = Substitute.For <IBasicLogger>(); IPatchProgress progress = Substitute.For <IPatchProgress>(); PatchApplier patchApplier = new PatchApplier(progress, logger); IPass pass1 = Substitute.For <IPass>(); IPass pass2 = Substitute.For <IPass>(); IPass pass3 = Substitute.For <IPass>(); pass1.Name.Returns(":PASS1"); pass2.Name.Returns(":PASS2"); pass3.Name.Returns(":PASS3"); UrlDir.UrlConfig[] patchUrlConfigs = new UrlDir.UrlConfig[9]; IPatch[] patches = new IPatch[9]; for (int i = 0; i < patches.Length; i++) { patches[i] = Substitute.For <IPatch>(); } patches[0].CountsAsPatch.Returns(false); patches[1].CountsAsPatch.Returns(false); patches[2].CountsAsPatch.Returns(false); patches[3].CountsAsPatch.Returns(true); patches[4].CountsAsPatch.Returns(true); patches[5].CountsAsPatch.Returns(true); patches[6].CountsAsPatch.Returns(true); patches[7].CountsAsPatch.Returns(true); patches[8].CountsAsPatch.Returns(true); pass1.GetEnumerator().Returns(new ArrayEnumerator <IPatch>(patches[0], patches[1], patches[2])); pass2.GetEnumerator().Returns(new ArrayEnumerator <IPatch>(patches[3], patches[4], patches[5])); pass3.GetEnumerator().Returns(new ArrayEnumerator <IPatch>(patches[6], patches[7], patches[8])); IPass[] patchList = new IPass[] { pass1, pass2, pass3 }; LinkedList <IProtoUrlConfig> databaseConfigs = Assert.IsType <LinkedList <IProtoUrlConfig> >(patchApplier.ApplyPatches(new[] { pass1, pass2, pass3 })); progress.DidNotReceiveWithAnyArgs().Error(null, null); progress.DidNotReceiveWithAnyArgs().Exception(null, null); progress.DidNotReceiveWithAnyArgs().Exception(null, null, null); logger.DidNotReceive().Log(LogType.Warning, Arg.Any <string>()); logger.DidNotReceive().Log(LogType.Error, Arg.Any <string>()); logger.DidNotReceiveWithAnyArgs().Exception(null, null); Received.InOrder(delegate { progress.PassStarted(pass1); patches[0].Apply(databaseConfigs, progress, logger); patches[1].Apply(databaseConfigs, progress, logger); patches[2].Apply(databaseConfigs, progress, logger); progress.PassStarted(pass2); patches[3].Apply(databaseConfigs, progress, logger); progress.PatchApplied(); patches[4].Apply(databaseConfigs, progress, logger); progress.PatchApplied(); patches[5].Apply(databaseConfigs, progress, logger); progress.PatchApplied(); progress.PassStarted(pass3); patches[6].Apply(databaseConfigs, progress, logger); progress.PatchApplied(); patches[7].Apply(databaseConfigs, progress, logger); progress.PatchApplied(); patches[8].Apply(databaseConfigs, progress, logger); progress.PatchApplied(); }); }
/// <summary> /// Change all references to the current patch, towards the specified patch. /// Since set list slots are not referenced; do nothing. /// </summary> /// <param name="newPatch"></param> public override void ChangeReferences(IPatch newPatch) { // Do nothing }
public void SetInstalledMark(IPatch patch){ TargetPathResolver.Write("usr/patch/.inst/" + patch.Code + ".installed", ""); }
public bool Equals(IPatch x, IPatch y) { return(x != null && x.Equals(y)); }
private void doInstall(IPatch patch){ foreach (var identity in patch.GetDependences()){ doInstall((IPatch) Load(identity)); } if (patch.IsInstalled){ return; } logger.get("comdiv.patching.manager").Info("INSTALLING PATCH: {0}...", patch.Code); patch.Install(); }
public int GetHashCode(IPatch obj) { return(obj.GetHashCode()); }
public override Task Update(IPatch patch, string correlationIdentifier) { return Task.FromResult(0); }
public void AddForPatch(IPatch patch) => forPass.Add(patch ?? throw new ArgumentNullException(nameof(patch)));