コード例 #1
0
        /// <summary>
        /// Sets the info on the GUI.
        /// Some of this parameters can be edited by user so use <c>ReadInterface</c> method
        /// to gather all changed names or disabled variables.
        /// </summary>
        public void InitializeInterface(IList <CodeVariable> vars, IList <CodeVariable> toDisable, CodeModelLanguages language)
        {
            int            i = 0;
            IList <string> varNames;
            IList <string> propNames;

            // generate output names:
            storedLanguage = language;
            NameHelper.GetVariableNames(vars, out varNames, out propNames, checkUpdateNames.Checked, language);

            dataVars.Rows.Clear();
            if (vars != null)
            {
                storedVars = vars;

                // create array to store 2 states for each row:
                modifiedVars = new bool[2 * vars.Count];

                foreach (CodeVariable v in vars)
                {
                    dataVars.Rows.Add((toDisable != null && toDisable.Contains(v)? false: true), v.Name, varNames[i], propNames[i]);
                    i++;
                }
            }

            ActiveControl = bttOK;
        }
コード例 #2
0
        private static bool ProcessClassGuidAttribute(CodeEditPoint editorEditPoint, string guid)
        {
            CodeFunction currentFunction =
                editorEditPoint.GetCurrentCodeElement <CodeFunction>(vsCMElement.vsCMElementFunction);

            // if inside the function, then applying of an attribute to class/struct is prohibited:
            if (currentFunction != null)
            {
                return(false);
            }

            // if the current place is inside string characters: ""
            // then don't jump to the class definition:
            EditPoint startString = editorEditPoint.EditPoint.CreateEditPoint();

            startString.CharLeft(1);
            string s = startString.GetText(2);

            if (s == "\"\"" || editorEditPoint.IsSelected)
            {
                return(false);
            }

            CodeClass          currentClass  = editorEditPoint.GetCurrentCodeElement <CodeClass>(vsCMElement.vsCMElementClass);
            CodeStruct         currentStruct = editorEditPoint.GetCurrentCodeElement <CodeStruct>(vsCMElement.vsCMElementStruct);
            EditPoint          start         = null;
            CodeModelLanguages language      = CodeModelLanguages.Unknown;

            // find the start location of current class:
            if (currentClass != null)
            {
                start    = currentClass.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint();
                language = CodeHelper.GetCodeLanguage(currentClass.Language);
            }

            // find the start location of current structure:
            if (currentStruct != null)
            {
                start    = currentStruct.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint();
                language = CodeHelper.GetCodeLanguage(currentStruct.Language);
            }

            // append attributes at the 'start' location:
            if (start != null)
            {
                string sourceCodeSnippet = CodeHelper.GenerateFromAttribute(language,
                                                                            VariableHelper.GetGuidAttribute(guid));

                if (language == CodeModelLanguages.VisualBasic)
                {
                    sourceCodeSnippet += Environment.NewLine;
                }

                start.ReplaceText(start, sourceCodeSnippet, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
                return(true);
            }

            // nothing special found... just insert the Guid string...
            return(false);
        }
コード例 #3
0
        /// <summary>
        /// Gets the names of the paramters based on a given set of variables.
        /// Each variable generates one name.
        /// </summary>
        public static IList <string> GetParameterNames(IList <CodeVariable> vars, CodeModelLanguages language)
        {
            if (vars == null || vars.Count == 0)
            {
                return(null);
            }

            IList <string> paramNames = new List <string>(vars.Count);
            string         name;

            // generate name in secure mode:
            foreach (CodeVariable v in vars)
            {
                name = GetParameterName(v.Name, language);

                while (paramNames.Contains(name))
                {
                    name = "_" + name;
                }

                paramNames.Add(name);
            }

            return(paramNames);
        }
コード例 #4
0
        /// <summary>
        /// Converts given number into hex string.
        /// </summary>
        public static string ToHex(string number, CodeModelLanguages language)
        {
            if (!string.IsNullOrEmpty(number))
            {
                uint value;

                if (uint.TryParse(number, out value))
                {
                    return(ToHex(value, language));
                }

                if (uint.TryParse(number, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out value))
                {
                    return(ToHex(value, language));
                }

                if ((number.StartsWith("0x") || number.StartsWith("0X") || number.StartsWith("&H")) &&
                    uint.TryParse(number.Substring(2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out value))
                {
                    return(ToHex(value, language));
                }
            }

            // parsing failed, return string:
            return(number);
        }
コード例 #5
0
        protected override string GenerateStringCode(string inputFileContent)
        {
            string globalNamespaceName;
            string guidListClassName;
            string cmdIdListClassName;
            string supporterPostfix;
            bool   isPublic;

            // get parameters passed as 'FileNamespace' inside properties of the file generator:
            InterpreteArguments((string.IsNullOrEmpty(FileNamespace) ? null : FileNamespace.Split(';')),
                                out globalNamespaceName, out guidListClassName, out cmdIdListClassName,
                                out supporterPostfix, out isPublic);

            // create support CodeDOM classes:
            CodeNamespace       globalNamespace   = new CodeNamespace(globalNamespaceName);
            CodeTypeDeclaration classGuideList    = CreateClass(guidListClassName, VsctComments.ClassGuideListComment, isPublic);
            CodeTypeDeclaration classPkgCmdIDList = CreateClass(cmdIdListClassName, VsctComments.ClassPkgCmdIDListComments, isPublic);
            CodeModelLanguages  currentLanguage   = CodeHelper.GetCodeLanguage(GetProject().CodeModel.Language);
            IList <NamedValue>  guids;
            IList <NamedValue>  ids;

            // retrieve the list GUIDs and IDs defined inside VSCT file:
            VsctParser.Parse(inputFileContent, out guids, out ids);

            // generate members describing GUIDs:
            if (guids != null)
            {
                foreach (NamedValue s in guids)
                {
                    s.Supporter = s.Name + supporterPostfix;
                    classGuideList.Members.Add(CreateConstField("System.String", s.Supporter, s.Value, true));
                }

                foreach (NamedValue g in guids)
                {
                    classGuideList.Members.Add(CreateStaticField("Guid", g.Name, g.Supporter, true));
                }
            }

            // generate members describing IDs:
            if (ids != null)
            {
                foreach (NamedValue i in ids)
                {
                    classPkgCmdIDList.Members.Add(CreateConstField("System.UInt32", i.Name,
                                                                   ConversionHelper.ToHex(i.Value, currentLanguage),
                                                                   false));
                }
            }

            // add all members to final namespace:
            globalNamespace.Imports.Add(new CodeNamespaceImport("System"));
            globalNamespace.Types.Add(classGuideList);
            globalNamespace.Types.Add(classPkgCmdIDList);

            // generate source code:
            return(CodeHelper.GenerateFromNamespace(GetCodeProvider(), globalNamespace, true));
        }
コード例 #6
0
        /// <summary>
        /// Serialize given number into hex representation.
        /// </summary>
        public static string ToHex(uint value, CodeModelLanguages language)
        {
            switch (language)
            {
            case CodeModelLanguages.VisualBasic:
                return("&H" + value.ToString("X4"));

            default:
                return("0x" + value.ToString("X4"));
            }
        }
コード例 #7
0
        /// <summary>
        /// Returns 'true' if given project is managed.
        /// </summary>
        public static bool IsManaged(Project p)
        {
            try
            {
                CodeModelLanguages language = CodeHelper.GetCodeLanguage(p.CodeModel.Language);

                return(language == CodeModelLanguages.VisualBasic ||
                       language == CodeModelLanguages.VisualCSharp);
            }
            catch
            {
                return(false);
            }
        }
コード例 #8
0
        /// <summary>
        /// Gets the name of the property based on a given variable name.
        /// </summary>
        public static string GetPropertyName(string variableName, CodeModelLanguages language)
        {
            StringBuilder result = new StringBuilder(variableName);

            if (RemoveLeadingUnderscore(variableName, result, true))
            {
                RemoveInternalUnderscore(result.ToString(), result);
            }
            else
            {
                RemoveInternalUnderscore(variableName, result);
            }

            return(result.ToString());
        }
コード例 #9
0
ファイル: CodeHelper.cs プロジェクト: zy26/tytannet
        /// <summary>
        /// Returns a CodeDomProvider object for the given language.
        /// </summary>
        public static CodeDomProvider GetCodeProvider(CodeModelLanguages language)
        {
            switch (language)
            {
            case CodeModelLanguages.VisualBasic:
                return(CodeDomProvider.CreateProvider("VB"));

            case CodeModelLanguages.VisualJSharp:
                return(CodeDomProvider.CreateProvider("VJ#"));

            case CodeModelLanguages.VisualC:
            case CodeModelLanguages.VisualManagedC:
                return(CodeDomProvider.CreateProvider("MC"));

            default:
                return(CodeDomProvider.CreateProvider("C#"));
            }
        }
コード例 #10
0
        private bool Refactor(IList <CodeNamedElement> codeElements, string codeClassName, string languageGuid, CodeElements codeMembers, EditPoint insertLocation, out int gotoLine)
        {
            // set invalid goto-line:
            gotoLine = -1;

            if (codeElements != null)
            {
                // get the language and a list of currently available properties:
                CodeModelLanguages language = CodeHelper.GetCodeLanguage(languageGuid);

                // update parameter names for each element:
                NameHelper.UpdateParameterNames(codeElements, language);

                if (cfgDialog == null)
                {
                    cfgDialog = new InitConstructorRefactorForm();
                }

                cfgDialog.InitInterface(codeElements);

                if (cfgDialog.ShowDialog() == DialogResult.OK && cfgDialog.ReadInterface(out codeElements))
                {
                    // generate code based on user modifications:
                    string code = GenerateSourceCodeOutput(codeClassName, codeElements, language);

                    // insert code to the editor:
                    if (!string.IsNullOrEmpty(code))
                    {
                        insertLocation.ReplaceText(insertLocation, code, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);

                        // jump without selection to the insertion place:
                        gotoLine = insertLocation.Line + 2;
                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #11
0
        /// <summary>
        /// Create constructor <c>CodeElement</c>.
        /// </summary>
        private static CodeMemberMethod CreateConstructor(string codeClassName, CodeModelLanguages language, bool hasVariables)
        {
            CodeMemberMethod initConstructor;

            if (language == CodeModelLanguages.VisualBasic)
            {
                // for VisualBasic work with CodeConstructor class:
                initConstructor = new CodeConstructor();
            }
            else
            {
                // for C# and others work with CodeMemberMethod as in another way this constructor
                // will not have a name:
                initConstructor = new CodeMemberMethod();
            }

            initConstructor.Name       = codeClassName;
            initConstructor.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            initConstructor.ReturnType = new CodeTypeReference(" ");

            if (hasVariables)
            {
                // add comment:
                initConstructor.Comments.Add(new CodeCommentStatement("<summary>", true));
                initConstructor.Comments.Add(new CodeCommentStatement("Init constructor of " + codeClassName + ".", true));
                initConstructor.Comments.Add(new CodeCommentStatement("</summary>", true));
            }
            else
            {
                // add comment:
                initConstructor.Comments.Add(new CodeCommentStatement("<summary>", true));
                initConstructor.Comments.Add(new CodeCommentStatement("Default constructor of " + codeClassName + ".", true));
                initConstructor.Comments.Add(new CodeCommentStatement("</summary>", true));
            }

            return(initConstructor);
        }
コード例 #12
0
        private static string GenerateSourceCodeOutput(string codeClassName, IList <CodeNamedElement> codeElements, CodeModelLanguages language)
        {
            CodeTypeMemberCollection code            = new CodeTypeMemberCollection();
            CodeTypeMember           initConstructor = VariableHelper.GetInitConstructor(codeClassName, codeElements, language);

            code.Add(initConstructor);
            return(Environment.NewLine + CodeHelper.GenerateFromMember(language, code));
        }
コード例 #13
0
        /// <summary>
        /// Generates the init constructor that is based on the given variables.
        /// </summary>
        public static CodeTypeMember GetInitConstructor(string codeClassName, IList <CodeVariable> vars, IList <string> paramNames, CodeModelLanguages language)
        {
            CodeMemberMethod initConstructor = CreateConstructor(codeClassName, language, vars != null && vars.Count > 0);

            int i = 0;

            if (vars != null)
            {
                //// if all the variables are shared, then make assumption
                //// that the whole class is shared:
                //if (VariableHelper.AreShared(vars))
                //    initConstructor.Attributes = MemberAttributes.Static | MemberAttributes.Final;

                // generate names for parameters if not given:
                if (paramNames == null)
                {
                    paramNames = NameHelper.GetParameterNames(vars, language);
                }

                foreach (CodeVariable v in vars)
                {
                    string paramName = paramNames[i++];

                    // declare parameter:
                    initConstructor.Parameters.Add(new CodeParameterDeclarationExpression(" " + v.Type.AsString, paramName));

                    // make usage of this parameter:
                    if (v.IsShared)
                    {
                        initConstructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(codeClassName), v.Name),
                                                                               new CodeVariableReferenceExpression(paramName)));
                    }
                    else
                    {
                        initConstructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), v.Name),
                                                                               new CodeVariableReferenceExpression(paramName)));
                    }
                }
            }

            return(initConstructor);
        }
