public void AddRange() { CodeTypeReference ref1 = new CodeTypeReference(string.Empty); CodeTypeReference ref2 = new CodeTypeReference(string.Empty); CodeTypeReference ref3 = new CodeTypeReference(string.Empty); CodeTypeReferenceCollection coll1 = new CodeTypeReferenceCollection(); coll1.Add(ref1); coll1.Add(ref2); CodeTypeReferenceCollection coll2 = new CodeTypeReferenceCollection(); coll2.Add(ref3); coll2.AddRange(coll1); Assert.AreEqual(3, coll2.Count, "#1"); Assert.AreEqual(1, coll2.IndexOf(ref1), "#2"); Assert.AreEqual(2, coll2.IndexOf(ref2), "#3"); Assert.AreEqual(0, coll2.IndexOf(ref3), "#4"); CodeTypeReferenceCollection coll3 = new CodeTypeReferenceCollection(); coll3.Add(ref3); coll3.AddRange(new CodeTypeReference[] { ref1, ref2 }); Assert.AreEqual(3, coll2.Count, "#5"); Assert.AreEqual(1, coll2.IndexOf(ref1), "#6"); Assert.AreEqual(2, coll2.IndexOf(ref2), "#7"); Assert.AreEqual(0, coll2.IndexOf(ref3), "#8"); }
public void Add() { CodeTypeReference ref1 = new CodeTypeReference(string.Empty); CodeTypeReference ref2 = new CodeTypeReference(string.Empty); CodeTypeReferenceCollection coll = new CodeTypeReferenceCollection(); Assert.AreEqual(0, coll.Add(ref1), "#1"); Assert.AreEqual(1, coll.Count, "#2"); Assert.AreEqual(0, coll.IndexOf(ref1), "#3"); Assert.AreEqual(1, coll.Add(ref2), "#4"); Assert.AreEqual(2, coll.Count, "#5"); Assert.AreEqual(1, coll.IndexOf(ref2), "#6"); }
public void Constructor2() { CodeTypeReference ref1 = new CodeTypeReference(string.Empty); CodeTypeReference ref2 = new CodeTypeReference(string.Empty); CodeTypeReferenceCollection c = new CodeTypeReferenceCollection(); c.Add(ref1); c.Add(ref2); CodeTypeReferenceCollection coll = new CodeTypeReferenceCollection(c); Assert.AreEqual(2, coll.Count, "#1"); Assert.AreEqual(0, coll.IndexOf(ref1), "#2"); Assert.AreEqual(1, coll.IndexOf(ref2), "#3"); }
protected virtual void AddPageBaseTypes(CodeTypeReferenceCollection baseTypes) { baseTypes.Add(PageBaseClass); baseTypes.Add(typeof(System.Web.IHttpHandler)); switch (parser.EnableSessionState) { case PagesEnableSessionState.ReadOnly: baseTypes.Add(typeof(IReadOnlySessionState)); break; case PagesEnableSessionState.True: baseTypes.Add(typeof(IRequiresSessionState)); break; } }
/// <summary> /// Interfaces do not exist in python, however multi inheritance does. Instead of /// using interfaces, use multi intheritance. /// </summary> private static void ReplaceInterfaceParameters(CodeTypeDeclaration e) { List <string> parameters = new List <string>(); CodeTypeReferenceCollection coll = new CodeTypeReferenceCollection(); for (int i = 0; i < e.BaseTypes.Count; i++) { string baseType = null; if (e.BaseTypes[i].BaseType.StartsWith("I") && Char.IsUpper(e.BaseTypes[i].BaseType[1])) { baseType = e.BaseTypes[i].BaseType.Remove(0, 1); //remove the first character ("I") e.BaseTypes[i].BaseType = baseType; //assigning directly causes a bug } //if after removing the char I from an Interface, the type already exists remove it if (!(parameters.Contains(baseType) || e.BaseTypes[i].BaseType.Equals(e.Name))) { parameters.Add(e.BaseTypes[i].BaseType); coll.Add(e.BaseTypes[i]); } } //copy coll in e.BaseTypes e.BaseTypes.Clear(); foreach (CodeTypeReference tRef in coll) { e.BaseTypes.Add(tRef); } }
public void Remove() { CodeTypeReference ctr1 = new CodeTypeReference(string.Empty); CodeTypeReference ctr2 = new CodeTypeReference(string.Empty); CodeTypeReferenceCollection coll = new CodeTypeReferenceCollection(); coll.Add(ctr1); coll.Add(ctr2); Assert.AreEqual(2, coll.Count, "#1"); Assert.AreEqual(0, coll.IndexOf(ctr1), "#2"); Assert.AreEqual(1, coll.IndexOf(ctr2), "#3"); coll.Remove(ctr1); Assert.AreEqual(1, coll.Count, "#4"); Assert.AreEqual(-1, coll.IndexOf(ctr1), "#5"); Assert.AreEqual(0, coll.IndexOf(ctr2), "#6"); }
public void AddRange_Self() { CodeTypeReferenceCollection coll = new CodeTypeReferenceCollection(); coll.Add(new CodeTypeReference(string.Empty)); Assert.AreEqual(1, coll.Count, "#1"); coll.AddRange(coll); Assert.AreEqual(2, coll.Count, "#2"); }
public static CodeTypeReferenceCollection Clone(this CodeTypeReferenceCollection collection) { if (collection == null) { return(null); } CodeTypeReferenceCollection c = new CodeTypeReferenceCollection(); foreach (CodeTypeReference reference in collection) { c.Add(reference.Clone()); } return(c); }
public void Constructor1_Deny_Unrestricted() { CodeTypeReferenceCollection coll = new CodeTypeReferenceCollection(array); coll.CopyTo(array, 0); Assert.AreEqual(1, coll.Add(ctr), "Add"); Assert.AreSame(ctr, coll[0], "this[int]"); coll.AddRange(array); coll.AddRange(coll); Assert.IsTrue(coll.Contains(ctr), "Contains"); Assert.AreEqual(0, coll.IndexOf(ctr), "IndexOf"); coll.Insert(0, ctr); coll.Remove(ctr); }
private CodeTypeReferenceCollection GetCodeTypeReferenceInCodeStatement(CodeStatement statement) { CodeTypeReferenceCollection references = new CodeTypeReferenceCollection(); // Is this a variable declaration statement? if (typeof(CodeVariableDeclarationStatement) == statement.GetType()) { // Add CodeTypeReference used to define the type of the variable to output. CodeVariableDeclarationStatement vdeclStatement = (CodeVariableDeclarationStatement)statement; references.Add(vdeclStatement.Type); // Do we have an initialization expression? if (vdeclStatement.InitExpression != null) { // Add CodeTypeReference in the initialization statement if available. CodeTypeReference r = GetCodeTypeReferenceInCodeExpression(vdeclStatement.InitExpression); Debug.Assert(r != null, "Could not obtain a proper CodeTypeReference from the variable initialization expression."); if (r == null) { Debugger.Break(); } references.Add(r); } } //// Is this a return statement? //else if (typeof(CodeMethodReturnStatement) == statement.GetType()) //{ // CodeMethodReturnStatement retStatement = (CodeMethodReturnStatement)statement; // // Add CodeTypeReference in the return statement if available. // CodeTypeReference r = GetCodeTypeReferenceInCodeExpression(retStatement.Expression); // Debug.Assert(r != null, "Could not obtain a proper CodeTypeReference from the variable initialization expression."); // references.Add(r); //} // Finally return the references. return(references); }
/// <summary> /// Builds the collection of CodeTypeReference for base types of a class. /// </summary> /// <param name="nodes">The nodes containing the configuration.</param> /// <returns>The CodeTypeReferenceCollection to add.</returns> public static CodeTypeReferenceCollection BuildBaseTypes( ArrayList nodes) { CodeTypeReferenceCollection result = new CodeTypeReferenceCollection(); foreach (XmlNode node in nodes) { foreach (XmlNode child in node.ChildNodes) { if (child.LocalName == "BaseType") { result.Add(child.InnerText); } } } return(result); }
public void Add_Null() { CodeTypeReferenceCollection coll = new CodeTypeReferenceCollection(); coll.Add((CodeTypeReference)null); }
/// <summary> /// Builds the appropriate code objects that would build the contents of /// <paramref name="e"/>. /// </summary> /// <param name="e"> /// The <see cref="OpenXmlElement"/> object to codify. /// </param> /// <param name="settings"> /// The <see cref="ISerializeSettings"/> to use during the code generation /// process. /// </param> /// <param name="typeCounts"> /// A lookup <see cref="IDictionary{TKey, TValue}"/> object containing the /// number of times a given type was referenced. This is used for variable naming /// purposes. /// </param> /// <param name="namespaces"> /// Collection <see cref="ISet{T}"/> used to keep track of all openxml namespaces /// used during the process. /// </param> /// <param name="elementName"> /// The variable name of the root <see cref="OpenXmlElement"/> object that was built /// from the <paramref name="e"/>. /// </param> /// <returns> /// A collection of code statements and expressions that could be used to generate /// a new <paramref name="e"/> object from code. /// </returns> public static CodeStatementCollection BuildCodeStatements( this OpenXmlElement e, ISerializeSettings settings, IDictionary <Type, int> typeCounts, ISet <string> namespaces, out string elementName) { // argument validation if (e is null) { throw new ArgumentNullException(nameof(e)); } if (settings is null) { throw new ArgumentNullException(nameof(settings)); } if (typeCounts is null) { throw new ArgumentNullException(nameof(typeCounts)); } if (namespaces is null) { throw new ArgumentNullException(nameof(namespaces)); } // method vars var result = new CodeStatementCollection(); var elementType = e.GetType(); // If current element is OpenXmlUnknownElement and IgnoreUnknownElements // setting is enabled, return an empty CodeStatementCollection and // proceed no further. if (settings.IgnoreUnknownElements && e is OpenXmlUnknownElement) { elementName = String.Empty; return(result); } // If current element is OpenXmlMiscNode and its XmlNodeType is found in // the IgnoreMiscNoteTypes setting, return an empty CodeStatementCollection // and proceed no futher. if (e is OpenXmlMiscNode eMisc) { if (settings.IgnoreMiscNodeTypes != null && settings.IgnoreMiscNodeTypes.Contains(eMisc.XmlNodeType)) { elementName = String.Empty; return(result); } } // If there is any custom code available for the current element, use the // custom code instead if (settings?.Handlers != null && settings.Handlers.TryGetValue(elementType, out IOpenXmlHandler customHandler)) { // Make sure that the current handler implements IOpenXmlElementHandler. // If so, return the custom code statement collection. if (customHandler is IOpenXmlElementHandler cHandler) { // Only return the custom code statements if the hanlder // implementation doesn't return null var customCodeStatements = cHandler.BuildCodeStatements( e, settings, typeCounts, namespaces, out elementName); if (customCodeStatements != null) { return(customCodeStatements); } } } // Build the initializer for the current element elementName = elementType.GenerateVariableName(typeCounts); CodeStatement statement; CodeObjectCreateExpression createExpression; CodeMethodReferenceExpression methodReferenceExpression; CodeMethodInvokeExpression invokeExpression; CodeTypeReferenceCollection typeReferenceCollection; CodeTypeReference typeReference; // Used for dealing with thrown FormatExceptions Func <string, CodeStatement> handleFmtException; // Dictionary used to map complex objects to element properties var simpleTypePropReferences = new Dictionary <string, string>(); Type tmpType = null; string simpleName = null; string junk = null; object val = null; object propVal = null; PropertyInfo pi = null; OpenXmlSimpleType tmpSimpleType; // Start pulling out the properties of the current element. var sProperties = elementType.GetOpenXmlSimpleValuesProperties(); var cProps = elementType.GetOpenXmlSimpleTypeProperties(false); IReadOnlyList <PropertyInfo> cProperties = cProps .Where(m => !m.PropertyType.IsEnumValueType()) .ToList(); IReadOnlyList <PropertyInfo> enumProperties = cProps .Where(m => m.PropertyType.IsEnumValueType()) .ToList(); // Create a variable reference statement CodeAssignStatement primitivePropertyAssignment( string objName, string varName, string rVal, bool varIsRef = false) { var rValExp = (varIsRef ? new CodeVariableReferenceExpression(rVal) : new CodePrimitiveExpression(rVal) as CodeExpression); return(new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(objName), varName), rValExp)); } // Add the current element type namespace to the set object namespaces.Add(elementType.Namespace); // Need to build the non enumvalue complex objects first before assigning // them as properties of the current element foreach (var complex in cProperties) { // Get the value of the current property val = complex.GetValue(e); // Skip properties that are null if (val is null) { continue; } // Add the complex property namespace to the set namespaces.Add(complex.PropertyType.Namespace); // Use the junk var to store the property type name junk = complex.PropertyType.Name; // Build the variable name simpleName = complex.PropertyType.GenerateVariableName(typeCounts); // Need to handle the generic properties special when trying // to build a variable name. if (complex.PropertyType.IsGenericType) { // Setup necessary CodeDom objects typeReferenceCollection = new CodeTypeReferenceCollection(); foreach (var gen in complex.PropertyType.GenericTypeArguments) { typeReferenceCollection.Add(gen.Name); } typeReference = new CodeTypeReference(junk); typeReference.TypeArguments.AddRange(typeReferenceCollection); createExpression = new CodeObjectCreateExpression(typeReference); statement = new CodeVariableDeclarationStatement(typeReference, simpleName, createExpression); } else { createExpression = new CodeObjectCreateExpression(junk); statement = new CodeVariableDeclarationStatement(junk, simpleName, createExpression); } result.Add(statement); // Finish the variable assignment statement result.Add(primitivePropertyAssignment(simpleName, "InnerText", val.ToString())); result.AddBlankLine(); // Keep track of the objects to assign to the current element // complex properties simpleTypePropReferences.Add(complex.Name, simpleName); } // Initialize the mc attribute information, if available if (e.MCAttributes != null) { tmpType = e.MCAttributes.GetType(); simpleName = tmpType.GenerateVariableName(typeCounts); createExpression = new CodeObjectCreateExpression(tmpType.Name); statement = new CodeVariableDeclarationStatement(tmpType.Name, simpleName, createExpression); result.Add(statement); foreach (var m in tmpType.GetStringValueProperties()) { val = m.GetValue(e.MCAttributes); if (val != null) { statement = new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(simpleName), m.Name), new CodePrimitiveExpression(val.ToString())); result.Add(statement); } } result.AddBlankLine(); simpleTypePropReferences.Add("MCAttributes", simpleName); } // Include the alias prefix if the current element belongs to a class // within the namespaces identified to needing an alias junk = elementType.GetObjectTypeName(settings.NamespaceAliasOptions.Order); createExpression = new CodeObjectCreateExpression(junk); // OpenXmlUknownElement objects require the calling of custom constructors if (e is OpenXmlUnknownElement) { createExpression.Parameters.AddRange(new CodeExpression[] { new CodePrimitiveExpression(e.Prefix), new CodePrimitiveExpression(e.LocalName), new CodePrimitiveExpression(e.NamespaceUri) }); } // OpenXmlLeafTextElement classes have constructors that take in // one StringValue object as a parameter to populate the new // object's Text property. This takes advantange of that knowledge. else if (elementType.IsSubclassOf(typeof(OpenXmlLeafTextElement))) { var leafText = elementType.GetProperty("Text").GetValue(e); var param = new CodePrimitiveExpression(leafText); createExpression.Parameters.Add(param); } statement = new CodeVariableDeclarationStatement(junk, elementName, createExpression); result.Add(statement); // Don't forget to add any additional namespaces to the element if (e.NamespaceDeclarations != null && e.NamespaceDeclarations.Count() > 0) { result.AddBlankLine(); foreach (var ns in e.NamespaceDeclarations) { methodReferenceExpression = new CodeMethodReferenceExpression( new CodeVariableReferenceExpression(elementName), "AddNamespaceDeclaration"); invokeExpression = new CodeMethodInvokeExpression(methodReferenceExpression, new CodePrimitiveExpression(ns.Key), new CodePrimitiveExpression(ns.Value)); result.Add(invokeExpression); } // Add a line break if namespace declarations were present and if the current // element has additional properties that need to be filled out. if ((cProperties.Count > 0 || simpleTypePropReferences.Count > 0) || (sProperties.Count > 0 && sProperties.Count(sp => sp.GetValue(e) != null) > 0)) { result.AddBlankLine(); } } // Now set the properties of the current variable foreach (var p in sProperties) { val = p.GetValue(e); if (val == null) { continue; } // Add the simple property type namespace to the set namespaces.Add(p.PropertyType.Namespace); tmpSimpleType = val as OpenXmlSimpleType; if (!tmpSimpleType.HasValue) { statement = new CodeCommentStatement( $"'{val}' is not a valid value for the {p.Name} property"); } else { propVal = val.GetType().GetProperty("Value").GetValue(val); statement = new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(elementName), p.Name), new CodePrimitiveExpression(propVal)); } result.Add(statement); } if (simpleTypePropReferences.Count > 0) { foreach (var sProp in simpleTypePropReferences) { statement = new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(elementName), sProp.Key), new CodeVariableReferenceExpression(sProp.Value)); result.Add(statement); } } // Go through the list of complex properties again but include // EnumValue`1 type properties in the search. foreach (var cp in enumProperties) { val = cp.GetValue(e); simpleName = null; if (val is null) { continue; } pi = cp.PropertyType.GetProperty("Value"); simpleName = pi.PropertyType.GetObjectTypeName(settings.NamespaceAliasOptions.Order); // Add the simple property type namespace to the set namespaces.Add(pi.PropertyType.Namespace); handleFmtException = (eName) => new CodeCommentStatement( $"Could not parse value of '{cp.Name}' property for variable " + $"`{eName}` - {simpleName} enum does not contain '{val}' field"); // This code may run into issues if, for some unfortunate reason, the xml schema used to help // create the current OpenXml SDK library is not set correctly. If that happens, the // catch statements will print out the current line of code as a comment as a stop gap until // the issue is reported and fix. try { statement = new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(elementName), cp.Name), new CodeFieldReferenceExpression( new CodeVariableReferenceExpression(simpleName), pi.GetValue(val).ToString())); } catch (TargetInvocationException tie) when(tie.InnerException != null && tie.InnerException is FormatException) { // This is used if the value retrieved from an element property // doesn't match any of the enum values of the expected property // type statement = handleFmtException(elementName); } catch (FormatException) { statement = handleFmtException(elementName); } catch { throw; } result.Add(statement); } // Insert an empty line result.AddBlankLine(); // See if the current element has children and retrieve that information if (e.HasChildren) { foreach (var child in e) { // Ignore OpenXmlUnknownElement objects if specified if (settings.IgnoreUnknownElements && child is OpenXmlUnknownElement) { continue; } // use recursion to generate source code for the child elements result.AddRange( child.BuildCodeStatements(settings, typeCounts, namespaces, out string appendName)); methodReferenceExpression = new CodeMethodReferenceExpression( new CodeVariableReferenceExpression(elementName), "Append"); invokeExpression = new CodeMethodInvokeExpression(methodReferenceExpression, new CodeVariableReferenceExpression(appendName)); result.Add(invokeExpression); result.AddBlankLine(); } } // Return all of the collected expressions and statements return(result); }
public static void Add(this CodeTypeReferenceCollection collection, string ns, string type, params CodeTypeReference[] typeArguments) { collection.Add(new CodeTypeReference(string.Join(".", ns, type), typeArguments)); }
public static void Add(this CodeTypeReferenceCollection collection, string ns, string type) { collection.Add(new CodeTypeReference(string.Join(".", ns, type))); }
// CodeTypeReferenceCollection public void CodeTypeReferenceCollectionExample() { //<Snippet1> //<Snippet2> // Creates an empty CodeTypeReferenceCollection. CodeTypeReferenceCollection collection = new CodeTypeReferenceCollection(); //</Snippet2> //<Snippet3> // Adds a CodeTypeReference to the collection. collection.Add(new CodeTypeReference(typeof(bool))); //</Snippet3> //<Snippet4> // Adds an array of CodeTypeReference objects to the collection. CodeTypeReference[] references = { new CodeTypeReference(typeof(bool)), new CodeTypeReference(typeof(bool)) }; collection.AddRange(references); // Adds a collection of CodeTypeReference objects to the collection. CodeTypeReferenceCollection referencesCollection = new CodeTypeReferenceCollection(); referencesCollection.Add(new CodeTypeReference(typeof(bool))); referencesCollection.Add(new CodeTypeReference(typeof(bool))); collection.AddRange(referencesCollection); //</Snippet4> //<Snippet5> // Tests for the presence of a CodeTypeReference in the // collection, and retrieves its index if it is found. CodeTypeReference testReference = new CodeTypeReference(typeof(bool)); int itemIndex = -1; if (collection.Contains(testReference)) { itemIndex = collection.IndexOf(testReference); } //</Snippet5> //<Snippet6> // Copies the contents of the collection, beginning at index 0, // to the specified CodeTypeReference array. // 'references' is a CodeTypeReference array. collection.CopyTo(references, 0); //</Snippet6> //<Snippet7> // Retrieves the count of the items in the collection. int collectionCount = collection.Count; //</Snippet7> //<Snippet8> // Inserts a CodeTypeReference at index 0 of the collection. collection.Insert(0, new CodeTypeReference(typeof(bool))); //</Snippet8> //<Snippet9> // Removes the specified CodeTypeReference from the collection. CodeTypeReference reference = new CodeTypeReference(typeof(bool)); collection.Remove(reference); //</Snippet9> //<Snippet10> // Removes the CodeTypeReference at index 0. collection.RemoveAt(0); //</Snippet10> //</Snippet1> }