Example #1
0
        private void AddSerializationProperties()
        {
            var addData = parentClass.AddProperty(new CodeProperty(parentClass)
            {
                Name         = "additionalData",
                PropertyKind = CodePropertyKind.AdditionalData,
            }).First();

            addData.Type = new CodeType(addData)
            {
                Name = "string"
            };
            var dummyProp = parentClass.AddProperty(new CodeProperty(parentClass)
            {
                Name = "dummyProp",
            }).First();

            dummyProp.Type = new CodeType(dummyProp)
            {
                Name = "string"
            };
            var dummyCollectionProp = parentClass.AddProperty(new CodeProperty(parentClass)
            {
                Name = "dummyColl",
            }).First();

            dummyCollectionProp.Type = new CodeType(dummyCollectionProp)
            {
                Name           = "string",
                CollectionKind = CodeTypeBase.CodeTypeCollectionKind.Array,
            };
            var dummyComplexCollection = parentClass.AddProperty(new CodeProperty(parentClass)
            {
                Name = "dummyComplexColl"
            }).First();

            dummyComplexCollection.Type = new CodeType(dummyComplexCollection)
            {
                Name           = "Complex",
                CollectionKind = CodeTypeBase.CodeTypeCollectionKind.Array,
                TypeDefinition = new CodeClass(parentClass.Parent)
                {
                    Name = "SomeComplexType"
                }
            };
            var dummyEnumProp = parentClass.AddProperty(new CodeProperty(parentClass)
            {
                Name = "dummyEnumCollection",
            }).First();

            dummyEnumProp.Type = new CodeType(dummyEnumProp)
            {
                Name           = "SomeEnum",
                TypeDefinition = new CodeEnum(parentClass.Parent)
                {
                    Name = "EnumType"
                }
            };
        }
Example #2
0
 private void AddRequestProperties()
 {
     parentClass.AddProperty(new CodeProperty {
         Name = "RequestAdapter",
         Kind = CodePropertyKind.RequestAdapter,
     });
     parentClass.AddProperty(new CodeProperty {
         Name = "pathParameters",
         Kind = CodePropertyKind.PathParameters,
     });
     parentClass.AddProperty(new CodeProperty {
         Name = "urlTemplate",
         Kind = CodePropertyKind.UrlTemplate,
     });
 }
    public CodePropertyWriterTests()
    {
        writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.CSharp, DefaultPath, DefaultName);
        tw     = new StringWriter();
        writer.SetTextWriter(tw);
        var root = CodeNamespace.InitRootNamespace();

        parentClass = new CodeClass {
            Name = "parentClass"
        };
        root.AddClass(parentClass);
        property = new CodeProperty {
            Name = PropertyName,
            Type = new CodeType {
                Name = TypeName
            },
        };
        parentClass.AddProperty(property, new() {
            Name = "pathParameters",
            Kind = CodePropertyKind.PathParameters,
        }, new() {
            Name = "requestAdapter",
            Kind = CodePropertyKind.RequestAdapter,
        });
    }
Example #4
0
        /// <summary>
        /// Adds the property.
        /// </summary>
        /// <param name="codeClass">The code class.</param>
        /// <param name="var">The var.</param>
        /// <returns></returns>
        public static CodeProperty AddProperty(CodeClass codeClass, CodeVariable var)
        {
            CodeProperty prop = null;

            try
            {
                prop = codeClass.AddProperty(
                    FormatPropertyName(var.Name),
                    FormatPropertyName(var.Name),
                    var.Type.AsFullName, -1,
                    vsCMAccess.vsCMAccessPublic, null);

                EditPoint editPoint = prop.Getter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                //Delete return default(int); added by codeClass.AddProperty
                editPoint.Delete(editPoint.LineLength);

                editPoint.Indent(null, 4);
                editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "return {0};", var.Name));

                editPoint = prop.Setter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                editPoint.Indent(null, 1);
                editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "{0} = value;", var.Name));
                editPoint.SmartFormat(editPoint);

                return(prop);
            }
            catch
            {
                //Property already exists
                return(null);
            }
        }
Example #5
0
 public static void AddBackingStoreProperty(this CodeClass codeClass)
 {
     codeClass?.AddProperty(new CodeProperty {
         Name = "backingStore",
         Kind = CodePropertyKind.BackingStore
     });
 }