コード例 #14
0
 /// <summary>
 /// Gets the normalized name of the variable.
 /// Remember that using this method may generate conflicts if such a name already exists,
 /// and these conflicts should be solved by the caller.
 /// </summary>
 public static string GetVariableName(string variableName, CodeModelLanguages language)
 {
     return(char.ToLower(variableName[0]) + variableName.Substring(1));
 }
コード例 #15
0
        /// <summary>
        /// Updates the parameter names for each <c>CodeNamedElement</c> item.
        /// </summary>
        public static void UpdateParameterNames(IList <CodeNamedElement> codeElements, CodeModelLanguages language)
        {
            if (codeElements == null || codeElements.Count == 0)
            {
                return;
            }

            List <string> paramNames = new List <string>();
            string        name;

            // generate name in secure mode:
            foreach (CodeNamedElement e in codeElements)
            {
                name = GetParameterName(e.Name, language);

                while (paramNames.Contains(name))
                {
                    name = "_" + name;
                }

                e.ParameterName = name;
                paramNames.Add(name);
            }
        }
コード例 #16
0
        private static bool ProcessText(ICollection <string> selectedLines, out string[] resultLines, CodeModelLanguages language)
        {
            resultLines = new string[selectedLines.Count];
            int    index = 0;
            string assign;

            foreach (string l in selectedLines)
            {
                int position = GetPosition(l, '=');
                if (position >= 0)
                {
                    assign = l.Substring(position + 1).Trim();
                    bool isSemicolon;
                    if (assign.EndsWith(";"))
                    {
                        isSemicolon = true;
                        assign      = assign.Substring(0, assign.Length - 1).Trim();
                    }
                    else
                    {
                        isSemicolon = false;
                    }

                    resultLines[index] = string.Format("{0} = {1}{2}", assign, l.Substring(0, position - 1), (isSemicolon ? ";" : string.Empty));
                }
                else
                {
                    resultLines[index] = l;
                }

                index++;
            }

            return(true);
        }
