Ejemplo n.º 1
0
        internal static string GetTextToFirstMatch(TextPoint startPoint, string matchString)
        {
            var startEditPoint = startPoint.CreateEditPoint();
            var endEditPoint = startEditPoint.CreateEditPoint();
            TextRanges subGroupMatches = null;

            if (endEditPoint.FindPattern(matchString, StandardFindOptions, ref endEditPoint, ref subGroupMatches))
            {
                return startEditPoint.GetText(endEditPoint);
            }

            return null;
        }
Ejemplo n.º 2
0
        void Execute(TextPoint StartPoint, TextPoint EndPoint, bool force)
        {
            TextDocument doc = (TextDocument)(_applicationObject.ActiveDocument.
                           Object("TextDocument"));

            //if (StartPoint.Line == EndPoint.Line && StartPoint.LineCharOffset == EndPoint.LineCharOffset)
            //    return;

            if (AStyle.fileMode ==  AStyleInterface.AstyleFilemode.CPP && doc.Language != "C/C++")
                return;

            if (AStyle.fileMode == AStyleInterface.AstyleFilemode.JAVA && doc.Language != "Java")
                return;

            if (AStyle.fileMode == AStyleInterface.AstyleFilemode.SHARP && doc.Language != "C#")
                return;

            if (!force && !AStyle.working)
                return;

            EditPoint startEditPoint = StartPoint.CreateEditPoint();
            EditPoint curEditPoint = StartPoint.CreateEditPoint();
            EditPoint endEditPoint = EndPoint.CreateEditPoint();
            startEditPoint.StartOfLine();
            curEditPoint.StartOfLine();
            endEditPoint.EndOfLine();
            string text = curEditPoint.GetText(endEditPoint);

            String textOut = AStyle.FormatSource(text, AStyleInterface.AstyleFilemode.SHARP);

            int hashik = text.GetHashCode() ^ endEditPoint.AbsoluteCharOffset;

            if(_hashes.Contains(hashik))
                return;

            if (textOut.TrimStart('\t') == text.TrimStart('\t'))
                return;

            if (_hashes.Count > 1000000)
                _hashes.Clear(); // no memory licking!

            _hashes.Add(hashik);

            var curOffset = doc.Selection.ActivePoint.AbsoluteCharOffset;
            int beginLinePos = curEditPoint.AbsoluteCharOffset;
            int beforeLength = endEditPoint.AbsoluteCharOffset - startEditPoint.AbsoluteCharOffset;

            curEditPoint.Delete(endEditPoint);
            curEditPoint.Insert(textOut);
            curEditPoint.MoveToAbsoluteOffset(startEditPoint.AbsoluteCharOffset + textOut.Length);

            doc.Selection.Cancel();
            doc.Selection.MoveToPoint(startEditPoint, false);
            doc.Selection.MoveToPoint(curEditPoint, true);
            _applicationObject.ExecuteCommand("Edit.FormatSelection", "");

            curEditPoint.EndOfLine();

            if (curOffset > beginLinePos)
            {
                doc.Selection.MoveToAbsoluteOffset(curOffset - beforeLength
                    + (curEditPoint.AbsoluteCharOffset - startEditPoint.AbsoluteCharOffset), false);
                _applicationObject.ExecuteCommand("Edit.FormatSelection", "");
            }
            else
                doc.Selection.MoveToAbsoluteOffset(curOffset, false);
        }