Example #6
0
        public override void UiBtnCommandAction(Object param)
        {
            if (string.IsNullOrWhiteSpace(UiCommandProppertyName))
            {
                return;
            }
            if (SelectedCodeElement == null)
            {
                return;
            }
            if (SelectedCodeElement.CodeElementRef == null)
            {
                return;
            }
            CodeClass cc = SelectedCodeElement.CodeElementRef as CodeClass;

            if (SelectedViewModel != null)
            {
                SolutionProject prj = ComboItemsSourceProjects.Where(p => string.Equals(p.ProjectUniqueName, SelectedViewModel.RootNodeProjectName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (prj != null)
                {
                    if (!string.Equals(SelectedProject.ProjectUniqueName, prj.ProjectUniqueName, StringComparison.OrdinalIgnoreCase))
                    {
                        if (SelectedProject.ProjectRef.Object is VSProject)
                        {
                            (SelectedProject.ProjectRef.Object as VSProject).References.AddProject(prj.ProjectRef);
                            SelectedProject.ProjectRef.Save();
                        }
                    }
                }
            }



            //cc.AddProperty(UiCommandProppertyName , UiCommandProppertyName, "System.Data.Entity.DbSet<" + SelectedViewModelRootClass + ">", -1, vsCMAccess.vsCMAccessPublic, null);
            CodeProperty codeProperty =
                cc.AddProperty(UiCommandProppertyName, UiCommandProppertyName, "DbSet<" + SelectedViewModelRootClass + ">", -1, vsCMAccess.vsCMAccessPublic, null);
            EditPoint editPoint = codeProperty.Getter.StartPoint.CreateEditPoint();

            editPoint.Delete(codeProperty.Getter.EndPoint);
            editPoint.Insert("get ;");

            editPoint = codeProperty.Setter.StartPoint.CreateEditPoint();
            editPoint.Delete(codeProperty.Setter.EndPoint);
            editPoint.Insert("set ;");
            if (cc.ProjectItem != null)
            {
                if (cc.ProjectItem.IsDirty)
                {
                    cc.ProjectItem.Save();
                }
            }



            DoAnaliseDbContext();
        }
        public void WritePropertyDocs()
        {
            var property = new CodeProperty()
            {
                Name   = "Email",
                Access = AccessModifier.Private,
                Type   = new CodeType()
                {
                    Name = "emailAddress"
                }
            };

            parentClass.AddProperty(property);
            propertyWriter.WriteCodeElement(property, languageWriter);

            var result = stringWriter.ToString();

            Assert.Contains("@var EmailAddress|null $email", result);
            Assert.Contains("private ?EmailAddress $email = null;", result);
        }
Example #8
0
    public CodePropertyWriterTests()
    {
        writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.Go, DefaultPath, DefaultName);
        tw     = new StringWriter();
        writer.SetTextWriter(tw);
        var root = CodeNamespace.InitRootNamespace();

        parentClass = new CodeClass {
            Name = "parentClass"
        };
        root.AddClass(parentClass);
        property = new CodeProperty {
            Name = PropertyName,
        };
        property.Type = new CodeType {
            Name = TypeName
        };
        parentClass.AddProperty(property);
    }
        public void DefinePublicProperty(string propertyName, string typeName)
        {
            FileCodeModel fileCodeModel = _projectItem.FileCodeModel;

            CodeElement   fileCodeElement      = fileCodeModel.CodeElements.Item(1);
            CodeNamespace fileNamespace        = (CodeNamespace)fileCodeElement;
            CodeElement   fileNamespaceElement = fileNamespace.Members.Item(1);
            CodeClass     codeClass            = (CodeClass)fileNamespaceElement;

            var l = codeClass.Language;

            codeClass.AddProperty(propertyName, propertyName, typeName, 0, vsCMAccess.vsCMAccessPublic);

            codeClass.AddVariable(propertyName, typeName, -1, vsCMAccess.vsCMAccessPublic);



            //fileCodeModel.AddVariable(propertyName, typeName, -1, vsCMAccess.vsCMAccessPublic);



            //CodeElement fileCodeElement = fileCodeModel.CodeElements.Item(1);
            //CodeNamespace fileNamespace = (CodeNamespace)fileCodeElement;
            //CodeElement fileNamespaceElement = fileNamespace.Members.Item(1);
            //CodeClass codeClass = (CodeClass)fileNamespaceElement;


            //var prop = codeClass.AddVariable(propertyName, typeName, -1, vsCMAccess.vsCMAccessPublic);
            //var startPoint = prop.StartPoint;
            //int linelength = startPoint.LineLength;
            //var edit = startPoint.CreateEditPoint();
            //var currentLine = edit.GetLines(edit.Line, edit.Line + 1).TrimStart();
            //var newLine = currentLine.Replace(";", " { get; set; }");
            //edit.Delete(currentLine.Length);
            //edit.Insert(newLine);
        }
Example #10
0
        private bool AddPropertyToClass(DBObjectWithType obj, CodeClass newClass, Column v)
        {
            bool failure = false;

            SauceClassGenerationPackage.OutputWindow.OutputStringThreadSafe(string.Format("Processing Column: {0}.{1}..{2}", obj.Object.Name, v.Name, Environment.NewLine));
            TranslateResult result = TranslateToClr(v.DataType);
            string          name   = MakeLegalName(v.Name);

            CodeProperty2 newProp = (CodeProperty2)newClass.AddProperty(name, name, result.Type, Type.Missing, vsCMAccess.vsCMAccessPublic);

            MakeAutoProperty(newProp);
            AddDataFieldAttribute(newProp, obj.Object, v);

            if (!result.Success)
            {
                failure = true;
                SauceClassGenerationPackage.OutputWindow.OutputStringThreadSafe(string.Format("Unable to translate {0} to a CLR type for {1}.{2}", v.DataType, obj.Object.Name, v.Name));
                this.InvokeOnMe(() =>
                {
                    SauceClassGenerationPackage.OutputWindow.Activate();
                });
            }
            return(failure);
        }
Example #11
0
        protected bool AddMemberElementsFromType(CodeType ct, CodeClass synchClass)
        {
            string indexerParamList = "";

            foreach (CodeElement member in ct.Members)
            {
                CodeFunction cf = member as CodeFunction;
                if (!AddSynchWrapperMember(synchClass, cf))
                {
                    return(false);
                }

                CodeProperty cp = member as CodeProperty;
                if (cp != null)
                {
                    string getter = "";
                    string setter = "";
                    //Getter and Setter throw if property lacks these methods
                    try{
                        if (cp.Getter != null)
                        {
                            getter = cp.Name;
                        }
                    }catch (Exception) {}
                    try{
                        if (cp.Setter != null)
                        {
                            setter = cp.Name;
                        }
                    }catch (Exception) {}

                    CodeFunction spSetter = null;
                    if (cp.Name != "SyncRoot")
                    {
                        CodeProperty sp        = synchClass.AddProperty(getter, setter, cp.Type, -1, cp.Access, null);
                        TextRanges   tr        = null;
                        bool         hasGetter = false;
                        sp.StartPoint.CreateEditPoint().ReplacePattern(sp.EndPoint, sp.Type.AsString, "override " + sp.Type.AsString,
                                                                       (int)EnvDTE.vsFindOptions.vsFindOptionsMatchWholeWord, ref tr);
                        if (getter != "")
                        {
                            hasGetter = true;
                            if (cp.Name != "IsSynchronized")
                            {
                                AddOneLineImpl(sp.Type.AsString + " ret;\nSystem.Threading.Monitor.Enter(_root);" +
                                               "\ntry{\nret = _parent." + getter + ";\n}\nfinally{System.Threading.Monitor.Exit(_root);}" +
                                               "\nreturn ret;", sp.Getter, true);
                            }
                            else
                            {
                                AddOneLineImpl("return true;", sp.Getter, true);
                            }
                        }
                        if (setter != "")
                        {
                            //bug work-around
                            foreach (CodeElement codeElm in synchClass.Members)
                            {
                                if (codeElm.Name == sp.Name)
                                {
                                    spSetter = ((CodeProperty)codeElm).Setter;
                                }
                            }

                            AddOneLineImpl("\nSystem.Threading.Monitor.Enter(_root);" +
                                           "\ntry{\n _parent." + setter + " = value;\n}\nfinally{System.Threading.Monitor.Exit(_root);}",
                                           spSetter, false);
                        }

                        if (cp.Name == "this")                         //fix up indexer override
                        //add parameters
                        {
                            CodeFunction getterOrSetter;
                            if (hasGetter)
                            {
                                getterOrSetter = cp.Getter;
                            }
                            else
                            {
                                getterOrSetter = cp.Setter;
                            }

                            System.Text.StringBuilder paramList        = new System.Text.StringBuilder();
                            System.Text.StringBuilder paramListNoTypes = new System.Text.StringBuilder();
                            bool first = true;
                            foreach (CodeParameter p in cp.Getter.Parameters)
                            {
                                if (!first)
                                {
                                    paramListNoTypes.Append(", ");
                                    paramList.Append(", ");
                                }
                                first = false;
                                paramList.Append(p.Type.AsString);
                                paramList.Append(" ");
                                paramList.Append(p.Name);
                                paramListNoTypes.Append(p.Name);
                            }

                            EditPoint firstLine  = sp.StartPoint.CreateEditPoint();
                            EditPoint secondLine = sp.StartPoint.CreateEditPoint();
                            TextPoint endPt      = sp.EndPoint;
                            secondLine.LineDown(1); secondLine.StartOfLine();
                            TextRanges tr1 = null;
                            firstLine.ReplacePattern(secondLine, "this", "this[" + paramList.ToString() + "]",
                                                     (int)EnvDTE.vsFindOptions.vsFindOptionsMatchWholeWord, ref tr1);

                            //calls - replace .this with [param1, param2]
                            paramListNoTypes.Insert(0, '[');
                            paramListNoTypes.Append("]");
                            indexerParamList = paramListNoTypes.ToString();
                        }
                    }
                }
                if (indexerParamList != "")
                {
                    TextRanges tr = null;
                    synchClass.StartPoint.CreateEditPoint().ReplacePattern(
                        synchClass.EndPoint, ".this", indexerParamList,
                        (int)EnvDTE.vsFindOptions.vsFindOptionsMatchCase, ref tr);
                }
            }
            return(true);
        }
Example #12
0
        public bool MakeBaseClassCompatiableWithSyncPattern()
        {
            CodeType ct = (CodeType)_cc;

            bool isSynchronizedFound = false;
            bool syncRootFound       = false;
            bool synchronizedFound   = false;

            //check base class for non-virtual functions
            for (CodeElements baseClasses = _cc.Bases; baseClasses != null;)
            {
                if (baseClasses.Count == 0)
                {
                    break;
                }
                CodeClass baseClass = baseClasses.Item(1) as CodeClass;
                if (baseClass.Name == "Object")
                {
                    break;
                }

                foreach (CodeElement ceBase in baseClass.Members)
                {
                    CodeFunction cfBase = ceBase as CodeFunction;
                    if (cfBase != null)
                    {
                        if (!cfBase.IsShared && !cfBase.CanOverride &&
                            cfBase.FunctionKind != EnvDTE.vsCMFunction.vsCMFunctionConstructor &&
                            cfBase.Name != "Finalize")
                        {
                            System.Windows.Forms.MessageBox.Show("The selected class contains base classes with non-virtual member functions." +
                                                                 "  Please change these to virtual to allow synchronized wrapper creation.");
                            return(false);
                        }
                    }
                    CodeProperty cpBase = ceBase as CodeProperty;
                    if (cpBase != null)
                    {
                        try{
                            if (!cpBase.Getter.IsShared && !cpBase.Getter.CanOverride)
                            {
                                System.Windows.Forms.MessageBox.Show("The selected class contains base classes with non-virtual member properties." +
                                                                     "  Please change these to virtual to allow synchronized wrapper creation.");
                                return(false);
                            }
                        }catch (Exception) {}
                        try{
                            if (!cpBase.Setter.IsShared && !cpBase.Setter.CanOverride)
                            {
                                System.Windows.Forms.MessageBox.Show("The selected class contains base classes with non-virtual member properties." +
                                                                     "  Please change these to virtual to allow synchronized wrapper creation.");
                                return(false);
                            }
                        }catch (Exception) {}
                    }
                }
                baseClasses = baseClass.Bases;
            }

            //check current clas
            foreach (CodeElement member in ct.Members)
            {
                CodeFunction cf = member as CodeFunction;
                if (!CheckFunctionIsVirtualAndFixIfOK(cf))
                {
                    return(false);
                }

                if (cf != null && cf.Name == "Synchronized")
                {
                    synchronizedFound = true;
                }

                CodeProperty cp = member as CodeProperty;
                if (cp != null)
                {
                    if (cp.Name == "SyncRoot")
                    {
                        syncRootFound = true;
                    }
                    if (cp.Name == "IsSynchronized")
                    {
                        isSynchronizedFound = true;
                    }
                    //Getter and Setter throw if property lacks these methods
                    try{
                        if (!CheckFunctionIsVirtualAndFixIfOK(cp.Getter))
                        {
                            return(false);
                        }
                    }catch (Exception) {}
                    try{
                        if (!CheckFunctionIsVirtualAndFixIfOK(cp.Setter))
                        {
                            return(false);
                        }
                    }catch (Exception) {}
                }
            }

            if (!isSynchronizedFound)
            {
                CodeProperty isSynchProp =
                    _cc.AddProperty("IsSynchronized", "", EnvDTE.vsCMTypeRef.vsCMTypeRefBool, -1, EnvDTE.vsCMAccess.vsCMAccessPublic, null);
                CodeFunction isSynchPropGetter = isSynchProp.Getter;
                isSynchPropGetter.CanOverride = true;
                AddOneLineImpl("return false;", isSynchPropGetter, true);
            }
            if (!syncRootFound)
            {
                CodeProperty syncRootProp =
                    _cc.AddProperty("SyncRoot", "", EnvDTE.vsCMTypeRef.vsCMTypeRefObject, -1, EnvDTE.vsCMAccess.vsCMAccessPublic, null);
                CodeFunction syncRootGetter = syncRootProp.Getter;
                syncRootGetter.CanOverride = true;
                AddOneLineImpl("return this;", syncRootGetter, true);
            }
            if (!synchronizedFound)
            {
                CodeFunction synchronizedStatic = _cc.AddFunction("Synchronized", EnvDTE.vsCMFunction.vsCMFunctionFunction,
                                                                  _cc.FullName, -1, EnvDTE.vsCMAccess.vsCMAccessPublic, null);
                synchronizedStatic.IsShared = true;
                synchronizedStatic.AddParameter("inst", _cc.FullName, -1);
                AddOneLineImpl("return new Synch" + _cc.Name + "(inst);", synchronizedStatic, true);
            }

            _cc.StartPoint.CreateEditPoint().SmartFormat(_cc.EndPoint);

            return(true);
        }
Example #13
0
 private void AddRequestProperties()
 {
     parentClass.AddProperty(new CodeProperty {
         Name = "requestAdapter",
         Kind = CodePropertyKind.RequestAdapter,
     });
     parentClass.AddProperty(new CodeProperty {
         Name = "pathParameters",
         Kind = CodePropertyKind.PathParameters,
         Type = new CodeType {
             Name = "string"
         },
     });
     parentClass.AddProperty(new CodeProperty {
         Name = "UrlTemplate",
         Kind = CodePropertyKind.UrlTemplate,
     });
 }
        /// <summary>
        /// Adds the property.
        /// </summary>
        /// <param name="codeClass">The code class.</param>
        /// <param name="var">The var.</param>
        /// <returns></returns>
        public static CodeProperty AddProperty(CodeClass codeClass, CodeVariable var)
        {
            CodeProperty prop = null;

            try
            {
                prop = codeClass.AddProperty(
                    FormatPropertyName(var.Name),
                    FormatPropertyName(var.Name),
                    var.Type.AsFullName, -1,
                    vsCMAccess.vsCMAccessPublic, null);

                EditPoint editPoint = prop.Getter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                //Delete return default(int); added by codeClass.AddProperty
                editPoint.Delete(editPoint.LineLength);

                editPoint.Indent(null, 4);
                editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "return {0};", var.Name));

                editPoint = prop.Setter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                editPoint.Indent(null, 1);
                editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "{0} = value;", var.Name));
                editPoint.SmartFormat(editPoint);

                return prop;
            }
            catch
            {
                //Property already exists
                return null;
            }
        }