コード例 #17
0
ファイル: CodeHelper.cs プロジェクト: zy26/tytannet
 /// <summary>
 /// Generates source code from given CodeTypeMemberCollection.
 /// </summary>
 public static string GenerateFromMember(CodeModelLanguages language, CodeTypeMemberCollection memberCollection)
 {
     return(GenerateFromMember(GetCodeProvider(language), memberCollection, true));
 }
コード例 #18
0
        private static string GenerateSourceCodeOutput(string codeClassName, IEnumerable <CodeVariable> vars, IList <string> varNames, IList <string> propNames, CodeModelLanguages language, PropertyGeneratorOptions options, string regionName)
        {
            // generate output:
            if (vars != null)
            {
                CodeTypeMemberCollection code = new CodeTypeMemberCollection();
                int index = 0;

                // serialize variables:
                foreach (CodeVariable var in vars)
                {
                    code.Add(VariableHelper.GetProperty(codeClassName, propNames[index], var, varNames[index], options));

                    // replace the variable:
                    var.Name = varNames[index];

                    try
                    {
                        vsCMAccess access;

                        if (VariableHelper.GetVariableAttributes(var, options, out access))
                        {
                            var.Access = access;
                        }
                    }
                    catch
                    {
                    }

                    index++;
                }

                if ((options & PropertyGeneratorOptions.SuppressRegion) != PropertyGeneratorOptions.SuppressRegion)
                {
                    code[0].StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, regionName));
                    code[code.Count - 1].EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, regionName));
                }

                return(CodeHelper.GenerateFromMember(language, code));
            }

            return(null);
        }
