public void AddNotNull() { var list = new List <int?>(); int?v1 = null; list.AddNotNull(v1); Assert.AreEqual(0, list.Count); v1 = 1; list.AddNotNull(v1); Assert.AreEqual(1, list.Count); }
public List <Tile> GetAdjacentTiles(Tile tile) { var adjacentTiles = new List <Tile>(); adjacentTiles.AddNotNull(GetTile(tile.X, tile.Y - 1)); adjacentTiles.AddNotNull(GetTile(tile.X, tile.Y + 1)); adjacentTiles.AddNotNull(GetTile(tile.X - 1, tile.Y)); adjacentTiles.AddNotNull(GetTile(tile.X + 1, tile.Y)); return(adjacentTiles); }
static ApiParameter CreateParameter( ISymbol symbol, MetadataItem item, bool isReturn = false ) { var type = symbol switch { IParameterSymbol s => s.Type, IEventSymbol s => s.Type, IPropertySymbol s => s.Type, IFieldSymbol s => s.Type, _ => throw new ArgumentException( $"Symbol {symbol.Kind} is not supported", nameof(symbol) ) }; return(ApiParameter.Create(symbol, item, type.ToDisplayString(), isReturn)); } MetadataItem?GetMetadataItem(ISymbol symbol) { var item = DefaultVisit(symbol); if (item == null) { return(null); } item.Type = symbol.GetMemberTypeFromSymbol(); return(item.Type == MemberType.Default ? null : item); } List <MetadataItem> VisitDescendants <T>( IEnumerable <T> children, Func <T, IEnumerable <T> > getChildren, Func <T, bool> filter ) where T : ISymbol { var result = new List <MetadataItem>(); var stack = new Stack <T>(children.Reverse()); while (stack.Count > 0) { var child = stack.Pop(); if (filter(child)) { result.AddNotNull(child.Accept(this)); } foreach (var m in getChildren(child).Reverse()) { stack.Push(m); } } return(result); }
protected override SyncAttempt <IDataType> DeserializeCore(XElement node, SyncSerializerOptions options) { var info = node.Element("Info"); var name = info.Element("Name").ValueOrDefault(string.Empty); var key = node.GetKey(); var attempt = FindOrCreate(node); if (!attempt.Success) { throw attempt.Exception; } var details = new List <uSyncChange>(); var item = attempt.Result; // basic if (item.Name != name) { details.AddUpdate("Name", item.Name, name, "Name"); item.Name = name; } if (item.Key != key) { details.AddUpdate("Key", item.Key, key, "Key"); item.Key = key; } var editorAlias = info.Element("EditorAlias").ValueOrDefault(string.Empty); if (editorAlias != item.EditorAlias) { // change the editor type..... var newEditor = Current.DataEditors.FirstOrDefault(x => x.Alias.InvariantEquals(editorAlias)); if (newEditor != null) { details.AddUpdate("EditorAlias", item.EditorAlias, editorAlias, "EditorAlias"); item.Editor = newEditor; } } // removing sort order - as its not used on datatypes, // and can change based on minor things (so gives false out of sync results) // item.SortOrder = info.Element("SortOrder").ValueOrDefault(0); var dbType = info.Element("DatabaseType").ValueOrDefault(ValueStorageType.Nvarchar); if (item.DatabaseType != dbType) { details.AddUpdate("DatabaseType", item.DatabaseType, dbType, "DatabaseType"); item.DatabaseType = dbType; } // config details.AddRange(DeserializeConfiguration(item, node)); details.AddNotNull(SetFolderFromElement(item, info.Element("Folder"))); return(SyncAttempt <IDataType> .Succeed(item.Name, item, ChangeType.Import, details)); }
public void AddNotNullForCollectionStruct() { var list = new List <int> { 1, 2 }; list.AddNotNull(3); Assert.Equal(3, list.Count); list.AddNotNull(null); Assert.Equal(3, list.Count); var list2 = (List <int>)null; list2.AddNotNull(3); Assert.Null(list2); }
public void AddNotNull() { var list = new List <string> { "hey", "bye" }; list.AddNotNull("hi"); Assert.Equal(3, list.Count); list.AddNotNull(null); Assert.Equal(3, list.Count); var list2 = (List <string>)null; list2.AddNotNull("hi"); Assert.Null(list2); }
/// <summary> /// works out changes, when the child elements are all properties (and have their own node names) /// this only works when each property is unique (no duplicates in a list) /// </summary> private IEnumerable <uSyncChange> CalculatePropertyChanges(TrackedItem change, XElement current, XElement target, string name, string path) { var updates = new List <uSyncChange>(); var currentNode = current.XPathSelectElement(path); var targetNode = target.XPathSelectElement(path); foreach (var childNode in currentNode.Elements()) { var currentNodePath = GetChangePath(change.Path, $"/{childNode.Name.LocalName}"); var currentNodeName = GetChangeName(change.Name, childNode.Name.LocalName); // we basically compare to target now. var targetChildNode = targetNode.Element(childNode.Name.LocalName); if (targetChildNode == null) { // no target, this element will get deleted updates.Add(uSyncChange.Delete(path, $"{name} [{childNode.Name.LocalName}]", GetElementValues(childNode))); continue; } // check all the children of the current and target for changes if (change.Children != null && change.Children.Any()) { foreach (var child in change.Children) { updates.AddRange(CalculateChanges(child, currentNode, targetNode, currentNodeName, currentNodePath)); } } else { var childValue = childNode.ValueOrDefault(string.Empty); var targetChildValue = targetChildNode.ValueOrDefault(string.Empty); if (!childValue.Equals(targetChildValue)) { // if there are no children, they we are comparing the actual text of the nodes updates.AddNotNull(Compare(currentNodePath, currentNodeName, childValue, targetChildValue, change.MaskValue)); } } } // missing from current (so new) foreach (var targetChild in targetNode.Elements()) { var currentChildNode = currentNode.Element(targetChild.Name.LocalName); if (currentChildNode == null) { // not in current, its a new property. updates.Add(uSyncChange.Create(path, $"{name} [{targetChild.Name.LocalName}]", GetElementValues(targetChild))); } } return(updates); }
/// <summary> /// actually kicks off here, if you have two xml files that are diffrent. /// </summary> private IEnumerable <uSyncChange> CalculateDiffrences(XElement target, XElement source) { var changes = new List <uSyncChange>(); foreach (var trackingItem in this.TrackingItems) { if (trackingItem.SingleItem) { changes.AddNotNull(TrackSingleItem(trackingItem, target, source, TrackingDirection.TargetToSource)); changes.AddNotNull(TrackSingleItem(trackingItem, source, target, TrackingDirection.SourceToTarget)); } else { changes.AddRange(TrackMultipleKeyedItems(trackingItem, target, source, TrackingDirection.TargetToSource)); changes.AddRange(TrackMultipleKeyedItems(trackingItem, source, target, TrackingDirection.SourceToTarget)); } } return(changes); }
private IEnumerable <uSyncChange> CompareNode(XElement target, XElement source, string path, string name, bool maskValue) { var changes = new List <uSyncChange>(); // compare attributes foreach (var sourceAttribute in source.Attributes()) { var sourceAttributeName = sourceAttribute.Name.LocalName; changes.AddNotNull( Compare( target.Attribute(sourceAttributeName).ValueOrDefault(string.Empty), sourceAttribute.Value, path + $"{seperator}{sourceAttributeName}", $"{name} > {sourceAttributeName}", maskValue)); } if (source.HasElements) { // compare elements. foreach (var sourceElement in source.Elements()) { var sourceElementName = sourceElement.Name.LocalName; changes.AddNotNull( Compare( target.Element(sourceElementName).ValueOrDefault(string.Empty), sourceElement.Value, path + $"{seperator}{sourceElementName}", $"{name} > {sourceElementName}", maskValue)); } } else { changes.AddNotNull(Compare(target.ValueOrDefault(string.Empty), source.ValueOrDefault(string.Empty), path, name, maskValue)); } return(changes); }
protected IEnumerable <uSyncDependency> GetItemDependency(JObject itemValue, DependencyFlags flags) { if (itemValue == null) { return(Enumerable.Empty <uSyncDependency>()); } if (itemValue.ContainsKey("contentData")) { // nested content mode. var contentData = itemValue.Value <JObject>("contentData"); var docTypeAlias = contentData.Value <string>(this.docTypeAliasValue); if (contentData == null || docTypeAlias == null) { return(Enumerable.Empty <uSyncDependency>()); } var docType = GetDocType(docTypeAlias); if (docType == null) { return(Enumerable.Empty <uSyncDependency>()); } List <uSyncDependency> dependencies = new List <uSyncDependency>(); var docTypeDependency = CreateDocTypeDependency(docType, flags); dependencies.AddNotNull(docTypeDependency); dependencies.AddRange(GetPropertyDependencies(contentData, docType, flags)); return(dependencies); } else { // linked content mode var key = itemValue.Value <Guid>("key"); if (key != null) { // we need to include the ancestors of any included // bento items, to ensure we get the library structure // of the bento items as part of the sync. var bentoFlags = flags | DependencyFlags.IncludeAncestors; var udi = GuidUdi.Create(Constants.UdiEntityType.Document, key); return(CreateDependency(udi as GuidUdi, bentoFlags).AsEnumerableOfOne()); } } return(Enumerable.Empty <uSyncDependency>()); }
protected override SyncAttempt <IContent> DeserializeCore(XElement node, SyncSerializerOptions options) { var attempt = FindOrCreate(node); if (!attempt.Success) { throw attempt.Exception; } var item = attempt.Result; var details = new List <uSyncChange>(); details.AddRange(DeserializeBase(item, node, options)); details.AddNotNull(DeserializeTemplate(item, node)); details.AddRange(DeserializeSchedules(item, node, options)); return(SyncAttempt <IContent> .Succeed(item.Name, item, ChangeType.Import, details)); }
private IEnumerable <uSyncChange> TrackMultipleKeyedItems(TrackingItem trackingItem, XElement target, XElement source, TrackingDirection direction) { var changes = new List <uSyncChange>(); var sourceItems = source.XPathSelectElements(trackingItem.Path); foreach (var sourceNode in sourceItems) { // make the selection path for this item. var itemPath = trackingItem.Path.Replace("*", sourceNode.Parent.Name.LocalName) + MakeSelectionPath(sourceNode, trackingItem.Keys); var itemName = trackingItem.Name.Replace("*", sourceNode.Parent.Name.LocalName) + MakeSelectionName(sourceNode, String.IsNullOrWhiteSpace(trackingItem.ValueKey) ? trackingItem.Keys : trackingItem.ValueKey); var targetNode = target.XPathSelectElement(itemPath); if (targetNode == null) { var value = sourceNode.ValueOrDefault(string.Empty); if (!string.IsNullOrEmpty(trackingItem.ValueKey)) { value = GetKeyValue(sourceNode, trackingItem.ValueKey); } // missing, we add either a delete or create - depending on tracking direction changes.AddNotNull(AddMissingChange(trackingItem.Path, itemName, value, direction)); } // only track updates when tracking target to source. else if (direction == TrackingDirection.TargetToSource) { // check the node to see if its an update. changes.AddRange(CompareNode(targetNode, sourceNode, trackingItem.Path, itemName, trackingItem.MaskValue)); } } return(changes); }
public override IEnumerable <uSyncDependency> GetDependencies(object value, string editorAlias, DependencyFlags flags) { var jsonValue = GetJsonValue(value); if (jsonValue == null) { return(Enumerable.Empty <uSyncDependency>()); } var dependencies = new List <uSyncDependency>(); // format of block data. // { "layout" : {}, "contentData": {}, "settingsData": {} } foreach (var block in contentBlocks) { // contentData is the thing we need to inspect. if (jsonValue.ContainsKey(block)) { var contentData = jsonValue.Value <JArray>(block); if (contentData != null) { foreach (var contentItem in contentData.Cast <JObject>()) { var contentType = GetDocTypeByKey(contentItem, this.docTypeKeyAlias); if (contentType != null) { dependencies.AddNotNull(CreateDocTypeDependency(contentType, flags)); dependencies.AddRange(this.GetPropertyDependencies(contentItem, contentType, flags)); } } } } } return(dependencies); }
private void HandleInput(KeyboardState key) { if (key[Key.Space]) { projectiles.AddNotNull(playerTank.Shoot(playerTank)); } if (key[Key.Up]) { playerTank.MoveOrTurn(Direction.Up, GetImpassable(), boundaries); } else if (key[Key.Down]) { playerTank.MoveOrTurn(Direction.Down, GetImpassable(), boundaries); } else if (key[Key.Left]) { playerTank.MoveOrTurn(Direction.Left, GetImpassable(), boundaries); } else if (key[Key.Right]) { playerTank.MoveOrTurn(Direction.Right, GetImpassable(), boundaries); } }
private object CreateNewObject(GOLD.Reduction r) { object result = null; int pointerCount; switch ((ProductionIndex)r.Parent.TableIndex()) { case ProductionIndex.Decls: // <Decls> ::= <Decl> <Decls> var declarationHead = r.GetData(0) as DeclarationStatement; var declarationTail = r.GetData(1) as List<DeclarationStatement>; declarationTail.InsertNotNull(0, declarationHead); return declarationTail; case ProductionIndex.Decls2: // <Decls> ::= return new List<DeclarationStatement>(); case ProductionIndex.Decl: // <Decl> ::= <Func Decl> return r.GetData(0); case ProductionIndex.Decl2: // <Decl> ::= <Func Proto> return r.GetData(0); case ProductionIndex.Decl3: // <Decl> ::= <Struct Decl> return r.GetData(0); case ProductionIndex.Decl4: // <Decl> ::= <Union Decl> return r.GetData(0); case ProductionIndex.Decl5: // <Decl> ::= <Enum Decl> return r.GetData(0); case ProductionIndex.Decl6: // <Decl> ::= <Var Decl> return r.GetData(0); case ProductionIndex.Decl7: // <Decl> ::= <Typedef Decl> return r.GetData(0); case ProductionIndex.Funcproto_Lparen_Rparen_Semi: // <Func Proto> ::= <Func ID> '(' <Types> ')' ';' break; case ProductionIndex.Funcproto_Lparen_Rparen_Semi2: // <Func Proto> ::= <Func ID> '(' <Params> ')' ';' break; case ProductionIndex.Funcproto_Lparen_Rparen_Semi3: // <Func Proto> ::= <Func ID> '(' ')' ';' break; case ProductionIndex.Funcdecl_Lparen_Rparen: // <Func Decl> ::= <Func ID> '(' <Params> ')' <Block> var function = r.GetData(0) as FunctionDeclaration; function.Parameters = r.GetData(2) as List<Parameter>; function.Block = r.GetData(4) as BlockStatement; return function; case ProductionIndex.Funcdecl_Lparen_Rparen2: // <Func Decl> ::= <Func ID> '(' <Id List> ')' <Struct Def> <Block> throw new NotImplementedException(); case ProductionIndex.Funcdecl_Lparen_Rparen3: // <Func Decl> ::= <Func ID> '(' ')' <Block> function = r.GetData(0) as FunctionDeclaration; function.Block = r.GetData(3) as BlockStatement; return function; case ProductionIndex.Params_Comma: // <Params> ::= <Param> ',' <Params> var paramHead = r.GetData(0) as Parameter; var paramTail = r.GetData(2) as List<Parameter>; paramTail.InsertNotNull(0,paramHead); return paramTail; case ProductionIndex.Params: // <Params> ::= <Param> return new List<Parameter>() { r.GetData(0) as Parameter }; case ProductionIndex.Param_Const_Id: // <Param> ::= const <Type> Id break; case ProductionIndex.Param_Id: // <Param> ::= <Type> Id return new Parameter(r.GetData(0) as IRType, r.GetData(1).ToString()); case ProductionIndex.Types_Comma: // <Types> ::= <Type> ',' <Types> var typeHead = r.GetData(0) as IRType; var typeTail = r.GetData(2) as List<IRType>; typeTail.InsertNotNull(0, typeHead); return typeTail; case ProductionIndex.Types: // <Types> ::= <Type> return new List<IRType> { r.GetData(0) as IRType}; case ProductionIndex.Idlist_Id_Comma: // <Id List> ::= Id ',' <Id List> var idHead = r.GetData(0).ToString(); var idTail = r.GetData(2) as List<string>; idTail.InsertNotNull(0, idHead); return idTail; case ProductionIndex.Idlist_Id: // <Id List> ::= Id var idList = r.GetData(0).ToString(); return new List<string>() { idList }; case ProductionIndex.Funcid_Id: // <Func ID> ::= <Type> Id return new FunctionDeclaration(r.GetData(0) as IRType, r.GetData(1).ToString()); case ProductionIndex.Funcid_Id2: // <Func ID> ::= Id //return new Function(r.GetData(0).ToString()); throw new NotImplementedException("<Func ID> ::= Id"); case ProductionIndex.Typedefdecl_Typedef_Id_Semi: // <Typedef Decl> ::= typedef <Type> Id ';' break; case ProductionIndex.Structdecl_Struct_Id_Lbrace_Rbrace_Semi: // <Struct Decl> ::= struct Id '{' <Struct Def> '}' ';' return new StructDeclaration(r.GetData(0).ToString(), r.GetData(3) as List<IdDeclarationStatement>); case ProductionIndex.Uniondecl_Union_Id_Lbrace_Rbrace_Semi: // <Union Decl> ::= union Id '{' <Struct Def> '}' ';' return new UnionDeclaration(r.GetData(1).ToString(), r.GetData(3) as List<IdDeclarationStatement>); case ProductionIndex.Structdef: // <Struct Def> ::= <Var Decl> <Struct Def> var declarationstm = r.GetData(0) as List<IdDeclarationStatement>; var structdeftail = r.GetData(1) as List<IdDeclarationStatement>; declarationstm.AddRange(structdeftail); return declarationstm; case ProductionIndex.Structdef2: // <Struct Def> ::= <Var Decl> declarationstm = r.GetData(0) as List<IdDeclarationStatement>; return declarationstm; case ProductionIndex.Vardecl_Semi: // <Var Decl> ::= <Mod> <Type> <Var> <Var List> ';' var baseType = r.GetData(1) as IRType; var partialDeclaration = r.GetData(2) as PartialIdDeclarationStatement; var varList = r.GetData(3) as List<VarItem>; var idDeclaration = partialDeclaration.DeclarationStatement; var partialType = baseType; if (partialDeclaration.ArrayType != null ) { partialDeclaration.ArrayType.Type = partialType; partialType = partialDeclaration.ArrayType; } idDeclaration.Type = partialType; idDeclaration.Modifier = r.GetData(0) as Modifier; var idDeclarationList = new List<IdDeclarationStatement>() { idDeclaration }; foreach (var varItem in varList) { IRType baseVarItemType = baseType; pointerCount = Convert.ToInt32(varItem.Pointers); for (int i = 0; i < pointerCount; i++) { baseVarItemType = new PointerType(baseVarItemType); } if (varItem.PartialIdDeclaration.ArrayType != null) { varItem.PartialIdDeclaration.ArrayType.Type = baseVarItemType; baseVarItemType = varItem.PartialIdDeclaration.ArrayType; } varItem.PartialIdDeclaration.DeclarationStatement.Type = baseVarItemType; idDeclarationList.Add(varItem.PartialIdDeclaration.DeclarationStatement); } return idDeclarationList; case ProductionIndex.Vardecl_Semi2: // <Var Decl> ::= <Type> <Var> <Var List> ';' baseType = r.GetData(0) as IRType; partialDeclaration = r.GetData(1) as PartialIdDeclarationStatement; varList = r.GetData(2) as List<VarItem>; idDeclaration = partialDeclaration.DeclarationStatement; partialType = baseType; if (partialDeclaration.ArrayType != null ) { partialDeclaration.ArrayType.Type = partialType; partialType = partialDeclaration.ArrayType; } idDeclaration.Type = partialType; idDeclarationList = new List<IdDeclarationStatement>() { idDeclaration }; foreach (var varItem in varList) { IRType baseVarItemType = baseType; pointerCount = Convert.ToInt32(varItem.Pointers); for (int i = 0; i < pointerCount; i++) { baseVarItemType = new PointerType(baseVarItemType); } if (varItem.PartialIdDeclaration.ArrayType != null) { varItem.PartialIdDeclaration.ArrayType.Type = baseVarItemType; baseVarItemType = varItem.PartialIdDeclaration.ArrayType; } varItem.PartialIdDeclaration.DeclarationStatement.Type = baseVarItemType; idDeclarationList.Add(varItem.PartialIdDeclaration.DeclarationStatement); } return idDeclarationList; case ProductionIndex.Vardecl_Semi3: // <Var Decl> ::= <Mod> <Var> <Var List> ';' throw new NotImplementedException("<Var Decl> ::= <Mod> <Var> <Var List> "); case ProductionIndex.Var_Id: // <Var> ::= Id <Array> var arrayType = r.GetData(1) as ArrayType; var id = r.GetData(0).ToString(); idDeclaration = new IdDeclarationStatement(id); partialDeclaration = new PartialIdDeclarationStatement(idDeclaration, arrayType); return partialDeclaration; case ProductionIndex.Var_Id_Eq: // <Var> ::= Id <Array> '=' <Op If> arrayType = r.GetData(1) as ArrayType; var assigment = r.GetData(3) as Expression; id = r.GetData(0).ToString(); idDeclaration = new IdDeclarationStatement(id,assigment); partialDeclaration = new PartialIdDeclarationStatement(idDeclaration, arrayType); return partialDeclaration; case ProductionIndex.Array_Lbracket_Rbracket: // <Array> ::= '[' <Expr> ']' var sizeExpression = r.GetData(1) as DecValue; return new ArrayType(Convert.ToInt64(sizeExpression.Value)); case ProductionIndex.Array_Lbracket_Rbracket2: // <Array> ::= '[' ']' return new ArrayType(); case ProductionIndex.Array: // <Array> ::= return null; case ProductionIndex.Varlist_Comma: // <Var List> ::= ',' <Var Item> <Var List> var varItemHead = r.GetData(1) as VarItem; var varItemTail = r.GetData(2) as List<VarItem>; varItemTail.InsertNotNull(0, varItemHead); return varItemTail; case ProductionIndex.Varlist: // <Var List> ::= return new List<VarItem>(); case ProductionIndex.Varitem: // <Var Item> ::= <Pointers> <Var> var pointers = Convert.ToInt32(r.GetData(0)); var var = r.GetData(1) as PartialIdDeclarationStatement; return new VarItem( pointers, var); case ProductionIndex.Mod_Extern: // <Mod> ::= extern no extern no break;//ver que pedo con la excepcion case ProductionIndex.Mod_Static: // <Mod> ::= static return new StaticModifier(); case ProductionIndex.Mod_Register: // <Mod> ::= register return new RegisterModifier(); case ProductionIndex.Mod_Auto: // <Mod> ::= auto return new AutoModifier(); case ProductionIndex.Mod_Volatile: // <Mod> ::= volatile no volatile no break; //ver que pedo con la excepcion case ProductionIndex.Mod_Const: // <Mod> ::= const return new ConstModifier(); case ProductionIndex.Enumdecl_Enum_Id_Lbrace_Rbrace_Semi: // <Enum Decl> ::= enum Id '{' <Enum Def> '}' ';' return new EnumDeclaration(r.GetData(1).ToString(), r.GetData(3) as List<EnumValue>); case ProductionIndex.Enumdef_Comma: // <Enum Def> ::= <Enum Val> ',' <Enum Def> var enumHead = r.GetData(0) as EnumValue; var enumTail = r.GetData(2) as List<EnumValue>; enumTail.InsertNotNull(0, enumHead); return enumTail; case ProductionIndex.Enumdef: // <Enum Def> ::= <Enum Val> return new List<EnumValue> {r.GetData(0) as EnumValue}; case ProductionIndex.Enumval_Id: // <Enum Val> ::= Id return r.GetData(0); case ProductionIndex.Enumval_Id_Eq_Octliteral: // <Enum Val> ::= Id '=' OctLiteral return new EnumValue(r.GetData(0).ToString(), Convert.ToInt32(r.GetData(2).ToString(), 8)); case ProductionIndex.Enumval_Id_Eq_Hexliteral: // <Enum Val> ::= Id '=' HexLiteral return new EnumValue(r.GetData(0).ToString(), Convert.ToInt32(r.GetData(2).ToString(), 16)); case ProductionIndex.Enumval_Id_Eq_Decliteral: // <Enum Val> ::= Id '=' DecLiteral return new EnumValue(r.GetData(0).ToString(), Convert.ToInt32(r.GetData(2).ToString(), 10)); case ProductionIndex.Type: // <Type> ::= <Base> <Pointers> baseType = r.GetData(0) as IRType; pointerCount = Convert.ToInt32(r.GetData(1)); for (int i = 0; i < pointerCount; i++) { baseType = new PointerType(baseType); } return baseType; case ProductionIndex.Base: // <Base> ::= <Sign> <Scalar> if (r.GetData(0).ToString() == "unsigned") { if ( r.GetData(1) is IntType ) { return new UnsignedIntType(); } else if (r.GetData(1) is ShortType) { return new UnsignedShortType(); } else if (r.GetData(1) is LongType) { return new UnsignedLongType(); } else if (r.GetData(1) is ShortIntType) { return new UnsignedShortIntType(); } else if (r.GetData(1) is FloatType) { return new UnsignedFloatType(); } else if (r.GetData(1) is LongIntType) { return new UnsignedLongIntType(); } else if (r.GetData(1) is DoubleType) { return new UnsignedDoubleType(); } } return r.GetData(1); case ProductionIndex.Base_Struct_Id: // <Base> ::= struct Id return new StructType(r.GetData(1).ToString());//Crear una clase para definir el tipo inferido del struct case ProductionIndex.Base_Struct_Lbrace_Rbrace: // <Base> ::= struct '{' <Struct Def> '}' return new StructType(r.GetData(2) as List<DeclarationStatement>); case ProductionIndex.Base_Union_Id: // <Base> ::= union Id return new UnionType(r.GetData(1).ToString());//Crear una clase para definir el tipo inferido del union case ProductionIndex.Base_Union_Lbrace_Rbrace: // <Base> ::= union '{' <Struct Def> '}' return new UnionType(r.GetData(2) as List<DeclarationStatement>); case ProductionIndex.Base_Enum_Id: // <Base> ::= enum Id return new EnumType(r.GetData(1).ToString()); case ProductionIndex.Sign_Signed: // <Sign> ::= signed return r.GetData(0); case ProductionIndex.Sign_Unsigned: // <Sign> ::= unsigned return r.GetData(0); case ProductionIndex.Sign: // <Sign> ::= return 0; case ProductionIndex.Scalar_Char: // <Scalar> ::= char return new CharType(); case ProductionIndex.Scalar_Int: // <Scalar> ::= int return new IntType(); case ProductionIndex.Scalar_Short: return new ShortType(); case ProductionIndex.Scalar_Long: // <Scalar> ::= long return new LongType(); case ProductionIndex.Scalar_Short_Int: //<Scalar> ::= short int return new ShortIntType(); case ProductionIndex.Scalar_Long_Int: return new LongIntType(); case ProductionIndex.Scalar_Float: return new FloatType(); case ProductionIndex.Scalar_Double: return new DoubleType(); case ProductionIndex.Scalar_Void: return new VoidType(); case ProductionIndex.Pointers_Times: // <Pointers> ::= '*' <Pointers> return Convert.ToInt32(r.GetData(1)) + 1; case ProductionIndex.Pointers: // <Pointers> ::= return 0; case ProductionIndex.Stm: // <Stm> ::= <Var Decl> return r.GetData(0); case ProductionIndex.Stm_Id_Colon: // <Stm> ::= Id ':' return r.GetData(0).ToString(); //labelstatement class missing case ProductionIndex.Stm_If_Lparen_Rparen: // <Stm> ::= if '(' <Expr> ')' <Stm> var ifDeclaration = new IfStatement(r.GetData(2) as Expression, r.GetData(4) as Statement); return ifDeclaration; case ProductionIndex.Stm_If_Lparen_Rparen_Else: // <Stm> ::= if '(' <Expr> ')' <Then Stm> else <Stm> ifDeclaration = new IfStatement(r.GetData(2) as Expression, r.GetData(4) as Statement, r.GetData(6) as Statement); return ifDeclaration; case ProductionIndex.Stm_While_Lparen_Rparen: // <Stm> ::= while '(' <Expr> ')' <Stm> var whileDeclaration = new WhileStatement(r.GetData(2) as Expression, r.GetData(4) as Statement); return whileDeclaration; case ProductionIndex.Stm_For_Lparen_Semi_Semi_Rparen: // <Stm> ::= for '(' <Arg> ';' <Arg> ';' <Arg> ')' <Stm> var forDeclaration = new ForStatement(r.GetData(2) as Expression, r.GetData(4) as Expression, r.GetData(6) as Expression, r.GetData(8) as Statement); return forDeclaration; case ProductionIndex.Stm2: // <Stm> ::= <Normal Stm> return r.GetData(0); case ProductionIndex.Thenstm_If_Lparen_Rparen_Else: // <Then Stm> ::= if '(' <Expr> ')' <Then Stm> else <Then Stm> ifDeclaration = new IfStatement(r.GetData(2) as Expression, r.GetData(4) as Statement, r.GetData(6) as Statement); return ifDeclaration; case ProductionIndex.Thenstm_While_Lparen_Rparen: // <Then Stm> ::= while '(' <Expr> ')' <Then Stm> whileDeclaration = new WhileStatement(r.GetData(2) as Expression, r.GetData(4) as Statement); return whileDeclaration; case ProductionIndex.Thenstm_For_Lparen_Semi_Semi_Rparen: // <Then Stm> ::= for '(' <Arg> ';' <Arg> ';' <Arg> ')' <Then Stm> forDeclaration = new ForStatement(r.GetData(2) as Expression, r.GetData(4) as Expression, r.GetData(6) as Expression, r.GetData(8) as Statement); return forDeclaration; case ProductionIndex.Thenstm: // <Then Stm> ::= <Normal Stm> return r.GetData(0); case ProductionIndex.Normalstm_Do_While_Lparen_Rparen: // <Normal Stm> ::= do <Stm> while '(' <Expr> ')' var doDeclaration = new DoStatement(r.GetData(1) as Statement, r.GetData(4) as Expression); return doDeclaration; case ProductionIndex.Normalstm_Switch_Lparen_Rparen_Lbrace_Rbrace: // <Normal Stm> ::= switch '(' <Expr> ')' '{' <Case Stms> '}' var switchDeclaration = new SwitchStatement(r.GetData(2) as Expression, r.GetData(5) as List<DefaultCaseStatement>); return switchDeclaration; case ProductionIndex.Normalstm: // <Normal Stm> ::= <Block> return r.GetData(0); case ProductionIndex.Normalstm_Semi: // <Normal Stm> ::= <Expr> ';' var expressionStatement = new ExpressionStatement(r.GetData(0) as Expression); return expressionStatement; case ProductionIndex.Normalstm_Goto_Id_Semi: // <Normal Stm> ::= goto Id ';' return new GoToIdStatement(); //guardar el id case ProductionIndex.Normalstm_Break_Semi: // <Normal Stm> ::= break ';' return new BreakStatement(); case ProductionIndex.Normalstm_Continue_Semi: // <Normal Stm> ::= continue ';' return new ContinueStatement(); case ProductionIndex.Normalstm_Return_Semi: // <Normal Stm> ::= return <Expr> ';' return new ReturnStatement(r.get_Data(1) as Expression); case ProductionIndex.Normalstm_Semi2: // <Normal Stm> ::= ';' return new NoOpExpression(); case ProductionIndex.Arg: // <Arg> ::= <Expr> return r.GetData(0); case ProductionIndex.Arg2: // <Arg> ::= return new NoOpExpression(); case ProductionIndex.Casestms_Case_Colon: // <Case Stms> ::= case <Value> ':' <Stm List> <Case Stms> var caseStatementHead = new CaseStatement(r.GetData(1) as ValueExpression, r.GetData(3) as List<Statement>); var caseStatementTail = r.GetData(4) as List<DefaultCaseStatement>; caseStatementTail.InsertNotNull(0, caseStatementHead); return caseStatementTail; case ProductionIndex.Casestms_Default_Colon: // <Case Stms> ::= default ':' <Stm List> return new List<DefaultCaseStatement>() { new DefaultCaseStatement(r.GetData(2) as List<Statement>) }; case ProductionIndex.Casestms: // <Case Stms> ::= return new List<DefaultCaseStatement>(); case ProductionIndex.Block_Lbrace_Rbrace: // <Block> ::= '{' <Stm List> '}' return new BlockStatement(r.GetData(1) as List<Statement>); case ProductionIndex.Stmlist: // <Stm List> ::= <Stm> <Stm List> var statemetListTail = r.GetData(1) as List<Statement>; var declList = r.GetData(0) as List<IdDeclarationStatement>; if (declList != null) { var statementList = new List<Statement>(); foreach (var dec in declList) { statementList.AddNotNull(dec); } foreach (var TailItem in statemetListTail) { statementList.AddNotNull(TailItem); } return statementList; } statemetListTail.InsertNotNull(0, r.GetData(0) as Statement); return statemetListTail; case ProductionIndex.Stmlist2: // <Stm List> ::= return new List<Statement>(); case ProductionIndex.Expr_Comma: // <Expr> ::= <Expr> ',' <Op Assign> var expr = r.GetData(0) as ExpressionList; if (expr != null) { return new ExpressionList(expr, r.GetData(2) as Expression); } else return new ExpressionList(r.GetData(0) as Expression, r.GetData(2) as Expression); case ProductionIndex.Expr: // <Expr> ::= <Op Assign> return r.GetData(0); case ProductionIndex.Opassign_Eq: // <Op Assign> ::= <Op If> '=' <Op Assign> return new AssignExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign_Pluseq: // <Op Assign> ::= <Op If> '+=' <Op Assign> return new AdditionAssignmentExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign_Minuseq: // <Op Assign> ::= <Op If> '-=' <Op Assign> return new SubtractionAsigExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign_Timeseq: // <Op Assign> ::= <Op If> '*=' <Op Assign> return new MultiplicationAsigExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign_Diveq: // <Op Assign> ::= <Op If> '/=' <Op Assign> return new DivisionAsigExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign_Careteq: // <Op Assign> ::= <Op If> '^=' <Op Assign> return new BitwiseXorAssignmentExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign_Ampeq: // <Op Assign> ::= <Op If> '&=' <Op Assign> return new BitwiseAndAssignExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign_Pipeeq: // <Op Assign> ::= <Op If> '|=' <Op Assign> return new BitwiseOrAssigExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign_Gtgteq: // <Op Assign> ::= <Op If> '>>=' <Op Assign> return new BitwiseRightShiftAssigExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign_Ltlteq: // <Op Assign> ::= <Op If> '<<=' <Op Assign> return new BitwiseLeftShiftAssigExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opassign: // <Op Assign> ::= <Op If> return r.get_Data(0); case ProductionIndex.Opif_Question_Colon: // <Op If> ::= <Op Or> '?' <Op If> ':' <Op If> return new TernaryConditional(r.GetData(0) as Expression, r.GetData(2) as Expression, r.GetData(4) as Expression); case ProductionIndex.Opif: // <Op If> ::= <Op Or> return r.get_Data(0); case ProductionIndex.Opor_Pipepipe: // <Op Or> ::= <Op Or> '||' <Op And> return new LogicalOrExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opor: // <Op Or> ::= <Op And> return r.get_Data(0); case ProductionIndex.Opand_Ampamp: // <Op And> ::= <Op And> '&&' <Op BinOR> return new LogicAndExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opand: // <Op And> ::= <Op BinOR> return r.get_Data(0); case ProductionIndex.Opbinor_Pipe: // <Op BinOR> ::= <Op BinOR> '|' <Op BinXOR> return new BitwiseOrExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opbinor: // <Op BinOR> ::= <Op BinXOR> return r.get_Data(0); case ProductionIndex.Opbinxor_Caret: // <Op BinXOR> ::= <Op BinXOR> '^' <Op BinAND> return new BitwiseXorExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opbinxor: // <Op BinXOR> ::= <Op BinAND> return r.get_Data(0); case ProductionIndex.Opbinand_Amp: // <Op BinAND> ::= <Op BinAND> '&' <Op Equate> return new BitwiseAndExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opbinand: // <Op BinAND> ::= <Op Equate> return r.get_Data(0); case ProductionIndex.Opequate_Eqeq: // <Op Equate> ::= <Op Equate> '==' <Op Compare> return new EqualsExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opequate_Exclameq: // <Op Equate> ::= <Op Equate> '!=' <Op Compare> return new NotEqualExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opequate: // <Op Equate> ::= <Op Compare> return r.get_Data(0); case ProductionIndex.Opcompare_Lt: // <Op Compare> ::= <Op Compare> '<' <Op Shift> return new LessThanExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opcompare_Gt: // <Op Compare> ::= <Op Compare> '>' <Op Shift> return new GreaterThanExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opcompare_Lteq: // <Op Compare> ::= <Op Compare> '<=' <Op Shift> return new LessOrEqualToExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opcompare_Gteq: // <Op Compare> ::= <Op Compare> '>=' <Op Shift> return new GreaterOrEqualExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opcompare: // <Op Compare> ::= <Op Shift> return r.get_Data(0); case ProductionIndex.Opshift_Ltlt: // <Op Shift> ::= <Op Shift> '<<' <Op Add> return new BitwiseLeftShiftExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opshift_Gtgt: return new BitwiseRightShiftExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opshift: // <Op Shift> ::= <Op Add> return r.get_Data(0); case ProductionIndex.Opadd_Plus: // <Op Add> ::= <Op Add> '+' <Op Mult> return new AddExpression(left: r.get_Data(0) as Expression, right: r.get_Data(2) as Expression); case ProductionIndex.Opadd_Minus: // <Op Add> ::= <Op Add> '-' <Op Mult> return new SubExpression(left: r.get_Data(0) as Expression, right: r.get_Data(2) as Expression); case ProductionIndex.Opadd: // <Op Add> ::= <Op Mult> return r.get_Data(0); case ProductionIndex.Opmult_Times: // <Op Mult> ::= <Op Mult> '*' <Op Unary> return new MulExpression(left: r.get_Data(0) as Expression, right: r.get_Data(2) as Expression); case ProductionIndex.Opmult_Div: // <Op Mult> ::= <Op Mult> '/' <Op Unary> return new DivisionExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opmult_Percent: // <Op Mult> ::= <Op Mult> '%' <Op Unary> return new ModExpression(left: r.GetData(0) as Expression, right: r.GetData(2) as Expression); case ProductionIndex.Opmult: // <Op Mult> ::= <Op Unary> return r.get_Data(0); case ProductionIndex.Opunary_Exclam: // <Op Unary> ::= '!' <Op Unary> return new NotEqualToExpression(r.GetData(1) as Expression); case ProductionIndex.Opunary_Tilde: // <Op Unary> ::= '~' <Op Unary> return new OneComplementExpression(r.get_Data(1) as Expression); case ProductionIndex.Opunary_Minus: // <Op Unary> ::= '-' <Op Unary> return new NegateExpression(r.get_Data(1) as Expression); case ProductionIndex.Opunary_Times: // <Op Unary> ::= '*' <Op Unary> return new PointerExpression(r.get_Data(1) as Expression); case ProductionIndex.Opunary_Amp: // <Op Unary> ::= '&' <Op Unary> return new ReferenceExpression(r.get_Data(1) as Expression); case ProductionIndex.Opunary_Plusplus: // <Op Unary> ::= '++' <Op Unary> return new PreIncrementExpression(r.get_Data(1) as Expression); case ProductionIndex.Opunary_Minusminus: // <Op Unary> ::= '--' <Op Unary> return new PreDecrementExpression(r.GetData(1) as Expression); case ProductionIndex.Opunary_Plusplus2: // <Op Unary> ::= <Op Pointer> '++' return new PostIncrementExpression(r.get_Data(0) as Expression); case ProductionIndex.Opunary_Minusminus2: // <Op Unary> ::= <Op Pointer> '--' return new PostDecrementExpression(r.GetData(0) as Expression); case ProductionIndex.Opunary_Lparen_Rparen: // <Op Unary> ::= '(' <Type> ')' <Op Unary> break; case ProductionIndex.Opunary_Sizeof_Lparen_Rparen: // <Op Unary> ::= sizeof '(' <Type> ')' break; case ProductionIndex.Opunary_Sizeof_Lparen_Id_Rparen: // <Op Unary> ::= sizeof '(' Id <Pointers> ')' break; case ProductionIndex.Opunary: // <Op Unary> ::= <Op Pointer> return r.get_Data(0); case ProductionIndex.Oppointer_Dot: // <Op Pointer> ::= <Op Pointer> '.' <Value> return new PointerReferenceAccessExpr(r.GetData(0) as Expression, r.GetData(2) as Expression); case ProductionIndex.Oppointer_Minusgt: // <Op Pointer> ::= <Op Pointer> '->' <Value> return new PointerAccessExpr(r.GetData(0) as Expression, r.GetData(2) as Expression); case ProductionIndex.Oppointer_Lbracket_Rbracket: // <Op Pointer> ::= <Op Pointer> '[' <Expr> ']' return new PointerArrayAccessExpr(r.GetData(0) as Expression, r.GetData(2) as Expression); case ProductionIndex.Oppointer: // <Op Pointer> ::= <Value> return r.get_Data(0); case ProductionIndex.Value_Octliteral: // <Value> ::= OctLiteral return new DecValue(Convert.ToInt32(r.get_Data(0).ToString(),8)); case ProductionIndex.Value_Hexliteral: // <Value> ::= HexLiteral return new DecValue(Convert.ToInt32(r.GetData(0).ToString(),16)); case ProductionIndex.Value_Decliteral: // <Value> ::= DecLiteral return new DecValue(Convert.ToInt32(r.get_Data(0))); case ProductionIndex.Value_Stringliteral: // <Value> ::= StringLiteral return new StringLiteral(r.GetData(0).ToString()); case ProductionIndex.Value_Charliteral: // <Value> ::= CharLiteral return new CharLiteral(Convert.ToByte(Convert.ToChar(r.GetData(0)))); case ProductionIndex.Value_Floatliteral: // <Value> ::= FloatLiteral return new FloatLiteral(Convert.ToDouble(r.GetData(0))); case ProductionIndex.Value_Id_Lparen_Rparen: // <Value> ::= Id '(' <Expr> ')' return new FunctionCallExpression(r.GetData(0).ToString(),r.GetData(2) as Expression); case ProductionIndex.Value_Id_Lparen_Rparen2: // <Value> ::= Id '(' ')' return new FunctionCallExpression(r.GetData(0).ToString()); case ProductionIndex.Value_Id: // <Value> ::= Id if (r.GetData(0).ToString() == "true") { return new DecValue(1); } else if (r.GetData(0).ToString() == "false") { return new DecValue(0); } else return new IdValue(r.GetData(0).ToString()); case ProductionIndex.Value_Lparen_Rparen: // <Value> ::= '(' <Expr> ')' return r.GetData(1) as Expression; } //switch return result; }
/// <summary> /// works out changes when we have a repeating block (e.g all the properties on a content type) /// </summary> private IEnumerable <uSyncChange> CalculateRepeatingChanges(TrackedItem change, XElement current, XElement target, string name, string path) { var updates = new List <uSyncChange>(); var currentItems = current.XPathSelectElements(path); var targetItems = target.XPathSelectElements(path); var currentIndex = 0; // loop through the nodes in the current item foreach (var currentNode in currentItems) { var currentNodePath = path; var currentNodeName = name; XElement targetNode = null; // if the key is blank we just compare the values in the elements if (string.IsNullOrWhiteSpace(change.Repeating.Key)) { if (change.Repeating.ElementsInOrder) { if (targetItems.Count() > currentIndex) { targetNode = targetItems.ElementAt(currentIndex); } } else { // if the element isn't the key, then we get the first one (by value) // if the value is different in this case we will consider this a delete targetNode = targetItems.FirstOrDefault(x => x.Value == currentNode.Value); } } else { // we need to find the current key value var currentKey = GetKeyValue(currentNode, change.Repeating.Key, change.Repeating.KeyIsAttribute); if (currentKey == string.Empty) { continue; } // now we need to make the XPath for the children this will be [key = ''] or [@key =''] // depending if its an attribute or element key currentNodePath += MakeKeyPath(change.Repeating.Key, currentKey, change.Repeating.KeyIsAttribute); if (!string.IsNullOrWhiteSpace(change.Repeating.Name)) { var itemName = GetKeyValue(currentNode, change.Repeating.Name, change.Repeating.NameIsAttribute); if (!string.IsNullOrWhiteSpace(itemName)) { currentNodeName += $": {itemName}"; } } // now see if we can find that node in the target elements we have loaded targetNode = GetTarget(targetItems, change.Repeating.Key, currentKey, change.Repeating.KeyIsAttribute); } if (targetNode == null) { // no target, this element will get deleted var oldValue = currentNode.Value; if (!string.IsNullOrWhiteSpace(change.Repeating.Name)) { oldValue = GetKeyValue(currentNode, change.Repeating.Name, change.Repeating.NameIsAttribute); } updates.Add(uSyncChange.Delete(path, name, oldValue)); continue; } // check all the children of the current and target for changes if (change.Children != null && change.Children.Any()) { foreach (var child in change.Children) { updates.AddRange(CalculateChanges(child, currentNode, targetNode, currentNodeName, currentNodePath)); } } else { // if there are no children, they we are comparing the actual text of the nodes updates.AddNotNull(Compare(currentNodePath, currentNodeName, currentNode.ValueOrDefault(string.Empty), targetNode.ValueOrDefault(string.Empty), change.MaskValue)); } currentIndex++; } if (!change.Repeating.ElementsInOrder) { // look for things in target but not current (for they will be removed) List <XElement> missing = new List <XElement>(); if (string.IsNullOrWhiteSpace(change.Repeating.Key)) { missing = targetItems.Where(x => !currentItems.Any(t => t.Value == x.Value)) .ToList(); } else { foreach (var targetItem in targetItems) { var targetNodePath = path; var targetKey = GetKeyValue(targetItem, change.Repeating.Key, change.Repeating.KeyIsAttribute); if (string.IsNullOrEmpty(targetKey)) { continue; } targetNodePath += MakeKeyPath(change.Repeating.Key, targetKey, change.Repeating.KeyIsAttribute); var currentNode = GetTarget(currentItems, change.Repeating.Key, targetKey, change.Repeating.KeyIsAttribute); if (currentNode == null) { missing.Add(targetItem); } } } if (missing.Any()) { foreach (var missingItem in missing) { var oldValue = missingItem.Value; if (!string.IsNullOrWhiteSpace(change.Repeating.Name)) { oldValue = GetKeyValue(missingItem, change.Repeating.Name, change.Repeating.NameIsAttribute); } updates.Add(uSyncChange.Create(path, name, oldValue)); } } } return(updates); }
private IEnumerable <uSyncChange> CalculateSingleChange(TrackedItem change, XElement current, XElement target, string name, string path) { var updates = new List <uSyncChange>(); var currentNode = current; var targetNode = target; if (!string.IsNullOrEmpty(path)) { currentNode = current.XPathSelectElement(path); targetNode = target.XPathSelectElement(path); if (currentNode == null) { if (targetNode != null) { return(uSyncChange.Create(path, name, targetNode.ValueOrDefault(string.Empty), change.CompareValue) .AsEnumerableOfOne()); } // if both are null, just return nothing. return(updates); } if (targetNode == null) { // its a delete (not in target) return(uSyncChange.Delete(path, name, currentNode.ValueOrDefault(string.Empty), change.CompareValue) .AsEnumerableOfOne()); } // this happens if both exist, we compare values in them. if (change.CompareValue) { // actual change updates.AddNotNull(Compare(path, name, currentNode.ValueOrDefault(string.Empty), targetNode.ValueOrDefault(string.Empty), change.MaskValue)); } if (change.Attributes != null && change.Attributes.Any()) { foreach (var attribute in change.Attributes) { var currentValue = currentNode.Attribute(attribute).ValueOrDefault(string.Empty); var targetValue = targetNode.Attribute(attribute).ValueOrDefault(string.Empty); updates.AddNotNull(Compare(path, $"{name} [{attribute}]", currentValue, targetValue, change.MaskValue)); } } } if (change.Children != null && change.Children.Any()) { foreach (var child in change.Children) { updates.AddRange(CalculateChanges(child, currentNode, targetNode, name, path)); } } return(updates); }
public virtual LockingInfo[] GetLockingInfo(string uniqueName) { PresentationInfo presentationInfo = _presentationDAL.GetPresentationInfo(uniqueName); List<ObjectKey> objectKeys = new List<ObjectKey> { ObjectKeyCreator.CreatePresentationKey(uniqueName) }; foreach (SlideInfo slideInfo in presentationInfo.SlideInfoList) { objectKeys.Add(ObjectKeyCreator.CreateSlideKey(uniqueName, slideInfo.Id)); } LockingInfo[] lockingInfos = GetLockingInfo(objectKeys.ToArray()); List<LockingInfo> lockingList = new List<LockingInfo>(); foreach (LockingInfo info in lockingInfos) { lockingList.AddNotNull(info); } return lockingList.ToArray(); }
public virtual LockingInfo[] GetLockingInfo(ObjectKey[] objectKeyArr) { List<LockingInfo> lockingInfoArr = new List<LockingInfo>(objectKeyArr.Length); foreach (ObjectKey objectKey in objectKeyArr) { LockingInfo info = _lockService.GetLockInfo(objectKey); lockingInfoArr.AddNotNull(info); } return lockingInfoArr.ToArray(); }
protected override SyncAttempt <IMedia> DeserializeCore(XElement node, SyncSerializerOptions options) { var attempt = FindOrCreate(node); if (!attempt.Success) { throw attempt.Exception; } var item = attempt.Result; var details = new List <uSyncChange>(); details.AddRange(DeserializeBase(item, node, options)); if (node.Element("Info") != null) { var trashed = node.Element("Info").Element("Trashed").ValueOrDefault(false); details.AddNotNull(HandleTrashedState(item, trashed)); } var propertyAttempt = DeserializeProperties(item, node, options); if (!propertyAttempt.Success) { return(SyncAttempt <IMedia> .Fail(item.Name, item, ChangeType.Fail, "Failed to save properties", propertyAttempt.Exception)); } var info = node.Element("Info"); var sortOrder = info.Element("SortOrder").ValueOrDefault(-1); HandleSortOrder(item, sortOrder); if (details.HasWarning() && options.FailOnWarnings()) { // Fail on warning. means we don't save or publish because something is wrong ? return(SyncAttempt <IMedia> .Fail(item.Name, item, ChangeType.ImportFail, "Failed with warnings", details, new Exception("Import failed because of warnings, and fail on warnings is true"))); } var saveAttempt = mediaService.Save(item); if (!saveAttempt.Success) { var errors = saveAttempt.Result?.EventMessages?.FormatMessages() ?? ""; return(SyncAttempt <IMedia> .Fail(item.Name, item, ChangeType.Fail, errors, saveAttempt.Exception)); } // add warning messages if things are missing var message = ""; if (details.Any(x => x.Change == ChangeDetailType.Warning)) { message += $" with warning(s)"; } // setting the saved flag on the attempt to true, stops base classes from saving the item. return(SyncAttempt <IMedia> .Succeed(item.Name, item, ChangeType.Import, "", true, propertyAttempt.Result)); }
protected override SyncAttempt <IContent> DeserializeCore(XElement node, SyncSerializerOptions options) { var attempt = FindOrCreate(node); if (!attempt.Success) { throw attempt.Exception; } var item = attempt.Result; var details = new List <uSyncChange>(); details.AddRange(DeserializeBase(item, node, options)); if (node.Element("Info") != null) { var trashed = node.Element("Info").Element("Trashed").ValueOrDefault(false); details.AddNotNull(HandleTrashedState(item, trashed)); } details.AddNotNull(DeserializeTemplate(item, node)); var propertiesAttempt = DeserializeProperties(item, node, options); if (!propertiesAttempt.Success) { return(SyncAttempt <IContent> .Fail(item.Name, item, ChangeType.ImportFail, "Failed to deserialize properties", attempt.Exception)); } details.AddRange(propertiesAttempt.Result); // sort order var sortOrder = node.Element("Info").Element("SortOrder").ValueOrDefault(-1); details.AddNotNull(HandleSortOrder(item, sortOrder)); var publishTimer = Stopwatch.StartNew(); if (details.HasWarning() && options.FailOnWarnings()) { // Fail on warning. means we don't save or publish because something is wrong ? return(SyncAttempt <IContent> .Fail(item.Name, item, ChangeType.ImportFail, "Failed with warnings", details, new Exception("Import failed because of warnings, and fail on warnings is true"))); } // published status // this does the last save and publish var saveAttempt = DoSaveOrPublish(item, node, options); if (saveAttempt.Success) { var message = saveAttempt.Result; if (details.Any(x => x.Change == ChangeDetailType.Warning)) { message += $" with warning(s)"; } if (publishTimer.ElapsedMilliseconds > 10000) { message += $" (Slow publish {publishTimer.ElapsedMilliseconds}ms)"; } var changeType = options.GetSetting(uSyncConstants.DefaultSettings.OnlyPublishDirty, uSyncConstants.DefaultSettings.OnlyPublishDirty_Default) && !item.IsDirty() ? ChangeType.NoChange : ChangeType.Import; // we say no change back, this stops the core second pass function from saving // this item (which we have just done with DoSaveOrPublish) return(SyncAttempt <IContent> .Succeed(item.Name, item, changeType, message, true, details)); } else { return(SyncAttempt <IContent> .Fail(item.Name, item, ChangeType.ImportFail, saveAttempt.Result, saveAttempt.Exception)); } }
protected IEnumerable <uSyncChange> DeserializeProperties(TObject item, XElement node) { logger.Debug(serializerType, "Deserializing Properties"); var propertiesNode = node?.Element("GenericProperties"); if (propertiesNode == null) { return(Enumerable.Empty <uSyncChange>()); } /// there are something we can't do in the loop, /// so we store them and do them once we've put /// things in. List <string> propertiesToRemove = new List <string>(); Dictionary <string, string> propertiesToMove = new Dictionary <string, string>(); List <uSyncChange> changes = new List <uSyncChange>(); foreach (var propertyNode in propertiesNode.Elements("GenericProperty")) { var alias = propertyNode.Element("Alias").ValueOrDefault(string.Empty); if (string.IsNullOrEmpty(alias)) { continue; } var key = propertyNode.Element("Key").ValueOrDefault(alias.GetHashCode().ToGuid()); var definitionKey = propertyNode.Element("Definition").ValueOrDefault(Guid.Empty); var propertyEditorAlias = propertyNode.Element("Type").ValueOrDefault(string.Empty); logger.Debug(serializerType, " > Property: {0} {1} {2} {3}", alias, key, definitionKey, propertyEditorAlias); bool IsNew = false; var property = GetOrCreateProperty(item, key, alias, definitionKey, propertyEditorAlias, out IsNew); if (property == null) { continue; } if (key != Guid.Empty && property.Key != key) { changes.AddUpdate("Key", property.Key, key, $"{alias}/Key"); property.Key = key; } if (property.Alias != alias) { changes.AddUpdate("Alias", property.Alias, alias, $"{alias}/Alias"); property.Alias = alias; } var name = propertyNode.Element("Name").ValueOrDefault(alias); if (property.Name != name) { changes.AddUpdate("Name", property.Name, name, $"{alias}/Name"); property.Name = name; } var description = propertyNode.Element("Description").ValueOrDefault(string.Empty); if (property.Description != description) { changes.AddUpdate("Description", property.Description, description, $"{alias}/Description"); property.Description = description; } var mandatory = propertyNode.Element("Mandatory").ValueOrDefault(false); if (property.Mandatory != mandatory) { changes.AddUpdate("Mandatory", property.Mandatory, mandatory, $"{alias}/Mandatory"); property.Mandatory = mandatory; } var regEx = propertyNode.Element("Validation").ValueOrDefault(string.Empty); if (property.ValidationRegExp != regEx) { changes.AddUpdate("Validation", property.ValidationRegExp, regEx, $"{alias}/RegEx"); property.ValidationRegExp = propertyNode.Element("Validation").ValueOrDefault(string.Empty); } var sortOrder = propertyNode.Element("SortOrder").ValueOrDefault(0); if (property.SortOrder != sortOrder) { changes.AddUpdate("SortOrder", property.SortOrder, sortOrder, $"{alias}/SortOrder"); property.SortOrder = sortOrder; } // added in v8.6 // reflection is fast but a a quick check of version is faster ! if (UmbracoVersion.LocalVersion.Major > 8 || UmbracoVersion.LocalVersion.Minor >= 6) { changes.AddNotNull(DeserializeNewProperty <string>(property, propertyNode, "MandatoryMessage")); changes.AddNotNull(DeserializeNewProperty <string>(property, propertyNode, "ValidationRegExpMessage")); } changes.AddRange(DeserializeExtraProperties(item, property, propertyNode)); var tab = propertyNode.Element("Tab").ValueOrDefault(string.Empty); if (IsNew) { changes.AddNew(alias, name, alias); logger.Debug(serializerType, "Property Is new adding to tab."); if (string.IsNullOrWhiteSpace(tab)) { item.AddPropertyType(property); } else { item.AddPropertyType(property, tab); } } else { logger.Debug(serializerType, "Property exists, checking tab location"); // we need to see if this one has moved. if (!string.IsNullOrWhiteSpace(tab)) { var tabGroup = item.PropertyGroups.FirstOrDefault(x => x.Name.InvariantEquals(tab)); if (tabGroup != null) { if (!tabGroup.PropertyTypes.Contains(property.Alias)) { // add to our move list. propertiesToMove[property.Alias] = tab; } } } } } // move things between tabs. changes.AddRange(MoveProperties(item, propertiesToMove)); // remove what needs to be removed changes.AddRange(RemoveProperties(item, propertiesNode)); return(changes); }