Example #15
0
        /// <summary>
        /// Selects the introduction page html to be at the top of the windows
        /// </summary>
        public override void Execute()
        {
            DTE         vs = GetService <DTE>(true);
            ProjectItem actionClassFile = (ProjectItem)DteHelper.GetTarget(vs);

            if ((actionClassFile == null) || (actionClassFile.FileCodeModel == null) ||
                (actionClassFile.FileCodeModel.CodeElements == null) ||
                (actionClassFile.FileCodeModel.CodeElements.Count == 0))
            {
                return;
            }

            string fieldName = "";

            if ((ParameterName.Length > 1) && (ParameterName[0] >= 'A') && (ParameterName[0] <= 'Z'))
            {
                fieldName = char.ToLower(parameterName[0], CultureInfo.CurrentCulture) +
                            parameterName.Substring(1);
            }
            else
            {
                fieldName = "_" + parameterName;
            }

            string attribute;

            if (ParameterIsOutput)
            {
                attribute = "Output";
            }
            else
            {
                attribute = "Input";
            }
            bool addedProperty = false;

            foreach (CodeElement element in actionClassFile.FileCodeModel.CodeElements)
            {
                if (element.Kind == vsCMElement.vsCMElementNamespace)
                {
                    foreach (CodeElement elementNamespace in ((CodeNamespace)element).Members)
                    {
                        if (elementNamespace.Kind == vsCMElement.vsCMElementClass)
                        {
                            #region Look where to insert the property
                            object    whereToInsert = null;
                            CodeClass classAction   = (CodeClass)elementNamespace;

                            CodeProperty foundProperty = null;
                            foreach (CodeElement classElement in classAction.Members)
                            {
                                if (foundProperty != null)
                                {
                                    if (classElement.Kind == vsCMElement.vsCMElementVariable)
                                    {
                                        // Then insert after this declaration of variable that was after the property
                                        whereToInsert = classElement;
                                    }
                                }
                                if (classElement.Kind == vsCMElement.vsCMElementProperty)
                                {
                                    foundProperty = (CodeProperty)classElement;
                                    bool hasAttribute = false;
                                    for (int i = 1; i <= foundProperty.Attributes.Count; i++)
                                    {
                                        if (foundProperty.Attributes.Item(i).Name == attribute)
                                        {
                                            hasAttribute = true;
                                            break;
                                        }
                                    }
                                    if (!hasAttribute)
                                    {
                                        foundProperty = null;
                                    }
                                }
                            }
                            if (foundProperty != null)
                            {
                                if (whereToInsert == null)
                                {
                                    whereToInsert = foundProperty;
                                }
                            }
                            else if (whereToInsert == null)
                            {
                                whereToInsert = 0;
                            }

                            #endregion

                            CodeProperty prop = classAction.AddProperty(ParameterName, ParameterName, ParameterType, whereToInsert, vsCMAccess.vsCMAccessPublic, actionClassFile.Name);

                            TextPoint getTextTP = prop.Getter.GetStartPoint(vsCMPart.vsCMPartBody);
                            EditPoint getText   = getTextTP.CreateEditPoint();
                            getText.ReplaceText(prop.Getter.GetEndPoint(vsCMPart.vsCMPartBody),
                                                string.Format(CultureInfo.InvariantCulture, "return {0};", fieldName), (int)vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines);
                            getText.SmartFormat(getTextTP);

                            TextPoint setTextTP = prop.Setter.GetStartPoint(vsCMPart.vsCMPartBody);
                            EditPoint setText   = setTextTP.CreateEditPoint();
                            setText.ReplaceText(0, string.Format(CultureInfo.InvariantCulture, "{0}=value;", fieldName), 0);
                            setText.SmartFormat(setTextTP);

                            if (ParameterIsOutput)
                            {
                                prop.AddAttribute(attribute, "", 0);
                            }
                            else
                            {
                                prop.AddAttribute(attribute, "true", 0);
                            }
                            classAction.AddVariable(fieldName, ParameterType, prop, vsCMAccess.vsCMAccessPrivate, actionClassFile.Name);

                            // Stop adding property, just the first class found
                            addedProperty = true;
                            break;
                        }
                    }
                    if (addedProperty)
                    {
                        break;
                    }
                }
            }
        }