Ejemplo n.º 3
0
        private EditPoint Expand(TextPoint point, Action<EditPoint> foundAction)
        {
            EditPoint i = point.CreateEditPoint();
            EditPoint result = null;

            do
            {
                var line = i.Line;
                var text = i.GetLine();

                if (CodeCommentHelper.LineMatchesRegex(i, _commentLineRegex).Success)
                {
                    result = i.CreateEditPoint();
                    foundAction(i);

                    // If result and iterator line are the same, the found action (move line up or
                    // down) did nothing. This means there is no point to keep searching, it would
                    // create an infinite loop.
                    if (result.Line == i.Line)
                    {
                        break;
                    }
                }
                else
                {
                    if (i != null && result != null && CodeCommentHelper.LineMatchesRegex(i, _codeLineRegex).Success)
                    {
                        result = null;
                    }

                    i = null;
                }
            } while (i != null);

            return result;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Expands a text point to the full comment.
        /// </summary>
        /// <param name="point">The original text point to expand from.</param>
        private void Expand(TextPoint point)
        {
            var i = point.CreateEditPoint();

            // Look up to find the start of the comment.
            _startPoint = Expand(point, p => p.LineUp());

            // If a valid start is found, look down to find the end of the comment.
            if (_startPoint != null)
            {
                _endPoint = Expand(point, p => p.LineDown());
            }

            if (StartPoint != null && EndPoint != null)
            {
                _startPoint.StartOfLine();
                _endPoint.EndOfLine();
                IsValid = true;
            }
            else
            {
                IsValid = false;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Expand a textpoint to the full comment, in the direction specified by the <paramref name="foundAction"/>.
        /// </summary>
        /// <param name="point">The initial starting point for the expansion.</param>
        /// <param name="foundAction">An action which advances the search either up or down.</param>
        /// <returns>
        /// The endpoint of the comment, or <c>null</c> if the expansion did not find a valid comment.
        /// </returns>
        private EditPoint Expand(TextPoint point, Action<EditPoint> foundAction)
        {
            EditPoint current = point.CreateEditPoint();
            EditPoint result = null;
            string prefix = null;

            do
            {
                var line = current.Line;
                var text = current.GetLine();

                var match = _commentLineRegex.Match(text);
                if (match.Success)
                {
                    // Cancel the expansion if the prefix does not match. This takes priority over
                    // the initial spacer check to allow formatting comments adjacent to Stylecop
                    // SA1626 style commented code.
                    var currentPrefix = match.Groups["prefix"].Value.TrimStart();
                    if (prefix != null && !string.Equals(prefix, currentPrefix))
                    {
                        break;
                    }
                    else
                    {
                        prefix = currentPrefix;
                    }

                    // The initial spacer is required, otherwise we assume this is commented out
                    // code and do not format.
                    if (match.Groups["initialspacer"].Success)
                    {
                        result = current.CreateEditPoint();
                        foundAction(current);

                        // If result and iterator line are the same, the found action (move line up or
                        // down) did nothing. This means we're at the start or end of the file, and
                        // there is no point to keep searching, it would create an infinite loop.
                        if (result.Line == current.Line)
                        {
                            break;
                        }
                    }
                    else
                    {
                        // Did not succesfully match the intial spacer, we have to assume this is
                        // code and cancel all formatting.
                        result = null;
                        current = null;
                    }
                }
                else
                {
                    current = null;
                }
            } while (current != null);

            return result;
        }
Ejemplo n.º 6
0
        private EditPoint Expand(TextPoint point, Action<EditPoint> foundAction)
        {
            EditPoint current = point.CreateEditPoint();
            EditPoint result = null;
            string prefix = null;

            do
            {
                var line = current.Line;
                var text = current.GetLine();

                var match = _commentLineRegex.Match(text);
                if (match.Success)
                {
                    // The initial spacer is required, otherwise we assume this is commented out
                    // code and do not format.
                    if (match.Groups["initialspacer"].Success)
                    {
                        // Get the comment prefix for the current line.
                        var currentPrefix = match.Groups["prefix"].Value.TrimStart();
                        if (prefix == null) { prefix = currentPrefix; }

                        // Cancel the expanding if the prefix does not match.
                        if (prefix != currentPrefix)
                        {
                            break;
                        }

                        result = current.CreateEditPoint();
                        foundAction(current);

                        // If result and iterator line are the same, the found action (move line up or
                        // down) did nothing. This means we're at the start or end of the file, and
                        // there is no point to keep searching, it would create an infinite loop.
                        if (result.Line == current.Line)
                        {
                            break;
                        }
                    }
                    else
                    {
                        // This is code! Set to null to abandon loop.
                        result = null;
                        current = null;
                    }
                }
                else
                {
                    current = null;
                }
            } while (current != null);

            return result;
        }
        /// <summary>Parses for strings by iterating through the text lines.</summary>
        /// <param name="element">The element.</param>
        /// <param name="stringResources">The string resources.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="isCSharp">If set to <c>true</c> it is CSharp code.</param>
        /// <param name="startLine">The start line.</param>
        /// <param name="endLine">The end line.</param>
        /// <returns>The last parsed line number or -1.</returns>
        private static int ParseForStrings(CodeElement element,
                                           List <StringResource> stringResources,
                                           Settings settings,
                                           bool isCSharp,
                                           int startLine,
                                           int endLine)
        {
            TextPoint startPoint = element.StartPoint,
                      endPoint   = element.EndPoint;
            EditPoint2 editPoint = null;

            try
            {
                if (element.Kind == vsCMElement.vsCMElementFunction)
                {
#if DEBUG_OUTPUT
                    System.Diagnostics.Debug.Print("    function kind: {0}", (element as CodeFunction).FunctionKind);
#endif

                    try
                    {
                        //we want to have the body only (throws COMException when inspecting an expression bodied function)
                        startPoint = element.GetStartPoint(vsCMPart.vsCMPartBody);
                        endPoint   = element.GetEndPoint(vsCMPart.vsCMPartBody);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.Print("ParseForStrings(vsCMElementFunction, line {0}): {1} - {2}", startPoint.Line, ex.GetType().Name, ex.Message);
                    }
                }

                editPoint = startPoint.CreateEditPoint() as EditPoint2;

                int editLine       = editPoint.Line,
                    editColumn     = editPoint.LineCharOffset;
                string   text      = editPoint.GetText(endPoint);
                string[] txtLines  = text.Replace("\r", string.Empty).Split('\n');
                bool     isComment = false;
#if IGNORE_METHOD_ARGUMENTS
                bool isIgnoreMethodArguments = false;
#endif

                foreach (string txtLine in txtLines)
                {
                    if ((editLine >= startLine) && (editLine <= endLine))
                    {
                        //this is a changed text line in the block

#if !IGNORE_METHOD_ARGUMENTS
                        if (txtLine.Contains("\""))
                        {
                            ParseForStrings(txtLine, editLine, editColumn, stringResources, settings, isCSharp, ref isComment);
                        }
#else
                        if (line.Contains("\""))
                        {
                            ParseForStrings(line, editLine, editColumn, stringResources, settings, ref isComment, ref isIgnoreMethodArguments);
                        }
#endif
                    }

                    ++editLine;

                    //only for the first line of the text block LineCharOffset will be used
                    if (editColumn > 1)
                    {
                        editColumn = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print("### Error: ParseForStrings(): {0} - {1}", ex.GetType().Name, ex.Message);
            }

            return(endPoint?.Line ?? (-1));
        }
        /// <summary>Parses for strings by iterating through the FileCodeModel.</summary>
        /// <param name="startPoint">The start point.</param>
        /// <param name="endPoint">The end point.</param>
        /// <param name="lastDocumentLength">Last length of the document.</param>
        private void ParseForStrings(TextPoint startPoint,
                                     TextPoint endPoint,
                                     int lastDocumentLength)
        {
            //0.35-0.06 seconds (threaded: 2.47-1.77 seconds)
            List <StringResource> stringResources = new List <StringResource>();

            bool isFullDocument          = startPoint.AtStartOfDocument && endPoint.AtEndOfDocument,
                 isTextWithStringLiteral = true;
            int startLine      = startPoint.Line,
                startCol       = startPoint.LineCharOffset,
                endLine        = endPoint.Line,
                endCol         = endPoint.LineCharOffset,
                documentLength = endPoint.Parent.EndPoint.Line,
                insertIndex    = 0;

            if (isFullDocument)
            {
                m_StringResources.Clear();
            }
            else
            {
                #region document manipulated -> adapt string resources and locations

                //determine whether the text between startLine and endLine (including) contains double quotes
                EditPoint editPoint = startPoint.CreateEditPoint() as EditPoint2;
                if (!startPoint.AtStartOfLine)
                {
                    editPoint.StartOfLine();
                }
                isTextWithStringLiteral = editPoint.GetLines(startLine, endLine + 1).Contains("\"");

                //move trailing locations behind changed lines if needed and
                //remove string resources on changed lines

                int lineOffset = documentLength - lastDocumentLength;
#if DEBUG_OUTPUT
                System.Diagnostics.Debug.Print("  Line offset is {0}", lineOffset);
#endif

                for (int i = m_StringResources.Count - 1; i >= 0; --i)
                {
                    StringResource stringResource = m_StringResources[i];
                    int            lineNo         = stringResource.Location.X;

                    if (lineNo + lineOffset > endLine)
                    {
                        if (lineOffset != 0)
                        {
#if DEBUG_OUTPUT
                            System.Diagnostics.Debug.Print("  Move string literal from line {0} to {1}", lineNo, lineNo + lineOffset);
#endif
                            stringResource.Offset(lineOffset, 0); //move
                        }
                    }
                    else if (lineNo >= startLine)
                    {
#if DEBUG_OUTPUT
                        System.Diagnostics.Debug.Print("  Remove string literal {0} ({1}): {2}", i, stringResource.Location, stringResource.Text);
#endif
                        m_StringResources.RemoveAt(i); //remove changed line
                    }
                    else if (insertIndex == 0)
                    {
#if DEBUG_OUTPUT
                        System.Diagnostics.Debug.Print("  List insert index is {0} / {1}", i + 1, m_StringResources.Count - 1);
#endif
                        insertIndex = i + 1;
                    }
                }

                #endregion
            }

#if DEBUG_OUTPUT
            System.Diagnostics.Debug.Print("  Text has{0} string literals.", isTextWithStringLiteral ? string.Empty : " no");
#endif

            if (isTextWithStringLiteral)
            {
                CodeElements elements = m_Window.Document.ProjectItem.FileCodeModel.CodeElements;

                foreach (CodeElement element in elements)
                {
                    ParseForStrings(element, m_DoProgress, stringResources, m_Settings, m_IsCSharp, startLine, endLine);

#if DEBUG
                    if (element.Kind == vsCMElement.vsCMElementProperty)
                    {
                        CodeProperty prop = element as CodeProperty;

                        if ((prop.Getter == null) && (prop.Setter == null))
                        {
                        }
                    }
#endif
                }

#if DEBUG_OUTPUT
                System.Diagnostics.Debug.Print("  Found {0} string literals", stringResources.Count);
#endif

                if (isFullDocument)
                {
                    m_StringResources.AddRange(stringResources);
                }
                else if (stringResources.Count > 0)
                {
                    m_StringResources.InsertRange(insertIndex, stringResources);
                }
            }

            m_DoCompleted(isFullDocument || (stringResources.Count > 0));
        }
Ejemplo n.º 9
0
        private void EditMigrations(Dictionary <string, string> properties)
        {
            // Edit migrations
            var migration = _viewModel.SelectedMigration.CodeType;
            var cc        = migration as CodeClass;
            // get functions
            var members = cc.Members;
            // list of ints
            List <int> migrations = new List <int>();

            // iterate through functions
            foreach (CodeElement member in members)
            {
                var func = member as CodeFunction;
                if (func == null)
                {
                    continue;
                }
                // TODO: investigate use of CodeFunction
                var createIndex = member.Name == "Create";
                if (createIndex)
                {
                    migrations.Add(0);
                    continue;
                }

                var index = member.Name.IndexOf("UpdateFrom");
                if (index == -1)
                {
                    continue;
                }

                migrations.Add(Int32.Parse(member.Name.Last().ToString()));
            }
            // sort numbers, just in case
            migrations.Sort();
            // get new update number
            var update = migrations.Count == 0 ? 0 : migrations.Last() + 1;
            // create method, either update or create
            var          methodName = update == 0 ? "Create" : "UpdateFrom" + update;
            CodeFunction cf         = cc.AddFunction(methodName, vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefInt, -1, vsCMAccess.vsCMAccessPublic);
            // access new method
            TextPoint tp  = cf.GetStartPoint(vsCMPart.vsCMPartBody);
            TextPoint end = cf.GetEndPoint(vsCMPart.vsCMPartBody);
            EditPoint ep  = tp.CreateEditPoint();

            // delete auto generated code
            ep.Delete(end);

            var partName = _viewModel.PartName.Trim();

            // add part bits and bobs
            if (_viewModel.Attachable)
            {
                ep.Insert(String.Format(@"ContentDefinitionManager.AlterPartDefinition(""{0}"", builder => builder", partName) + Environment.NewLine);
                // make attachable
                ep.Insert(".Attachable()");
                // add description
                if (!String.IsNullOrEmpty(_viewModel.HelpText))
                {
                    ep.Insert(Environment.NewLine + @".WithDescription(""" + _viewModel.HelpText + @""")");
                }
                ep.Insert(");" + Environment.NewLine + Environment.NewLine);
            }

            // add record migration
            if (_viewModel.Storage.Contains("Record Storage"))
            {
                ep.Insert(String.Format(@"SchemaBuilder.CreateTable(""{0}Record"", table => table", partName) +
                          Environment.NewLine +
                          ".ContentPartRecord()");
                foreach (var prop in properties)
                {
                    ep.Insert(Environment.NewLine + ".Column<" + prop.Value + @">(""" + prop.Key + @""")");
                }
                ep.Insert(");" + Environment.NewLine + Environment.NewLine);
            }

            // create widget
            if (_viewModel.CreateWidget)
            {
                ep.Insert(String.Format(@"ContentDefinitionManager.AlterTypeDefinition(""{0}"", widget => widget", (_viewModel.WidgetName ?? partName + "Widget").Trim()) +
                          Environment.NewLine +
                          @".WithPart(""CommonPart"")" +
                          Environment.NewLine +
                          @".WithPart(""WidgetPart"")" +
                          Environment.NewLine +
                          @".WithPart(""" + partName + @""")" +
                          Environment.NewLine +
                          @".WithSetting(""Stereotype"", ""Widget"")"
                          );
                ep.Insert(");" + Environment.NewLine + Environment.NewLine + Environment.NewLine);
            }

            var returnVal = update + 1;

            ep.Insert("return" + returnVal);

            // format document
            tp.CreateEditPoint().SmartFormat(ep);
        }
Ejemplo n.º 10
0
            public ICheckCPPoint CheckCursorPos()
            {
                ICheckCPPoint checkPnt  = null;
                Document      activeDoc = ChartPoints.Globals.dte.ActiveDocument;
                string        projName  = activeDoc.ProjectItem.ContainingProject.Name;
                TextSelection sel       = (TextSelection)activeDoc.Selection;
                TextPoint     caretPnt  = (TextPoint)sel.ActivePoint;
                VCCodeElement targetClassElem;

                for (;;)
                {
                    // checks if we are in text document
                    if (activeDoc == null)
                    {
                        break;
                    }
                    var textDoc = activeDoc.Object() as TextDocument;
                    if (textDoc == null)
                    {
                        break;
                    }
                    // we work only with project items
                    ProjectItem projItem = activeDoc.ProjectItem;
                    if (projItem == null)
                    {
                        break;
                    }
                    // only c++ items
                    FileCodeModel fcModel = projItem.FileCodeModel;
                    if (fcModel == null)
                    {
                        break;
                    }
                    if (fcModel.Language != CodeModelLanguageConstants.vsCMLanguageVC)
                    {
                        break;
                    }
                    vcCodeModel.Synchronize();// !!! MOVE TO METHOD ???
                    // chartpoint allowed only in class methods
                    CodeElement elem = fcModel.CodeElementFromPoint(caretPnt, vsCMElement.vsCMElementFunction);
                    if (elem == null)
                    {
                        break;
                    }
                    if (elem.Kind != vsCMElement.vsCMElementFunction)
                    {
                        break;
                    }
                    VCCodeFunction targetFunc = (VCCodeFunction)elem;
                    if (targetFunc == null)
                    {
                        break;
                    }
                    // check that we are in method definition (not declaration) in case of declaration in one file & definition in other
                    if (!targetFunc.File.Equals(activeDoc.FullName, StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }
                    // we are working only with class methods not global function
                    targetFunc.CodeModel.Synchronize();
                    targetFunc.CodeModel.SynchronizeFiles();
                    foreach (CodeElement _cl in targetFunc.CodeModel.Classes)
                    {
                        foreach (CodeElement _f in _cl.Children)
                        {
                            if (targetFunc.FullName.Equals(_f.FullName, StringComparison.OrdinalIgnoreCase))
                            {
                                targetFunc = (VCCodeFunction)_f;
                                break;
                            }
                        }
                    }
                    targetClassElem = (VCCodeElement)targetFunc.Parent;
                    if (targetClassElem == null)
                    {
                        break;
                    }
                    if (targetClassElem.Kind != vsCMElement.vsCMElementClass)
                    {
                        targetClassElem = null;
                        break;
                    }
                    VCCodeClass ownerClass = (VCCodeClass)targetClassElem;

                    TextPoint startFuncBody = targetFunc.StartPointOf[vsCMPart.vsCMPartBody, vsCMWhere.vsCMWhereDefinition];
                    TextPoint endFuncBody   = targetFunc.EndPointOf[vsCMPart.vsCMPartBody, vsCMWhere.vsCMWhereDefinition];
                    EditPoint startPnt      = startFuncBody.CreateEditPoint();
                    EditPoint endPnt        = endFuncBody.CreateEditPoint();
                    startPnt.FindPattern("{", (int)vsFindOptions.vsFindOptionsBackwards);
                    endPnt.FindPattern("}");
                    if ((caretPnt.Line > startPnt.Line && caretPnt.Line < endPnt.Line) ||
                        (caretPnt.Line == startPnt.Line && caretPnt.LineCharOffset >= startPnt.LineCharOffset) ||
                        (caretPnt.Line == endPnt.Line && caretPnt.LineCharOffset <= endPnt.LineCharOffset))
                    {
                        // Oh, oh you're in the body, now.. (c)
                        int linePos = (caretPnt.Line == startPnt.Line ? startPnt.LineCharOffset + 1 : 1 /*0*/);
                        checkPnt = new CheckCPPoint(ownerClass, projName, activeDoc.Name, System.IO.Path.GetFullPath(activeDoc.FullName).ToLower(), caretPnt.Line, linePos);

                        return(checkPnt);
                    }
                    break;
                }

                return(checkPnt);
            }
Ejemplo n.º 11
0
        public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeProperty originalClassCodeProperty)
        {
            vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction;
            object       functionType = null;

            functionKind = vsCMFunction.vsCMFunctionFunction;
            functionType = vsCMTypeRef.vsCMTypeRefVoid;

            //functionKind = vsCMFunction.vsCMFunctionSub;
            //functionType = vsCMTypeRef.vsCMTypeRefVoid;

            string nextAvailableName = originalClassCodeProperty.Name;

            if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass,
                                                                    nextAvailableName))
            {
                nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject);
            }

            CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction(
                nextAvailableName,
                functionKind,
                functionType,
                -1,
                originalClassCodeProperty.Access,
                -1);

            unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1);

            try{
                unitTestCodeFunction.Comment    = originalClassCodeProperty.Comment;
                unitTestCodeFunction.DocComment = originalClassCodeProperty.DocComment;
            }
            catch (Exception ex) {
                Logger.LogException(ex);
                //ignore
            }

            TextPoint bodyStartingPoint =
                unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint();

            //Stop here if not read-write type property now...

            if (originalClassCodeProperty.Setter == null)
            {
                boydEditPoint = bodyStartingPoint.CreateEditPoint();

                boydEditPoint.Insert(StringHelper.GetTabString() + "// Property is not read-write please add your own code here." + Environment.NewLine);
                //boydEditPoint.Insert(StringHelper.GetTabString() + "' Property is not read-write please add your own code here." + Environment.NewLine);

                return(unitTestCodeFunction);
            }

            string tvFunctionCallTemplate = string.Empty; // "iv{0}Type.{1} = default({2});";

            tvFunctionCallTemplate = "iv{0}Type.{1} = default({2});" + Environment.NewLine;
            // tvFunctionCallTemplate = "iv{0}Type.{1} = New {2}()" + Environment.NewLine;

            string tvFunctionCall = tvFunctionCallTemplate;

            CodeTypeRef tvPropertyType = originalClassCodeProperty.Type;

            string tvPropertyTypeAsString = tvPropertyType.AsString;

            tvFunctionCall = string.Format(tvFunctionCall, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString);

            bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            boydEditPoint = bodyStartingPoint.CreateEditPoint();

            //FIX ME (tabing)
            boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine);

            //FIX ME (tabbing)
            string tvTempString = string.Empty; // "iv{0}Type.{1}, default({2})";

            tvTempString = "iv{0}Type.{1}, default({2})";
            // tvTempString = "iv{0}Type.{1}, New {2}()";

            tvTempString = string.Format(tvTempString, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString);

            boydEditPoint.Insert(Environment.NewLine);
            boydEditPoint.Insert("\t\t\t// TODO: Update Assert to meet test needs" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\t//Assert.AreEqual(" + tvTempString + ");" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\t" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\tthrow new Exception(\"Not Implemented\");" + Environment.NewLine);

            return(unitTestCodeFunction);
        }
Ejemplo n.º 12
0
        public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeFunction originalClassCodeFuntion)
        {
            vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction;
            object       functionType = null;

            functionKind = vsCMFunction.vsCMFunctionFunction;
            functionType = vsCMTypeRef.vsCMTypeRefVoid;

            /*
             * functionKind = vsCMFunction.vsCMFunctionSub;
             *    functionType = vsCMTypeRef.vsCMTypeRefVoid;
             */

            string nextAvailableName = originalClassCodeFuntion.Name;

            if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass,
                                                                    nextAvailableName))
            {
                nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject);
            }

            CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction(
                nextAvailableName,
                functionKind,
                functionType,
                -1,
                originalClassCodeFuntion.Access,
                -1);

            bool tvIsStatic = originalClassCodeFuntion.IsShared;

            //add the NUnit attribute to the function
            unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1);

            try{
                unitTestCodeFunction.Comment    = originalClassCodeFuntion.Comment;
                unitTestCodeFunction.DocComment = originalClassCodeFuntion.DocComment;
            }
            catch (Exception ex) {
                //ignore, for some reason the doc throws in vb
                Logger.LogException(ex);
            }

            string tvFunctionCallTemplate   = string.Empty; //"iv{0}Type.{1}(";
            string tvFunctionReturnTemplate = string.Empty; //"{0} iv{1}Return = ";

            tvFunctionCallTemplate = "iv{0}Type.{1}(";

            if (tvIsStatic)
            {
                tvFunctionCallTemplate = "{0}.{1}(";
            }

            tvFunctionReturnTemplate = "{0} iv{1}Return = ";
            //tvFunctionReturnTemplate = "Dim iv{1}Return As {0} = ";

            string tvTempParameterList = string.Empty;
            string tvFunctionCall      = tvFunctionCallTemplate;
            string tvFunctionReturn    = tvFunctionReturnTemplate;


            if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor"))
            {
                CodeElements tvParameters = originalClassCodeFuntion.Parameters;

                foreach (CodeElement tvCodeElement in tvParameters)
                {
                    if (!tvFunctionCall.Equals(tvFunctionCallTemplate))
                    {
                        tvFunctionCall += ", ";
                    }

                    CodeParameter2 tvCodeParameter = (CodeParameter2)tvCodeElement;

                    string parameterName = tvCodeParameter.Name;

                    CodeTypeRef tvParameterType = tvCodeParameter.Type;

                    vsCMParameterKind tvParameterKind = tvCodeParameter.ParameterKind;

                    string parameterTypeAsString = tvParameterType.AsString;

                    tvTempParameterList += parameterTypeAsString + " " + parameterName + " = default(" + parameterTypeAsString + ");" + Environment.NewLine + StringHelper.GetTabString();
                    //tvTempParameterList += "Dim " + parameterName + " As " + parameterTypeAsString + " = New " + parameterTypeAsString + "()" + Environment.NewLine + StringHelper.GetTabString();

                    if (tvParameterKind == vsCMParameterKind.vsCMParameterKindRef)
                    {
                        tvFunctionCall += "ref " + parameterName;
                        // tvFunctionCall += parameterName;
                    }
                    else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindOut)
                    {
                        tvFunctionCall += "out " + parameterName;
                        // tvFunctionCall += parameterName
                    }
                    else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindIn)
                    {
                        tvFunctionCall += "in " + parameterName;
                        //tvFunctionCall += parameterName;
                    }
                    else
                    {
                        tvFunctionCall += parameterName;
                    }
                }

                tvFunctionCall = string.Format(tvFunctionCall + ");" + Environment.NewLine, ((CodeClass)originalClassCodeFuntion.Parent).Name, originalClassCodeFuntion.Name);
                //tvFunctionCall = string.Format(tvFunctionCall + ")" + Environment.NewLine, ((CodeClass)originalClassCodeFuntion.Parent).Name, originalClassCodeFuntion.Name);
            }

            if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid)
            {
                tvFunctionReturn = string.Format(tvFunctionReturn, originalClassCodeFuntion.Type.AsString, originalClassCodeFuntion.Name);
                tvFunctionCall   = tvFunctionReturn + tvFunctionCall;
            }

            TextPoint bodyStartingPoint =
                unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint();

            if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor"))
            {
                boydEditPoint.Insert("\t\t\t// TODO: Update variable/s' defaults to meet test needs" + Environment.NewLine);
                //boydEditPoint.Insert("\t\t\t' TODO: Update variable/s' defaults to meet test needs" + Environment.NewLine);


                boydEditPoint.Insert(StringHelper.GetTabString() + tvTempParameterList + Environment.NewLine);
                boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine);
            }

            if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid)
            {
                string stringHolder = "iv{0}Return";
                stringHolder = string.Format(stringHolder, originalClassCodeFuntion.Name);
                //FIX ME (tabing)
                //boydEditPoint.Insert(string.Format("\t\t\tAssert.AreEqual({0}, default({1}));\r\n", stringHolder, originalClassCodeFuntion.Type.AsString));
            }

            boydEditPoint.Insert(Environment.NewLine);
            boydEditPoint.Insert("\t\t\t//TODO: Update Assert to meet test needs" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\t//Assert.AreEqual( , );" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\t" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\tthrow new Exception(\"Not Implemented\");" + Environment.NewLine);

            return(unitTestCodeFunction);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Explores given method using VB lookuper
        /// </summary>
        protected override void Explore(AbstractBatchCommand parentCommand, CodeFunction2 codeFunction, CodeNamespace parentNamespace, CodeElement2 codeClassOrStruct, Predicate <CodeElement> exploreable, bool isLocalizableFalse)
        {
            if (codeFunction.MustImplement)
            {
                return;                             // method must not be abstract
            }
            if (!exploreable(codeFunction as CodeElement))
            {
                return;                                            // predicate must eval to true
            }
            // there is no way of knowing whether a function is not declared 'extern'. In that case, following will throw an exception.
            string functionText = null;

            try {
                functionText = codeFunction.GetText(); // get method text
            } catch (Exception) { }
            if (string.IsNullOrEmpty(functionText))
            {
                return;
            }

            TextPoint startPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            // is method decorated with Localizable(false)
            bool functionLocalizableFalse = (codeFunction as CodeElement).HasLocalizableFalseAttribute();

            var list = parentCommand.LookupInVB(functionText, startPoint, parentNamespace, codeClassOrStruct, codeFunction.Name, null, isLocalizableFalse || functionLocalizableFalse);

            // add context to result items (surounding few lines of code)
            EditPoint2 editPoint = (EditPoint2)startPoint.CreateEditPoint();

            foreach (AbstractResultItem item in list)
            {
                item.CodeModelSource = codeFunction;
                AddContextToItem(item, editPoint);
            }

            // read optional arguments initializers (just to show them - they cannot be moved)
            TextPoint headerStartPoint = null;

            try {
                headerStartPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader);
            } catch (Exception) { }
            if (headerStartPoint == null)
            {
                return;
            }

            string headerText = codeFunction.GetHeaderText();

            // search method header
            var headerList = parentCommand.LookupInVB(headerText, headerStartPoint, parentNamespace, codeClassOrStruct, codeFunction.Name, null, isLocalizableFalse || functionLocalizableFalse);

            // add to list
            editPoint = (EditPoint2)startPoint.CreateEditPoint();
            foreach (AbstractResultItem item in headerList)
            {
                item.IsConst         = true;
                item.CodeModelSource = codeFunction;
                AddContextToItem(item, editPoint);
            }
        }