コード例 #19
0
        private static void FindExistingProperties(IList <CodeVariable> vars, IList <CodeProperty> props, CodeModelLanguages language, out IList <CodeVariable> toRemove, bool remove)
        {
            // remove redundant properties:
            if (props != null && vars != null)
            {
                toRemove = new List <CodeVariable>();

                foreach (CodeVariable v in vars)
                {
                    if (EditorHelper.Contains(props, NameHelper.GetPropertyName(v.Name, language)))
                    {
                        toRemove.Add(v);
                    }
                }

                if (remove)
                {
                    foreach (CodeVariable v in toRemove)
                    {
                        vars.Remove(v);
                    }
                }
            }
            else
            {
                toRemove = null;
            }
        }
コード例 #20
0
        /// <summary>
        /// Gets the list of new variables' names and new propertys' names without the name conflicts.
        /// </summary>
        public static void GetVariableNames(IList <CodeVariable> vars, out IList <string> varNames, out IList <string> propNames, bool canChangeVarName, CodeModelLanguages language)
        {
            if (vars == null || vars.Count == 0)
            {
                varNames  = null;
                propNames = null;
            }
            else
            {
                varNames  = new List <string>(vars.Count);
                propNames = new List <string>(vars.Count);

                // generate the names:
                foreach (CodeVariable v in vars)
                {
                    string propName = GetPropertyName(v.Name, language);

                    // generate unique property name:
                    while (propNames.Contains(propName))
                    {
                        propName = propName + "Ex";
                    }
                    propNames.Add(propName);

                    // try to generate unique variable name:
                    if (canChangeVarName)
                    {
                        // new variable name will be based on property:
                        string varName = GetVariableName(GetPropertyName(v.Name, language), language);
                        if (string.Compare(propName, varName, language == CodeModelLanguages.VisualBasic) == 0)
                        {
                            do
                            {
                                varName = "_" + GetVariableName(varName, language);
                            } while (string.Compare(propName, varName, true) == 0);
                        }

                        // and if there are already variables with the same name,
                        // it will be prefixed with underline:
                        while (varNames.Contains(varName))
                        {
                            varName = "_" + varName;
                        }

                        varNames.Add(varName);
                    }
                    else
                    {
                        // in case no one allowed variable name manipulations,
                        // the name will remain untouched:
                        varNames.Add(v.Name);
                    }
                }
            }
        }