Example #16
0
        /// <summary>
        /// Generates the DTOs of the EDMX Document provided using the parameters received.
        /// </summary>
        /// <param name="parameters">Parameters for the generation of DTOs.</param>
        /// <param name="worker">BackgroundWorker reference.</param>
        public static List <DTOEntity> GenerateDTOs(GenerateDTOsParams parameters, BackgroundWorker worker)
        {
            LogManager.LogMethodStart();

            if (parameters.DTOsServiceReady)
            {
                VisualStudioHelper.AddReferenceToProject(parameters.TargetProject,
                                                         Resources.AssemblySystemRuntimeSerialization, Resources.AssemblySystemRuntimeSerialization);
            }

            if (GeneratorManager.CheckCancellationPending())
            {
                return(null);
            }

            EditPoint     objEditPoint;          // EditPoint to reuse
            CodeParameter objCodeParameter;      // CodeParameter to reuse
            CodeNamespace objNamespace   = null; // Namespace item to add Classes
            ProjectItem   sourceFileItem = null; // Source File Item to save
            int           dtosGenerated  = 0;

            List <EnumType> enums = DTOGenerator.GetEnumTypes(parameters);

            PropertyHelper.SetEnumTypes(enums);

            List <DTOEntity> entitiesDTOs = DTOGenerator.GetEntityDTOs(parameters);

            if (GeneratorManager.CheckCancellationPending())
            {
                return(null);
            }

            worker.ReportProgress(0, new GeneratorOnProgressEventArgs(0,
                                                                      string.Format(Resources.Text_DTOsGenerated, dtosGenerated, entitiesDTOs.Count)));

            TemplateClass.CreateFile();

            // Imports to add to the Source File
            var importList = new List <SourceCodeImport>();

            // EnumTypes defined in the EDMX ?
            if (enums.Exists(e => e.IsExternal == false))
            {
                importList.Add(new SourceCodeImport(parameters.EntitiesNamespace));
                VisualStudioHelper.AddReferenceToProject(parameters.TargetProject, parameters.EDMXProject);
            }

            // Include imports of external enums.
            foreach (string externalEnumNamespace in enums.Where(e => e.IsExternal).Select(e => e.Namespace).Distinct())
            {
                importList.Add(new SourceCodeImport(externalEnumNamespace));
            }

            // Generate Source File if type is One Source File
            if (parameters.SourceFileGenerationType == SourceFileGenerationType.OneSourceFile)
            {
                sourceFileItem = null;

                // Generate Source and Get the Namespace item
                objNamespace = VisualStudioHelper.GenerateSourceAndGetNamespace(
                    parameters.TargetProject, parameters.TargetProjectFolder,
                    parameters.SourceFileName, parameters.SourceFileHeaderComment,
                    parameters.SourceNamespace, parameters.DTOsServiceReady, out sourceFileItem);

                // Add Imports to Source File
                VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList);
            }

            // Check Cancellation Pending
            if (GeneratorManager.CheckCancellationPending())
            {
                return(null);
            }

            // Loop through Entities DTOs
            foreach (DTOEntity entityDTO in entitiesDTOs)
            {
                // Generate Source File if type is Source File per Class
                if (parameters.SourceFileGenerationType == SourceFileGenerationType.SourceFilePerClass)
                {
                    sourceFileItem = null;

                    // Generate Source and Get the Namespace item
                    objNamespace = VisualStudioHelper.GenerateSourceAndGetNamespace(
                        parameters.TargetProject, parameters.TargetProjectFolder,
                        entityDTO.NameDTO, parameters.SourceFileHeaderComment,
                        parameters.SourceNamespace, parameters.DTOsServiceReady, out sourceFileItem);

                    // Add Imports to Source File
                    VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList);
                }

                // Add Class
                CodeClass objCodeClass = objNamespace.AddClassWithPartialSupport(entityDTO.NameDTO, entityDTO.NameBaseDTO,
                                                                                 entityDTO.DTOClassAccess, entityDTO.DTOClassKind);

                // Set IsAbstract
                objCodeClass.IsAbstract = entityDTO.IsAbstract;

                // Set Class Attributes
                foreach (DTOAttribute classAttr in entityDTO.Attributes)
                {
                    objCodeClass.AddAttribute(classAttr.Name, classAttr.Parameters, AppConstants.PLACE_AT_THE_END);
                }

                // Set Class Properties
                foreach (DTOClassProperty entityProperty in entityDTO.Properties)
                {
                    // Add Property
                    CodeProperty objCodeProperty = objCodeClass.AddProperty(entityProperty.PropertyName,
                                                                            entityProperty.PropertyName, entityProperty.PropertyType, AppConstants.PLACE_AT_THE_END,
                                                                            entityProperty.PropertyAccess, null);

                    // Get end of accessors auto-generated code
                    objEditPoint = objCodeProperty.Setter.EndPoint.CreateEditPoint();
                    objEditPoint.LineDown();
                    objEditPoint.EndOfLine();
                    var getSetEndPoint = objEditPoint.CreateEditPoint();

                    // Move to the start of accessors auto-generated code
                    objEditPoint = objCodeProperty.Getter.StartPoint.CreateEditPoint();
                    objEditPoint.LineUp();
                    objEditPoint.LineUp();
                    objEditPoint.EndOfLine();

                    // Replace accessors auto-generated code with a more cleaner one
                    objEditPoint.ReplaceText(getSetEndPoint, Resources.CSharpCodeGetSetWithBrackets,
                                             Convert.ToInt32(vsEPReplaceTextOptions.vsEPReplaceTextAutoformat));

                    // Set Property Attributes
                    foreach (DTOAttribute propAttr in entityProperty.PropertyAttributes)
                    {
                        objCodeProperty.AddAttribute(propAttr.Name,
                                                     propAttr.Parameters, AppConstants.PLACE_AT_THE_END);
                    }

                    objEditPoint = objCodeProperty.StartPoint.CreateEditPoint();
                    objEditPoint.SmartFormat(objEditPoint);
                }

                if (parameters.GenerateDTOConstructors)
                {
                    // Add empty Constructor
                    CodeFunction emptyConstructor = objCodeClass.AddFunction(objCodeClass.Name,
                                                                             vsCMFunction.vsCMFunctionConstructor, null, AppConstants.PLACE_AT_THE_END,
                                                                             vsCMAccess.vsCMAccessPublic, null);

                    // Does this DTO have a Base Class ?
                    if (entityDTO.BaseDTO != null)
                    {
                        // Add call to empty Base Constructor
                        objEditPoint = emptyConstructor.StartPoint.CreateEditPoint();
                        objEditPoint.EndOfLine();
                        objEditPoint.Insert(Resources.Space + Resources.CSharpCodeBaseConstructor);
                    }

                    // Does this DTO have properties ?
                    if (entityDTO.Properties.Count > 0)
                    {
                        // Add Constructor with all properties as parameters
                        CodeFunction constructorWithParams = objCodeClass.AddFunction(objCodeClass.Name,
                                                                                      vsCMFunction.vsCMFunctionConstructor, null, AppConstants.PLACE_AT_THE_END,
                                                                                      vsCMAccess.vsCMAccessPublic, null);

                        foreach (DTOClassProperty entityProperty in entityDTO.Properties)
                        {
                            // Add Constructor parameter
                            objCodeParameter = constructorWithParams.AddParameter(
                                Utils.SetFirstLetterLowercase(entityProperty.PropertyName),
                                entityProperty.PropertyType, AppConstants.PLACE_AT_THE_END);

                            // Add assignment
                            objEditPoint = constructorWithParams.EndPoint.CreateEditPoint();
                            objEditPoint.LineUp();
                            objEditPoint.EndOfLine();
                            objEditPoint.Insert(Environment.NewLine + AppConstants.TAB + AppConstants.TAB + AppConstants.TAB);
                            objEditPoint.Insert(string.Format(Resources.CSharpCodeAssignmentThis,
                                                              entityProperty.PropertyName, objCodeParameter.Name));
                        }

                        // Does this DTO have a Base Class ?
                        if (entityDTO.BaseDTO != null)
                        {
                            // Get the Base Class properties (includes the properties of the base recursively)
                            List <DTOClassProperty> baseProperties =
                                DTOGenerator.GetPropertiesForConstructor(entityDTO.BaseDTO);

                            // Base Constructor parameters
                            var sbBaseParameters = new StringBuilder();

                            foreach (DTOClassProperty entityProperty in baseProperties)
                            {
                                // Add Constructor parameter
                                objCodeParameter = constructorWithParams.AddParameter(
                                    Utils.SetFirstLetterLowercase(entityProperty.PropertyName),
                                    entityProperty.PropertyType, AppConstants.PLACE_AT_THE_END);

                                // Add parameter separation if other parameters exists
                                if (sbBaseParameters.Length > 0)
                                {
                                    sbBaseParameters.Append(Resources.CommaSpace);
                                }

                                // Add to Base Constructor parameters
                                sbBaseParameters.Append(objCodeParameter.Name);
                            }

                            // Add call to Base Constructor with parameters
                            objEditPoint = constructorWithParams.StartPoint.CreateEditPoint();
                            objEditPoint.EndOfLine();
                            objEditPoint.Insert(
                                Environment.NewLine + AppConstants.TAB + AppConstants.TAB + AppConstants.TAB);
                            objEditPoint.Insert(
                                string.Format(Resources.CSharpCodeBaseConstructorWithParams, sbBaseParameters.ToString()));
                        } // END if DTO has a Base Class
                    }     // END if DTO has properties
                }         // END if Generate DTO Constructor methods

                // Save changes to Source File Item
                sourceFileItem.Save();

                // Count DTO generated
                dtosGenerated++;

                // Report Progress
                int progress = ((dtosGenerated * 100) / entitiesDTOs.Count);
                if (progress < 100)
                {
                    worker.ReportProgress(progress, new GeneratorOnProgressEventArgs(progress,
                                                                                     string.Format(Resources.Text_DTOsGenerated, dtosGenerated, entitiesDTOs.Count)));
                }

                // Check Cancellation Pending
                if (GeneratorManager.CheckCancellationPending())
                {
                    return(null);
                }
            } // END Loop through Entities DTOs

            // Save Target Project
            parameters.TargetProject.Save();

            // Delete Template Class File
            TemplateClass.Delete();

            // Report Progress
            worker.ReportProgress(100, new GeneratorOnProgressEventArgs(100,
                                                                        string.Format(Resources.Text_DTOsGenerated, dtosGenerated, entitiesDTOs.Count)));

            LogManager.LogMethodEnd();

            // Return the DTOs generated
            return(entitiesDTOs);
        }
Example #17
0
        public void WriteRequestExecutor()
        {
            CodeProperty[] properties =
            {
                new CodeProperty {
                    Kind = CodePropertyKind.RequestAdapter, Name = "requestAdapter"
                },
                new CodeProperty {
                    Kind = CodePropertyKind.UrlTemplate, Name = "urlTemplate"
                },
                new CodeProperty {
                    Kind = CodePropertyKind.PathParameters, Name = "pathParameters"
                },
            };
            parentClass.AddProperty(properties);
            var codeMethod = new CodeMethod()
            {
                Name       = "post",
                HttpMethod = HttpMethod.Post,
                ReturnType = new CodeType()
                {
                    IsExternal = true,
                    Name       = "StreamInterface"
                },
                Description = "This will send a POST request",
                Kind        = CodeMethodKind.RequestExecutor
            };

            codeMethod.AddParameter(new CodeParameter
            {
                Name     = "ResponseHandler",
                Kind     = CodeParameterKind.ResponseHandler,
                Optional = true,
                Type     = new CodeType
                {
                    Name       = "ResponseHandler",
                    IsNullable = true
                }
            });
            var codeMethodRequestGenerator = new CodeMethod()
            {
                Kind       = CodeMethodKind.RequestGenerator,
                HttpMethod = HttpMethod.Post,
                Name       = "createPostRequestInformation",
                ReturnType = new CodeType()
                {
                    Name = "RequestInformation"
                }
            };

            parentClass.AddMethod(codeMethod);
            parentClass.AddMethod(codeMethodRequestGenerator);
            var error4XX = root.AddClass(new CodeClass {
                Name = "Error4XX",
            }).First();
            var error5XX = root.AddClass(new CodeClass {
                Name = "Error5XX",
            }).First();
            var error401 = root.AddClass(new CodeClass {
                Name = "Error401",
            }).First();

            codeMethod.AddErrorMapping("4XX", new CodeType {
                Name = "Error4XX", TypeDefinition = error4XX
            });
            codeMethod.AddErrorMapping("5XX", new CodeType {
                Name = "Error5XX", TypeDefinition = error5XX
            });
            codeMethod.AddErrorMapping("403", new CodeType {
                Name = "Error403", TypeDefinition = error401
            });
            _codeMethodWriter.WriteCodeElement(codeMethod, languageWriter);
            var result = stringWriter.ToString();

            Assert.Contains("Promise", result);
            Assert.Contains("$requestInfo = $this->createPostRequestInformation();", result);
            Assert.Contains("RejectedPromise", result);
            Assert.Contains("catch(Exception $ex)", result);
            Assert.Contains("'403' => array(Error403::class, 'createFromDiscriminatorValue')", result);
            Assert.Contains("return $this->requestAdapter->sendPrimitiveAsync($requestInfo, StreamInterface::class, $responseHandler, $errorMappings);", result);
        }