コード例 #21
0
ファイル: CodeHelper.cs プロジェクト: zy26/tytannet
 /// <summary>
 /// Generates source code from given CodeTypeMemberCollection.
 /// </summary>
 public static string GenerateFromMember(CodeModelLanguages language, CodeTypeMemberCollection memberCollection, bool blankLinesBetweenMembers)
 {
     return(GenerateFromMember(GetCodeProvider(language), memberCollection, blankLinesBetweenMembers));
 }
コード例 #22
0
ファイル: CodeHelper.cs プロジェクト: zy26/tytannet
 /// <summary>
 /// Generates source code from given attributes.
 /// </summary>
 public static string GenerateFromAttribute(CodeModelLanguages language, params CodeAttributeDeclaration[] attributes)
 {
     return(GenerateFromAttribute(GetCodeProvider(language), attributes));
 }
コード例 #23
0
        private bool Refactor(IList <CodeVariable> vars, IList <CodeVariable> disabledVars, string codeClassName, string languageGUID, CodeElements codeMembers, EditPoint insertLocation, out int gotoLine)
        {
            IList <CodeVariable> toDisable;
            IList <CodeProperty> props;
            IList <string>       varNames;
            IList <string>       propNames;

            // set invalid goto-line:
            gotoLine = -1;

            if (vars != null)
            {
                // get the language and a list of currently available properties:
                CodeModelLanguages language = CodeHelper.GetCodeLanguage(languageGUID);
                props = EditorHelper.GetList <CodeProperty>(codeMembers, vsCMElement.vsCMElementProperty);

                // remove the variables from the list for which the properties exist:
                FindExistingProperties(vars, props, language, out toDisable, false);

                // add additional disabled variables:
                if (disabledVars != null)
                {
                    if (toDisable == null)
                    {
                        toDisable = disabledVars;
                    }
                    else
                    {
                        foreach (CodeVariable v in disabledVars)
                        {
                            if (!toDisable.Contains(v))
                            {
                                toDisable.Add(v);
                            }
                        }
                    }
                }

                if (cfgDialog == null)
                {
                    cfgDialog = new PropertyRefactorForm();
                    cfgDialog.GeneratorOptions = PropertyGeneratorOptions.GetterAndSetter | PropertyGeneratorOptions.ForcePropertyPublic | PropertyGeneratorOptions.ForceVarDontChange | PropertyGeneratorOptions.SuppressComment;
                    cfgDialog.RegionName       = RegionName;
                }

                // show dialog with possibility to change:
                cfgDialog.InitializeInterface(vars, toDisable, language);

                if (cfgDialog.ShowDialog() == DialogResult.OK && cfgDialog.ReadInterface(out vars, out varNames, out propNames))
                {
                    // generate code based on user modifications:
                    string code = GenerateSourceCodeOutput(codeClassName, vars, varNames, propNames, language, cfgDialog.GeneratorOptions, cfgDialog.RegionName);

                    // insert code to the editor:
                    if (!string.IsNullOrEmpty(code))
                    {
                        insertLocation.ReplaceText(insertLocation, code, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);

                        // jump without selection to the insertion place:
                        gotoLine = insertLocation.Line;
                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #24
0
        /// <summary>
        /// Generates the init constructor that is based on the given variables.
        /// </summary>
        public static CodeTypeMember GetInitConstructor(string codeClassName, IList <CodeNamedElement> codeElements, CodeModelLanguages language)
        {
            CodeMemberMethod initConstructor = CreateConstructor(codeClassName, language,
                                                                 codeElements != null && codeElements.Count > 0);

            if (codeElements != null)
            {
                //// if all the variables are shared, then make assumption
                //// that the whole class is shared:
                //if (VariableHelper.AreShared(vars))
                //    initConstructor.Attributes = MemberAttributes.Static | MemberAttributes.Final;

                foreach (CodeNamedElement e in codeElements)
                {
                    // declare parameter:
                    initConstructor.Parameters.Add(new CodeParameterDeclarationExpression(" " + e.ReferecedTypeName, e.ParameterName));

                    // make usage of this parameter - create assignment instruction:
                    initConstructor.Statements.Add(new CodeAssignStatement(e.GetReferenceExpression(codeClassName),
                                                                           new CodeVariableReferenceExpression(e.ParameterName)));
                }
            }

            return(initConstructor);
        }