Esempio n. 1
0
        static GeometryPoint GetGeometryPointFrom(SourcePoint srcPt, double val, Rect rect, double timeInPoint, TimeSpan leftTime, TimeSpan time)
        {
            Point         curPosPoint = new Point(rect.Location.X + ToolFunctions.GetDxByTime(time, timeInPoint, leftTime), val);
            GeometryPoint curPoint    = new GeometryPoint(curPosPoint, srcPt);

            return(curPoint);
        }
        private void BlockPainterPlugIn_DecorateLanguageElement(object sender, DecorateLanguageElementEventArgs args)
        {
            DelimiterCapableBlock block = args.LanguageElement as DelimiterCapableBlock;

            if (block != null && block.HasDelimitedBlock && !_processedLines.Contains(block.EndLine))
            {
                IList <DelimiterCapableBlock> blocksOnLine    = GetBlocksOnLine(block);
                DelimiterCapableBlock         lastBlockOnLine = blocksOnLine[blocksOnLine.Count - 1];
                SourcePoint startPointToPaint = new SourcePoint(block.EndLine, lastBlockOnLine.EndOffset + 1);

                for (int i = 0; i < blocksOnLine.Count; i++)
                {
                    block = blocksOnLine[i];

                    IParameter             blockTypeNameParameter = new Ninject.Parameters.Parameter(ParameterNames.BlockTypeName, block.GetType().Name, true);
                    IBlockPaintingStrategy strategy = _kernel.Get <IBlockPaintingStrategy>(blockTypeNameParameter);

                    if (i == 0)
                    {
                        startPointToPaint = strategy.PaintPrefix(block, args, startPointToPaint);
                    }

                    startPointToPaint = strategy.PaintBlock(block, args, startPointToPaint, blocksOnLine.Count > 1);
                }

                _processedLines.Add(block.EndLine);
            }
        }
        private void BlockPainterPlugIn_DecorateLanguageElement(object sender, DecorateLanguageElementEventArgs args)
        {
            DelimiterCapableBlock block = args.LanguageElement as DelimiterCapableBlock;

            if (block != null && block.HasDelimitedBlock && !_processedLines.Contains(block.EndLine))
            {
                IList<DelimiterCapableBlock> blocksOnLine = GetBlocksOnLine(block);
                DelimiterCapableBlock lastBlockOnLine = blocksOnLine[blocksOnLine.Count - 1];
                SourcePoint startPointToPaint = new SourcePoint(block.EndLine, lastBlockOnLine.EndOffset + 1);
                
                for (int i = 0; i < blocksOnLine.Count; i++)
                {
                    block = blocksOnLine[i];

                    IParameter blockTypeNameParameter = new Ninject.Parameters.Parameter(ParameterNames.BlockTypeName, block.GetType().Name, true);
                    IBlockPaintingStrategy strategy = _kernel.Get<IBlockPaintingStrategy>(blockTypeNameParameter);

                    if (i == 0)
                    {
                        startPointToPaint = strategy.PaintPrefix(block, args, startPointToPaint);
                    }

                    startPointToPaint = strategy.PaintBlock(block, args, startPointToPaint, blocksOnLine.Count > 1);
                }

                _processedLines.Add(block.EndLine);
            }
        }
            public IEnumerable<StyleCopCodeIssue> GetCodeIssues(
                ISourceCode sourceCode, 
                Func<ElementTypeFilter, IEnumerable<IElement>> enumerate, 
                Violation violation, 
                CsElement csElement)
            {
                SourcePoint? startPoint = null;
                SourcePoint? endPoint = null;
                foreach (var token in from token in csElement.ElementTokens
                                      where token.LineNumber == violation.Line && token.CsTokenType != CsTokenType.WhiteSpace
                                      select token)
                {
                    if (token.CsTokenType == CsTokenType.Namespace)
                    {
                        startPoint = endPoint = new SourcePoint(token.Location.StartPoint.LineNumber, token.Location.StartPoint.IndexOnLine + 1);
                    }
                    else if (token.CsTokenType == CsTokenType.OpenCurlyBracket || token.CsTokenType == CsTokenType.EndOfLine)
                    {
                        if (startPoint != null)
                        {
                            var sourceRange = new SourceRange(startPoint.Value, endPoint.Value);
                            yield return new StyleCopCodeIssue(CodeIssueType.CodeSmell, sourceRange);
                        }

                        yield break;
                    }
                    else if (startPoint != null)
                    {
                        endPoint = new SourcePoint(token.Location.EndPoint.LineNumber, token.Location.EndPoint.IndexOnLine + 2);
                    }
                }
            }
Esempio n. 5
0
        /// <summary>
        /// Selects the current member.
        /// </summary>
        /// <param name="caret">The caret.</param>
        /// <param name="textDocument">The text document.</param>
        /// <returns></returns>
        public static bool SelectCurrentMember(CaretServices caret, TextDocument textDocument)
        {
            bool result = false;

            if (caret == null || textDocument == null)
            {
                return(result);
            }

            if (caret.InsideCode == true)
            {
                SourcePoint     sourcePoint = caret.SourcePoint;
                LanguageElement element     = textDocument.GetNodeAt(sourcePoint);

                if (element.CanBeDocumented == false ||
                    element.ElementType == LanguageElementType.EnumElement)
                {
                    element = element.GetParentElementThatCanBeDocumented();
                }

                SourceRange range = element.GetFullBlockRange(BlockElements.AllSupportElements);
                CodeRush.Selection.SelectRange(range);

                result = true;
            }

            return(result);
        }
 public static CaretVector From(SourcePoint target, SourcePoint source, ElementPosition position)
 {
     CaretVector caretVector = new CaretVector(position);
     caretVector.LineDelta = target.Line - source.Line;
     caretVector.OffsetDelta = target.Offset - source.Offset;
     return caretVector;
 }
Esempio n. 7
0
        private static TagPrefix FromName(string name, SourcePoint start)
        {
            int colonIndex = name.IndexOf(":");

            if (colonIndex <= 0)
            {
                return(null);
            }

            SourceRange tagPrefixRange = SourceRange.Empty;
            string      tagPrefixName  = name.Substring(0, colonIndex);

            if (tagPrefixName == "xmlns")
            {
                string      xmlnsName      = name.Substring(colonIndex + 1);
                SourcePoint xmlnsNameStart = new SourcePoint(start.Line, start.Offset + tagPrefixName.Length + 1);
                SourcePoint end            = new SourcePoint(xmlnsNameStart.Line, xmlnsNameStart.Offset + xmlnsName.Length);
                tagPrefixRange = new SourceRange(xmlnsNameStart, end);
                tagPrefixName  = xmlnsName;
            }
            else
            {
                SourcePoint end = new SourcePoint(start.Line, start.Offset + tagPrefixName.Length);
                tagPrefixRange = new SourceRange(start, end);
            }
            return(new TagPrefix()
            {
                Name = tagPrefixName, Range = tagPrefixRange
            });
        }
 public void AddNewImport(SourcePoint start, string namespaceName, SourceFile sourceFile, bool isLast)
 {
     string newImportCall = CodeRush.Language.GenerateElement(new NamespaceReference(namespaceName), sourceFile.Project.Language);
     if (isLast && newImportCall.EndsWith(Environment.NewLine))		// Remove cr/lf from last entry.
         newImportCall = newImportCall.Remove(newImportCall.Length - Environment.NewLine.Length);
     _NewImportCalls.Add(new FileChange(sourceFile.Name, start, newImportCall));
 }
            public IEnumerable <StyleCopCodeIssue> GetCodeIssues(
                ISourceCode sourceCode,
                Func <ElementTypeFilter, IEnumerable <IElement> > enumerate,
                Violation violation,
                CsElement csElement)
            {
                SourcePoint?startPoint = null;
                SourcePoint?endPoint   = null;

                foreach (var token in from token in csElement.ElementTokens
                         where token.LineNumber == violation.Line && token.CsTokenType != CsTokenType.WhiteSpace
                         select token)
                {
                    if (token.CsTokenType == CsTokenType.Namespace)
                    {
                        startPoint = endPoint = new SourcePoint(token.Location.StartPoint.LineNumber, token.Location.StartPoint.IndexOnLine + 1);
                    }
                    else if (token.CsTokenType == CsTokenType.OpenCurlyBracket || token.CsTokenType == CsTokenType.EndOfLine)
                    {
                        if (startPoint != null)
                        {
                            var sourceRange = new SourceRange(startPoint.Value, endPoint.Value);
                            yield return(new StyleCopCodeIssue(CodeIssueType.CodeSmell, sourceRange));
                        }

                        yield break;
                    }
                    else if (startPoint != null)
                    {
                        endPoint = new SourcePoint(token.Location.EndPoint.LineNumber, token.Location.EndPoint.IndexOnLine + 2);
                    }
                }
            }
Esempio n. 10
0
        /// <summary>
        /// Checks for connections to ther contours and adds them to the model.
        /// </summary>
        /// <param name="model">The model to add the connections to.</param>
        /// <param name="args">The line arguments that might specify connections.</param>
        /// <param name="name">The name of the contour these args correspond to.</param>
        /// <param name="sourcePoint">Whether to add start or finish connections.</param>
        private static void GetConnections(Model model, string[] args, string name, SourcePoint sourcePoint)
        {
            List <int> indicies;
            string     flag = (sourcePoint == SourcePoint.Start) ? ARG_START : ARG_FINISH;

            if (args != null && LineOptionParser.GetValueIndicies(args, flag, out indicies))
            {
                foreach (int index in indicies)
                {
                    string      targetName;
                    TargetPoint targetPoint;
                    float       minZ = float.MinValue;
                    float       maxZ = float.MaxValue;

                    if (GetTargetPoint(args[index], out targetPoint))
                    {
                        targetName = args[index + 1];
                    }
                    else
                    {
                        string[] range = args[index].Substring(1, args[index].Length - 2).Split(',');
                        ParseRange(range[0], ref minZ, true);
                        ParseRange(range[1], ref maxZ, false);

                        GetTargetPoint(args[index + 1], out targetPoint);
                        targetName = args[index + 2];
                    }

                    model.AddConnection(new Connection(name, targetName, sourcePoint, targetPoint, minZ, maxZ));
                }
            }
        }
Esempio n. 11
0
        private void AddLoggingToMethod(Method method)
        {
            System.Diagnostics.Debug.WriteLine(string.Format("StartLine: >{0}< >{1}<", method.StartLine, method.StartOffset));
            System.Diagnostics.Debug.WriteLine(string.Format("EndLine:   >{0}< >{1}<", method.EndLine, method.EndOffset));
            SourceRange methodBody = method.BlockCodeRange;
            SourcePoint startBody = methodBody.Start;
            SourcePoint endBody = methodBody.End;
            System.Diagnostics.Debug.WriteLine(string.Format("StartBody: >{0}< >{1}<", startBody.Line, startBody.Offset));
            System.Diagnostics.Debug.WriteLine(string.Format("EndBody:   >{0}< >{1}<", endBody.Line, endBody.Offset));

            SourcePoint logEntryPoint = new SourcePoint();
            SourcePoint logExitPoint = new SourcePoint();

            logEntryPoint.Line = startBody.Line;
            logEntryPoint.Offset = 1;

            logExitPoint.Line = method.EndLine - 1;
            logExitPoint.Offset = endBody.Offset;

            try
            {
                SourceFile activeFile = CodeRush.Source.ActiveSourceFile;

                string LOGENTRY = @"
            #If TRACE
            Dim startTicks As Long = Log.Trace(""Enter"", LOG_APPNAME, BASE_ERRORNUMBER + 0)
            #End If

            ";

                string LOGEXIT = @"
            #If TRACE
            Log.Trace(""Exit"", LOG_APPNAME, BASE_ERRORNUMBER + 0, startTicks)
            #End If
            ";

                //FileChangeCollection fileChangeCollection = new FileChangeCollection();

                FileChange logExitFileChange = new FileChange(activeFile.Name, logExitPoint, LOGEXIT);
                fileChangeCollection.Add(logExitFileChange);

                //method.ParseOnDemandIfNeeded();

                //CodeRush.Source.ParseIfTextChanged();

                FileChange logEntryFileChange = new FileChange(activeFile.Name, logEntryPoint, LOGENTRY);
                fileChangeCollection.Add(logEntryFileChange);

                //CodeRush.Source.ParseIfTextChanged();
                // TODO(crhodes):
                // Need to figure out how to force a reparse.

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
        private FileSourceRangeCollection extractHqlNamedQuery(LanguageElement hqlQueryElement)
        {
            string hqlQuery = (hqlQueryElement as IPrimitiveExpression).Value.ToString();

            SourceFile namedQueriesXmlFile = getNamedQueriesXmlFile(hqlQueryElement.Project as ProjectElement);

            if (namedQueriesXmlFile != null)
            {
                string tempQueryName = getTempQueryName();

                if (!namedQueriesXmlFile.IsOpened)
                {
                    CodeRush.File.Activate(namedQueriesXmlFile.FilePath);
                }

                TextDocument namedQueriesXmlDocument = namedQueriesXmlFile.Document as TextDocument;
                TextDocument currentDocument         = hqlQueryElement.Document as TextDocument;
                string       currentFilePath         = hqlQueryElement.FileNode.FilePath;
                SourceFile   currentSourceFile       = hqlQueryElement.FileNode;

                string xmlContent = getXmlContent(hqlQuery, tempQueryName);

                insertXmlContentInNamedQueriesFile(namedQueriesXmlFile, xmlContent);

                string quotedTempQueryName = String.Format("\"{0}\"", tempQueryName);

                currentDocument.Replace(hqlQueryElement.Range, quotedTempQueryName, string.Empty, true);
                currentDocument.ParseIfTextChanged();

                FileSourceRangeCollection rangesToLink         = new FileSourceRangeCollection();
                SourceRange queryNameElementRange              = findElementByName(currentDocument.FileNode, quotedTempQueryName).Range;
                SourceRange queryNameElementRangeWithoutQuotes = new SourceRange(
                    queryNameElementRange.Start.Line,
                    queryNameElementRange.Start.Offset + 1,
                    queryNameElementRange.End.Line,
                    queryNameElementRange.End.Offset - 1);

                rangesToLink.Add(new FileSourceRange(currentSourceFile, queryNameElementRangeWithoutQuotes));

                SourcePoint queryNameLocationInNamedQueriesXmlDocument     = namedQueriesXmlDocument.FindText(tempQueryName);
                SourceRange queryNameElementRangeInNamedQueriesXmlDocument = new SourceRange(
                    queryNameLocationInNamedQueriesXmlDocument,
                    new SourcePoint(queryNameLocationInNamedQueriesXmlDocument.Line, queryNameLocationInNamedQueriesXmlDocument.Offset + tempQueryName.Length));

                rangesToLink.Add(new FileSourceRange(namedQueriesXmlFile, queryNameElementRangeInNamedQueriesXmlDocument));

                CodeRush.File.Activate(currentFilePath);
                TextDocument.Active.SelectText(queryNameElementRangeWithoutQuotes);

                return(rangesToLink);
            }
            else
            {
                MessageBox.Show("No file for hql named queries found", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            return(null);
        }
Esempio n. 13
0
 private void AddAttribute(LanguageElement element, string AttributeName)
 {
     var Builder = new ElementBuilder();
     var Attribute = Builder.BuildAttribute(AttributeName);
     var Section = Builder.BuildAttributeSection();
     Section.AddAttribute(Attribute);
     var Code = CodeRush.CodeMod.GenerateCode(Section, false);
     SourcePoint InsertionPoint = new SourcePoint(element.Range.Start.Line, 1);
     CodeRush.Documents.ActiveTextDocument.QueueInsert(InsertionPoint, Code);
 }
        public virtual SourcePoint PaintPrefix(DelimiterCapableBlock block, DecorateLanguageElementEventArgs args, SourcePoint startPointToPaint)
        {
            SourcePoint result = startPointToPaint;
            if (Settings.Enabled && MeetsLengthRquirement(block)) 
            {
                args.AddForegroundAdornment( new BlockPrefixDocumentAdornment(startPointToPaint, Settings));

                result = startPointToPaint.OffsetPoint(0, Settings.PrefixText.Length + 1);
            }
            return result;
        }
Esempio n. 15
0
        /// <summary>
        /// Executes the "join lines" action.
        /// </summary>
        /// <param name="ea">
        /// A <see cref="DevExpress.CodeRush.Core.ExecuteEventArgs"/> that contains the event data.
        /// </param>
        /// <remarks>
        /// <para>
        /// This method provides the primary functionality for the Join Lines plugin.
        /// </para>
        /// <para>
        /// If there is no selection, the line the caret is currently on will be joined
        /// with the subsequent line.
        /// </para>
        /// <para>
        /// If there is a selection, the selected lines will be joined and the caret will
        /// be placed at the beginning of the complete joined line.
        /// </para>
        /// </remarks>
        private void actionJoinLines_Execute(DevExpress.CodeRush.Core.ExecuteEventArgs ea)
        {
            // Don't do anything if we're not available.
            if (!this.Available)
            {
                return;
            }

            // Don't do anything if we don't have an active text document.
            if (CodeRush.Documents.ActiveTextDocument == null)
            {
                Log.SendError("{0}Active text document is null.", LOG_PREFIX);
                return;
            }

            SourcePoint origLocation = CodeRush.Caret.SourcePoint;

            Log.SendMsg(ImageType.Info, "{0}Joining lines.", LOG_PREFIX);
            CodeRush.UndoStack.BeginUpdate("JoinLines");
            try
            {
                string delimiter = ea.Action.Parameters.GetString("Delimiter", "");
                if (CodeRush.TextViews.Active.Selection.Exists)
                {
                    // Join the selected lines
                    CodeRush.TextViews.Active.Selection.ExtendToWholeLines();
                    int topLine  = CodeRush.TextViews.Active.Selection.StartLine;
                    int numLines = CodeRush.TextViews.Active.Selection.EndLine - topLine;
                    if (CodeRush.TextViews.Active.Selection.EndViewColumn == 1)
                    {
                        numLines--;
                    }
                    if (numLines == 0)
                    {
                        numLines = 1;
                    }
                    for (int i = 0; i < numLines; i++)
                    {
                        ExecuteJoin(topLine, delimiter);
                    }
                    CodeRush.Caret.MoveTo(topLine, 0);
                }
                else
                {
                    // Join the current line with the next line
                    ExecuteJoin(origLocation.Line, delimiter);
                    CodeRush.Caret.MoveTo(origLocation);
                }
            }
            finally
            {
                CodeRush.UndoStack.EndUpdate();
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Deep copy constructor.
        /// </summary>
        public Connection(Connection connection)
        {
            m_sourceName = connection.SourceName;
            m_targetName = connection.TargetName;

            m_sourcePoint = connection.SourcePoint;
            m_targetPoint = connection.TargetPoint;

            m_minZ = connection.MinZ;
            m_maxZ = connection.MaxZ;
        }
Esempio n. 17
0
        /// <summary>
        /// Returns true if the specified caret position is located inside either the start or end tag of the specified HtmlElement.
        /// </summary>
        private static bool IsCaretOnPairedHtmlTag(LanguageElement element, SourcePoint caret)
        {
            DevExpress.CodeRush.StructuralParser.HtmlElement htmlElement = element as DevExpress.CodeRush.StructuralParser.HtmlElement;
            if (htmlElement == null)		// Not an HtmlElement
                return false;

            if (htmlElement.CloseTagNameRange == SourceRange.Empty)		// Not a paired Html tag.
                return false;

            return htmlElement.NameRange.Contains(caret) || htmlElement.CloseTagNameRange.Contains(caret);
        }
Esempio n. 18
0
 private SourceRange GetMethodBoxRange(DecorateLanguageElementEventArgs args, Method Method)
 {
     // Get all the lines of the method
     var Lines = args.TextDocument.GetLines(Method.StartLine, Method.EndLine - Method.StartLine);
     // determine the longest of these
     string Longest = (from line in Lines orderby line.Length descending select line).First();
     // Build and return a SourceRange around the method
     SourcePoint EndPoint = new SourcePoint(Method.EndLine, Longest.Length);
     SourcePoint StartPoint = new SourcePoint(Method.StartLine, Method.StartOffset);
     return new SourceRange(StartPoint, EndPoint);
 }
 private bool IsValidSelection(LanguageElement member, TextViewSelection selection, SourcePoint caret)
 {
     if ((member == null) || (selection == null))
     {
         return false;
     }
     if (selection.Exists)
     {
         return false;
     }
     return (member.NameRange.Contains(caret) || CodeRush.Source.GetStartWordRange(member).Contains(caret));
 }
Esempio n. 20
0
        private void targetPicker_TargetSelected(object sender, TargetSelectedEventArgs ea)
        {
            CodeRush.UndoStack.BeginUpdate("Generalize");
            //Debug.Assert(String.IsNullOrEmpty(_fullBlockText), "fooey");
            SourcePoint targetPoint = ea.Location.EndInsertionPoint;

            CodeRush.Documents.ActiveTextDocument.ExpandText(targetPoint, "\r\n" + _activeBlock.Text);
            _activeBlock.Delete();
            //CodeRush.Documents.ActiveTextDocument.ExpandText(
            //    ea.Location.InsertionPoint,_fullBlockText);
            CodeRush.UndoStack.EndUpdate();
        }
        public virtual SourcePoint PaintPrefix(DelimiterCapableBlock block, DecorateLanguageElementEventArgs args, SourcePoint startPointToPaint)
        {
            SourcePoint result = startPointToPaint;

            if (Settings.Enabled && MeetsLengthRquirement(block))
            {
                args.AddForegroundAdornment(new BlockPrefixDocumentAdornment(startPointToPaint, Settings));

                result = startPointToPaint.OffsetPoint(0, Settings.PrefixText.Length + 1);
            }
            return(result);
        }
        public void Organize(
            TextDocument txtDoc, LanguageElement activeType, bool addRegions)
        {
            typeDeclaration = activeType as TypeDeclaration;
            if (typeDeclaration == null)
            {
                return;
            }

            if (txtDoc == null)
            {
                return;
            }

            textDocument = txtDoc;

            SourcePoint cursorPosition = CodeRush.Caret.SourcePoint;

            try
            {
                Class currentClass = typeDeclaration.GetClass();
                if (currentClass == null || currentClass.Document == null)
                {
                    return;
                }

                textDocument.Lock();
                InitializeDictionary();
                //Clear out list of regions that have been deleted
                deletedRegions.Clear();
                //clean out the string builder
                codeToInsert.Remove(0, codeToInsert.Length);

                ReadCodeElements(currentClass);
                BuildCode(addRegions);

                ApplyEdits();
            }
            catch (Exception ex)
            {
                Utilities.HandleException(ex);
            }
            finally
            {
                if (cursorPosition != SourcePoint.Empty)
                {
                    CodeRush.Caret.MoveTo(cursorPosition);
                }

                textDocument.Unlock();
                textDocument.Format();
            }
        }
Esempio n. 23
0
        private void AddAttribute(LanguageElement element, string AttributeName)
        {
            var Builder   = new ElementBuilder();
            var Attribute = Builder.BuildAttribute(AttributeName);
            var Section   = Builder.BuildAttributeSection();

            Section.AddAttribute(Attribute);
            var         Code           = CodeRush.CodeMod.GenerateCode(Section, false);
            SourcePoint InsertionPoint = new SourcePoint(element.Range.Start.Line, 1);

            CodeRush.Documents.ActiveTextDocument.QueueInsert(InsertionPoint, Code);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jsonObject = SourcePoint.ReadObjectWithSourcePoints(reader, JToken.Load, out var start, out var after);

            if (resourceExplorer.IsRef(jsonObject))
            {
                // We can't do this asynchronously as the Json.NET interface is synchronous
                jsonObject = resourceExplorer.ResolveRefAsync(jsonObject, context).GetAwaiter().GetResult();
            }

            return(jsonObject as JObject);
        }
Esempio n. 25
0
    private string GetActionText(WorkflowStepInfo currentStep, WorkflowStepInfo nextStep)
    {
        string text = ResHelper.LocalizeString(nextStep.StepDisplayName);
        WorkflowTransitionInfo transition = nextStep.RelatedTransition;
        SourcePoint            def        = (transition != null) ? currentStep.GetSourcePoint(transition.TransitionSourcePointGUID) : null;

        if (!String.IsNullOrEmpty(def?.Text))
        {
            text = String.Format(ResHelper.LocalizeString(def.Text), text);
        }

        return(text);
    }
Esempio n. 26
0
 /// <summary>
 /// Sets values from UI to provided source point object.
 /// </summary>
 /// <param name="sourcePoint">Source point</param>
 private void SetValues(SourcePoint sourcePoint)
 {
     if (sourcePoint != null)
     {
         sourcePoint.Label   = txtLabel.Text;
         sourcePoint.Text    = txtText.Text;
         sourcePoint.Tooltip = txtTooltip.Text;
         if (ShowCondition && (sourcePoint.Type != SourcePointTypeEnum.SwitchDefault))
         {
             sourcePoint.Condition = cbCondition.Text;
         }
     }
 }
        public override SourcePoint PaintBlock(DelimiterCapableBlock block, DecorateLanguageElementEventArgs args, SourcePoint startPointToPaint, bool multipleBlocksOnLine)
        {
            SourcePoint result = startPointToPaint;
            if (Settings.Enabled && MeetsLengthRquirement(block))
            {
                string customMetaString = String.Format("{0} '{1}'", Settings.BlockTypeName, (block as Struct).Name);
                
                args.AddForegroundAdornment(
                    new BlockMetaDataDocumentAdornment(startPointToPaint, Settings, customMetaString));

                result.OffsetPoint(0, customMetaString.Length);
            }
            return result;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jsonObject = SourcePoint.ReadObjectWithSourcePoints(reader, JToken.Load, out SourcePoint startPoint, out SourcePoint endPoint);

            if (refResolver.IsRef(jsonObject))
            {
                // We can't do this asynchronously as the Json.NET interface is synchronous
                jsonObject = refResolver.ResolveAsync(jsonObject).GetAwaiter().GetResult();
            }

            // jsonObject["id"] = jsonObject["id"] ?? jsonObject["$id"];

            var typeName = jsonObject["$type"]?.ToString();

            if (typeName == null)
            {
                throw new ArgumentNullException(JsonConvert.SerializeObject(jsonObject));
            }

            // if IdRefResolver made a path available for the JToken, then add it to the path stack
            // this maintains the stack of paths used as the source of json data
            var found = this.sourceMap.TryGetValue(jsonObject, out var range);

            if (found)
            {
                paths.Push(range.Path);
            }

            T result = TypeFactory.Build <T>(typeName, jsonObject, serializer);

            // DeclarativeTypeLoader.LoadAsync only adds FileResource to the paths stack
            if (paths.Count > 0)
            {
                // combine the "path for the most recent JToken from IdRefResolver" or the "top root path"
                // with the line information for this particular json fragment and add it to the sourceMap
                range = new SourceRange()
                {
                    Path = paths.Peek(), StartPoint = startPoint, EndPoint = endPoint
                };
                this.sourceMap.Add(result, range);
            }

            if (found)
            {
                paths.Pop();
            }

            return(result);
        }
        public override SourcePoint PaintBlock(DelimiterCapableBlock block, DecorateLanguageElementEventArgs args, SourcePoint startPointToPaint, bool multipleBlocksOnLine)
        {
            SourcePoint result = startPointToPaint;

            if (Settings.Enabled && MeetsLengthRquirement(block))
            {
                string customMetaString = GetMethodMetaString(block as Method);

                args.AddForegroundAdornment(new BlockMetaDataDocumentAdornment(startPointToPaint, Settings, customMetaString));

                result = startPointToPaint.OffsetPoint(0, customMetaString.Length);
            }

            return(result);
        }
Esempio n. 30
0
        private SourceRange GetInsertionRange(HtmlElement element)
        {
            if (element == null)
            {
                return(SourceRange.Empty);
            }
            SourcePoint start = element.Range.Start;
            SourcePoint end   = element.Range.End;

            if (element.HasCloseTag && !(element is AspDirective))
            {
                end = element.InnerRange.Start;
            }
            return(new SourceRange(start, end));
        }
Esempio n. 31
0
        private static bool CaretInsideTextField()
        {
            TextDocument doc = CodeRush.Documents.ActiveTextDocument;

            if (doc != null)
            {
                TextField textField = doc.LastActiveField;
                if (textField != null)
                {
                    SourcePoint caretPos = CodeRush.Caret.SourcePoint;
                    return(textField.Range.Contains(caretPos));
                }
            }
            return(false);
        }
        // private static methods...
        #region AtSourcePoint
        private static TagPrefix AtSourcePoint(LanguageElement activeElement, SourcePoint sourcePoint)
        {
            if (activeElement == null)
                return null;

            IEnumerable<TagPrefix> prefixes = TagPrefix.GetAll(activeElement);

            if (prefixes == null)
                return null;

            foreach (TagPrefix prefix in prefixes)
                if (prefix.Range.Contains(sourcePoint))
                    return prefix;
            return null;
        }
Esempio n. 33
0
        /// <summary>
        /// Add a developer comment.
        /// </summary>
        /// <param name="ea"></param>
        /// <developer>Paul Mrozowski</developer>
        /// <created>08/04/2006</created>
        private void actInitials_Execute(ExecuteEventArgs ea)
        {
            TextDocument doc = TextDocument.Active;
            SourcePoint  sp  = CodeRush.Caret.SourcePoint;

            string line       = doc.GetText(sp.Line);
            string xmlDoc     = CodeRush.Language.ActiveExtension.XMLDocCommentBegin;
            bool   xmlComment = line.TrimStart().StartsWith(xmlDoc);

            if (xmlDoc == null)
            {
                xmlDoc = "///";
            }

            if (xmlComment)
            {
                doc.QueueInsert(sp, String.Format("<developer>{0}</developer>\r\n{1}{2} <created>{3:" + m_dateformat + "}</created>",
                                                  this.m_devName,
                                                  line.Substring(0, line.IndexOf(xmlDoc)),
                                                  xmlDoc,
                                                  System.DateTime.Now));
            }
            else
            {
                string commentLine = CodeRush.Language.ActiveExtension.SingleLineCommentBegin;
                if (commentLine == null)
                {
                    commentLine = "//";
                }

                string comment = "";

                if (this.m_fullName)
                {
                    comment = String.Format("{0} {1} - {2:" + m_dateformat + "} - ", commentLine, this.m_devName, System.DateTime.Now);
                }
                else
                {
                    comment = String.Format("{0} {1} - {2:" + m_dateformat + "} - ", commentLine, this.m_devInitials, System.DateTime.Now);
                }

                doc.QueueInsert(sp, comment);
                CodeRush.Caret.MoveToEndOfLine();
                CodeRush.Caret.DeleteLeftWhiteSpace();
            }

            doc.ApplyQueuedEdits("Developer Comment");
        }
Esempio n. 34
0
        private static List <TagPrefix> FromValue(string name, SourcePoint start)
        {
            string[] parts = name.Split(':');
            if (parts == null || parts.Length == 0)
            {
                return(null);
            }

            List <TagPrefix> result = new List <TagPrefix>();
            int offset = start.Offset;
            int lines  = 0;

            for (int i = 0; i < parts.Length - 1; i++)
            {
                string part = parts[i];
                if (string.IsNullOrEmpty(part))
                {
                    continue;
                }

                int    countLines        = CodeRush.StrUtil.CountLines(part);
                string tagPrefixName     = part;
                int    indexlastSplitter = part.LastIndexOfAny(new char[] { '{', ' ', '\t', '\r', '\n' });
                if (indexlastSplitter >= 0)
                {
                    int startPosition = indexlastSplitter + 1;
                    if (countLines > 1)
                    {
                        lines  += countLines - 1;
                        offset  = CodeRush.StrUtil.GetLineLength(part, countLines) + 1;
                        offset -= part.Length - startPosition;
                    }
                    else
                    {
                        offset += startPosition;
                    }
                    tagPrefixName = part.Substring(startPosition);
                }
                SourcePoint startTagPrefix = new SourcePoint(start.Line + lines, offset);
                SourcePoint endTagPrefix   = new SourcePoint(start.Line + lines, offset + tagPrefixName.Length);
                result.Add(new TagPrefix()
                {
                    Name = tagPrefixName, Range = new SourceRange(startTagPrefix, endTagPrefix)
                });
                offset += tagPrefixName.Length + 1;
            }
            return(result);
        }
        public async Task <SourcePoint> EditSourcePoint(SourcePoint sourcePoint)
        {
            try
            {
                var previousSourcePoint = await _dbContext.SourcePoints.Include(o => o.Catalog).FirstOrDefaultAsync(o => o.Id == sourcePoint.Id);

                if (previousSourcePoint != null)
                {
                    previousSourcePoint.Name               = sourcePoint.Name;
                    previousSourcePoint.Position           = sourcePoint.Position;
                    previousSourcePoint.RangeId            = sourcePoint.RangeId;
                    previousSourcePoint.Value              = sourcePoint.Value;
                    previousSourcePoint.NamePosition       = sourcePoint.NamePosition;
                    previousSourcePoint.NameRangeId        = sourcePoint.NameRangeId;
                    previousSourcePoint.PublishedHistories = (await _dbContext.PublishedHistories.Where(o => o.SourcePointId == previousSourcePoint.Id).ToArrayAsync()).OrderByDescending(o => o.PublishedDate).ToArray();
                }

                await _dbContext.SaveChangesAsync();

                await _logService.WriteLog(new LogEntity()
                {
                    LogId      = "10002",
                    Action     = Constant.ACTIONTYPE_EDIT,
                    PointType  = Constant.POINTTYPE_SOURCEPOINT,
                    ActionType = ActionTypeEnum.AuditLog,
                    Message    = $"Edit source point by {_userProfileService.GetCurrentUser().Username} Previous value: source point named: {previousSourcePoint.Name} in the location: {previousSourcePoint.Position} value: {previousSourcePoint.Value} in the excel file named: {previousSourcePoint.Catalog.FileName} " +
                                 $"Current value: source point named: {sourcePoint.Name} in the location {sourcePoint.Position} value: {sourcePoint.Value} in the excel file name: {previousSourcePoint.Catalog.FileName}"
                });

                return(previousSourcePoint);
            }
            catch (Exception ex)
            {
                var logEntity = new LogEntity()
                {
                    LogId      = "10008",
                    Action     = Constant.ACTIONTYPE_EDIT,
                    ActionType = ActionTypeEnum.ErrorLog,
                    PointType  = Constant.POINTTYPE_SOURCEPOINT,
                    Message    = ".Net Error",
                    Detail     = ex.ToString()
                };
                logEntity.Subject = $"{logEntity.LogId} - {logEntity.Action} - {logEntity.PointType} - Error";
                await _logService.WriteLog(logEntity);

                throw ex;
            }
        }
    /// <summary>
    /// Initializes workflow step edit menu.
    /// </summary>
    protected void InitalizeMenu(SourcePoint sourcePoint, int workflowStepId)
    {
        string[,] tabs = new string[2, 4];
        tabs[0, 0] = GetString("general.general");
        tabs[0, 1] = String.Format("SetHelpTopic('helpTopic', '{0}');", CurrentWorkflow.IsAutomation ? "process_step_case" : "workflow_step_case");
        tabs[0, 2] = String.Format("General.aspx?workflowStepId={0}&sourcepointguid={1}", workflowStepId, sourcePoint.Guid);

        if (sourcePoint.Type != SourcePointTypeEnum.Timeout)
        {
            tabs[1, 0] = GetString("general.security");
            tabs[1, 1] = String.Format("SetHelpTopic('helpTopic', '{0}');", CurrentWorkflow.IsAutomation ? "process_step_case_security" : "workflow_step_case_security");
            tabs[1, 2] = String.Format("Security.aspx?workflowStepId={0}&sourcepointguid={1}", workflowStepId, sourcePoint.Guid);
        }
        CurrentMaster.Tabs.UrlTarget = "wfSourcePointContent";
        CurrentMaster.Tabs.Tabs = tabs;
    }
Esempio n. 37
0
    private void AddItem(SourcePoint sp, List <WorkflowTransitionInfo> connections)
    {
        string label = String.Format(GetString("wf.sourcepoint.label"), sp.Label);
        WorkflowTransitionInfo conn = connections.FirstOrDefault(i => i.TransitionSourcePointGUID == sp.Guid);

        if (conn != null)
        {
            WorkflowStepInfo target = WorkflowStepInfoProvider.GetWorkflowStepInfo(conn.TransitionEndStepID);
            if (target != null)
            {
                label = String.Format("{0} {1}", label, string.Format(GetString("wf.sourcepoint.step"), target.StepDisplayName));
            }
        }

        ddlSourcePoints.Items.Add(new ListItem(ResHelper.LocalizeString(label), sp.Guid.ToString()));
    }
Esempio n. 38
0
    /// <summary>
    /// Initializes workflow step edit menu.
    /// </summary>
    protected void InitalizeMenu(SourcePoint sourcePoint, int workflowStepId)
    {
        string[,] tabs = new string[2, 4];
        tabs[0, 0]     = GetString("general.general");
        tabs[0, 1]     = String.Format("SetHelpTopic('helpTopic', '{0}');", CurrentWorkflow.IsAutomation ? "process_step_case" : "workflow_step_case");
        tabs[0, 2]     = String.Format("General.aspx?workflowStepId={0}&sourcepointguid={1}", workflowStepId, sourcePoint.Guid);

        if (sourcePoint.Type != SourcePointTypeEnum.Timeout)
        {
            tabs[1, 0] = GetString("general.security");
            tabs[1, 1] = String.Format("SetHelpTopic('helpTopic', '{0}');", CurrentWorkflow.IsAutomation ? "process_step_case_security" : "workflow_step_case_security");
            tabs[1, 2] = String.Format("Security.aspx?workflowStepId={0}&sourcepointguid={1}", workflowStepId, sourcePoint.Guid);
        }
        CurrentMaster.Tabs.UrlTarget = "wfSourcePointContent";
        CurrentMaster.Tabs.Tabs      = tabs;
    }
        public override SourcePoint PaintBlock(DelimiterCapableBlock block, DecorateLanguageElementEventArgs args, SourcePoint startPointToPaint, bool multipleBlocksOnLine)
        {
            SourcePoint result = startPointToPaint;
            if (Settings.Enabled && MeetsLengthRquirement(block))
            {
                StringBuilder customMetaBuilder = new StringBuilder();
                customMetaBuilder.Append(String.Format("{0} '{1}'", Settings.BlockTypeName, (block as Class).Name));
                GenericBlock.AppendGenericTypes(block as AccessSpecifiedElement, customMetaBuilder);
                GenericBlock.AppendGenericTemplate(block as AccessSpecifiedElement, customMetaBuilder);

                args.AddForegroundAdornment(
                    new BlockMetaDataDocumentAdornment(startPointToPaint, Settings, customMetaBuilder.ToString()));

                result = startPointToPaint.OffsetPoint(0, customMetaBuilder.Length);
            }
            return result;
        }
Esempio n. 40
0
        public override SourcePoint PaintBlock(DelimiterCapableBlock block, DecorateLanguageElementEventArgs args, SourcePoint startPointToPaint, bool multipleBlocksOnLine)
        {
            SourcePoint result = startPointToPaint;

            if (Settings.Enabled && MeetsLengthRquirement(block))
            {
                StringBuilder customMetaBuilder = new StringBuilder();
                customMetaBuilder.Append(String.Format("{0} '{1}'", Settings.BlockTypeName, (block as Class).Name));
                GenericBlock.AppendGenericTypes(block as AccessSpecifiedElement, customMetaBuilder);
                GenericBlock.AppendGenericTemplate(block as AccessSpecifiedElement, customMetaBuilder);

                args.AddForegroundAdornment(
                    new BlockMetaDataDocumentAdornment(startPointToPaint, Settings, customMetaBuilder.ToString()));

                result = startPointToPaint.OffsetPoint(0, customMetaBuilder.Length);
            }
            return(result);
        }
Esempio n. 41
0
    private void GatherSource()
    {
        RaycastHit[] hits;
        int          layerMask1     = 1 << 10;
        int          layerMask2     = 1 << 8;
        int          finalLayerMask = layerMask1 | layerMask2;

        hits = Physics.SphereCastAll(transform.position, 3f, transform.forward, 1f, finalLayerMask);
        foreach (RaycastHit rh in hits)
        {
            if (rh.collider.gameObject.GetComponent <SourcePoint>())
            {
                SourcePoint sP = rh.collider.gameObject.GetComponent <SourcePoint>();
                sP.objectToChase = gameObject;
                sP.movementSpeed = 20f;
            }
        }
    }
        private Point GetCaretPositionScreenPoint(bool newLine)
        {
            SourcePoint point2;
            SourcePoint active = CodeRush.Caret.SourcePoint;;

            if (active == null)
            {
                return(Point.Empty);
            }
            if (newLine)
            {
                point2 = new SourcePoint(active.Line + 1, active.Offset);
            }
            else
            {
                point2 = new SourcePoint(active.Line, active.Offset);
            }
            return(CodeRush.TextViews.Active.ToScreenPoint(CodeRush.TextViews.Active.GetPoint(point2)));
        }
Esempio n. 43
0
    /// <summary>
    /// Sets values from UI to provided source point object.
    /// </summary>
    /// <param name="sourcePoint">Source point</param>
    private void SetValues(SourcePoint sourcePoint)
    {
        if (sourcePoint != null)
        {
            sourcePoint.Label   = txtLabel.Text;
            sourcePoint.Text    = txtText.Text;
            sourcePoint.Tooltip = txtTooltip.Text;

            if (ShowCondition && (sourcePoint.Type != SourcePointTypeEnum.SwitchDefault))
            {
                sourcePoint.Condition = cbCondition.Text;
            }

            if (CurrentStepInfo != null && IsRejectPlaceholderVisible())
            {
                CurrentStepInfo.SetValue("StepAllowReject", chkStepAllowReject.Checked);
            }
        }
    }
Esempio n. 44
0
    /// <summary>
    /// Saves data of edited source point from controls to edited object.
    /// </summary>
    /// <param name="validateData">Indicates whether form data should be validated prior to save</param>
    public void SaveData(bool validateData)
    {
        if (Visible && !StopProcessing)
        {
            if (!validateData || ValidateData())
            {
                var graphName = QueryHelper.GetString("graph", String.Empty);

                if (CurrentSourcePoint == null)
                {
                    // Create new source point
                    SourcePoint sp = WorkflowHelper.CreateSourcePoint(CurrentWorkflow.WorkflowType, CurrentStepInfo.StepType);
                    SetValues(sp);

                    // AddSourcePoint saves the workflow step to database
                    CurrentStepInfo.AddSourcePoint(sp);
                    SourcePointGuid = sp.Guid;
                    if (String.IsNullOrEmpty(AfterCreateRedirectURL))
                    {
                        ShowChangesSaved();
                    }
                    else
                    {
                        var queryString = $"?workflowstepid={CurrentStepInfo.StepID}&sourcepointGuid={SourcePointGuid}&graph={graphName}&saved=1";
                        URLHelper.Redirect(UrlResolver.ResolveUrl(URLHelper.AppendQuery(AfterCreateRedirectURL, queryString)));
                    }
                }
                else
                {
                    // Edit existing source point
                    if (CurrentSourcePoint.Label != txtLabel.Text.Trim())
                    {
                        // Refresh header
                        ScriptHelper.RefreshTabHeader(Page);
                    }

                    SetValues(CurrentSourcePoint);
                    WorkflowScriptHelper.RefreshDesignerFromDialog(Page, CurrentStepInfo.StepID, graphName);
                }
            }
        }
    }
        public virtual SourcePoint PaintBlock(DelimiterCapableBlock block, DecorateLanguageElementEventArgs args, SourcePoint startPointToPaint, bool multipleBlocksOnLine)
        {
            SourcePoint result = startPointToPaint;
            if (Settings.Enabled && MeetsLengthRquirement(block))
            {
                StringBuilder metaDataBuilder = new StringBuilder();
                metaDataBuilder.Append(Settings.BlockTypeName);

                if(Settings.ShowDetailedBlockMetaData)
                {
                    DetailedBlockMetaData.AppendDetailedBlockMetaData(block,multipleBlocksOnLine,metaDataBuilder);
                }

                args.AddForegroundAdornment( new BlockMetaDataDocumentAdornment(startPointToPaint, Settings, metaDataBuilder.ToString()));

                result = new SourcePoint(block.EndLine,  startPointToPaint.Offset + Settings.BlockTypeName.Length);
            }

            return result;
        }
        public static ElementLocation From(LanguageElement methodOrProperty, SourcePoint sourcePoint)
        {
            LanguageElement element = CodeRush.Source.GetNodeAt(sourcePoint);
            if (element == null)
                return null;
            ElementLocation elementLocation = null;
            ElementLocation childLocation = null;

            while (true)
            {
                elementLocation = FromLanguageElement(element, sourcePoint);
                elementLocation._Child = childLocation;
                childLocation = elementLocation;
                if (element == methodOrProperty)
                    break;
                element = element.Parent;
                if (element == null)
                    break;
            }
            return elementLocation;
        }
        private static List<TagPrefix> FromValue(string name, SourcePoint start)
        {
            string[] parts = name.Split(':');
            if (parts == null || parts.Length == 0)
                return null;

            List<TagPrefix> result = new List<TagPrefix>();
            int offset = start.Offset;
            int lines = 0;
            for (int i = 0; i < parts.Length - 1; i++)
            {
                string part = parts[i];
                if (string.IsNullOrEmpty(part))
                    continue;

                int countLines = CodeRush.StrUtil.CountLines(part);
                string tagPrefixName = part;
                int indexlastSplitter = part.LastIndexOfAny(new char[] { '{', ' ', '\t', '\r', '\n' });
                if (indexlastSplitter >= 0)
                {
                    int startPosition = indexlastSplitter + 1;
                    if (countLines > 1)
                    {
                        lines += countLines - 1;
                        offset = CodeRush.StrUtil.GetLineLength(part, countLines) + 1;
                        offset -= part.Length - startPosition;
                    }
                    else
                        offset += startPosition;
                    tagPrefixName = part.Substring(startPosition);
                }
                SourcePoint startTagPrefix = new SourcePoint(start.Line + lines, offset);
                SourcePoint endTagPrefix = new SourcePoint(start.Line + lines, offset + tagPrefixName.Length);
                result.Add(new TagPrefix() { Name = tagPrefixName, Range = new SourceRange(startTagPrefix, endTagPrefix) });
                offset += tagPrefixName.Length + 1;
            }
            return result;
        }
        private static TagPrefix FromName(string name, SourcePoint start)
        {
            int colonIndex = name.IndexOf(":");
            if (colonIndex <= 0)
                return null;

            SourceRange tagPrefixRange = SourceRange.Empty;
            string tagPrefixName = name.Substring(0, colonIndex);
            if (tagPrefixName == "xmlns")
            {
                string xmlnsName = name.Substring(colonIndex + 1);
                SourcePoint xmlnsNameStart = new SourcePoint(start.Line, start.Offset + tagPrefixName.Length + 1);
                SourcePoint end = new SourcePoint(xmlnsNameStart.Line, xmlnsNameStart.Offset + xmlnsName.Length);
                tagPrefixRange = new SourceRange(xmlnsNameStart, end);
                tagPrefixName = xmlnsName;
            }
            else
            {
                SourcePoint end = new SourcePoint(start.Line, start.Offset + tagPrefixName.Length);
                tagPrefixRange  = new SourceRange(start, end);
            }
            return new TagPrefix() { Name = tagPrefixName, Range = tagPrefixRange };
        }
 private static SourcePoint GetPosition(SourcePoint sourcePoint, CaretVector vector)
 {
     return sourcePoint.OffsetPoint(vector.LineDelta, vector.OffsetDelta);
 }
 private static SourceRange InsertChildAtEndOfParent(LanguageElement Child, DelimiterCapableBlock Parent, TextDocument textDocument)
 {
     SourceRange NSRange = Parent.GetFullBlockRange();
     SourcePoint InsertPoint = new SourcePoint(NSRange.End.Line, 1);
     return textDocument.InsertText(InsertPoint, CodeRush.Language.GenerateElement(Child));
 }
 private bool ShouldBeAvailable(SourcePoint caret)
 {
     return NamespaceShouldBeUpdated(CodeRush.Source.ActiveFileNode.GetNodeAt(caret), ExpectedNamespace(CodeRush.Source.ActiveFileNode.Project as ProjectElement, CodeRush.Documents.ActiveTextDocument.Path));
 }
 private static CaretVector GetClosestVector(LanguageElement element, SourcePoint target)
 {
     List<CaretVector> locations = new List<CaretVector>();
     AddAllVectors(locations, element, target);
     locations.Sort(new VectorComparer());
     if (locations.Count > 0)
         return locations[0];
     return null;
 }
Esempio n. 53
0
 private void cpImplementIDisposable_Apply(object sender, ApplyContentEventArgs ea)
 {
     _ActiveClass = ea.ClassInterfaceOrStruct as TypeDeclaration;
       if (_ActiveClass == null)
     return;
       _TextDocument = ea.TextDocument;
       ElementBuilder elementBuilder = new ElementBuilder();
       AddDisposeImplementer(elementBuilder);
       AddVirtualDisposeMethod(elementBuilder);
       AddDestructorMember(elementBuilder);
       _DisposableImplementationCode = elementBuilder.GenerateCode(_TextDocument.Language);
       if (_ActiveClass.FirstChild == null)
       {
     SourcePoint startPt = SourcePoint.Empty;
     CodeRush.Language.GetCodeBlockStart(_ActiveClass, ref startPt);
     _InsertionPoint = startPt;
     GenerateIDisposableImplementationCode();
       }
       else
       {
     targetPicker1.Code = _DisposableImplementationCode;
     LanguageElement target = _ActiveClass.FirstChild;
     foreach (Method method in _ActiveClass.AllMethods)
     {
       target = method;
       break;
     }
     targetPicker1.Start(ea.TextView, target, InsertCode.UsePicker);
       }
 }
Esempio n. 54
0
 public dynamic Parse(ITextStream stream, ErrorReporter errors, SourcePoint startLocation)
 {
     object result = this.parser.Parse(stream, errors, startLocation);
     return this.NormalizeResult(result);
 }
Esempio n. 55
0
 private void targetPicker1_TargetSelected(object sender, TargetSelectedEventArgs ea)
 {
     _InsertionPoint = ea.Location.SourcePoint;
       GenerateIDisposableImplementationCode();
 }
Esempio n. 56
0
        /// <summary>
        /// Returns a range of code to highlight, which may be different from the actual code selected. This is done to 
        /// work around a cosmetic display bug in the 11.1 version of the BlockHighlighter control when highlighting 
        /// leading white space, and also to be more consistent with user expectations (users think of a member as starting
        /// and ending with code, not white space, but a cut or copy should include leading and trailing white space).
        /// </summary>
        private static SourceRange GetHighlightRange(TextView textView, SourceRange selectionRange)
        {
            SourcePoint top = selectionRange.Top;
            SourcePoint bottom = selectionRange.Bottom;
            if (bottom.Offset == 1)
            {
                if (bottom.Line > 1)
                {
                    string lineAbove = textView.TextDocument.GetText(bottom.Line - 1);
                    if (lineAbove.Length > 0)
                    {
                        bottom = new SourcePoint(bottom.Line - 1, lineAbove.Length + 1);
                    }
                }
            }
            string topLine = textView.TextDocument.GetText(top.Line);
            //string bottomLine = textView.TextDocument.GetText(bottom.Line);
            string topLeft;
            //string bottomLeft;
            int leadingWhiteSpaceCount = 0;
            //int trailingWhiteSpaceCount = 0;
            if (top.Offset - 1 > 0 && top.Offset - 1 < topLine.Length)
                topLeft = topLine.Substring(0, top.Offset - 1);
            else
                topLeft = topLine;
            leadingWhiteSpaceCount = CodeRush.StrUtil.GetLeadingWhiteSpaceCharCount(topLeft);
            top = top.OffsetPoint(0, leadingWhiteSpaceCount);

            //if (bottom.Offset - 1 > 0 && bottom.Offset - 1 < bottomLine.Length)
            //	bottomLeft = bottomLine.Substring(0, bottom.Offset - 1);
            //else
            //	bottomLeft = bottomLine;
            //trailingWhiteSpaceCount = CodeRush.StrUtil.GetLeadingWhiteSpaceCharCount(bottomLeft);
            //bottom = bottom.OffsetPoint(0, trailingWhiteSpaceCount);

            SourceRange highlightRange = new SourceRange(top, bottom);
            return highlightRange;
        }
Esempio n. 57
0
 /// <summary>
 /// Returns true if the specified SourcePoint is inside the specified range (but not at either of the ends of the SourceRange).
 /// </summary>
 public static bool Holds(this SourceRange range, SourcePoint testPoint)
 {
     return testPoint > range.Top && testPoint < range.Bottom;
 }
    private void AddItem(SourcePoint sp, List<WorkflowTransitionInfo> connections)
    {
        string label = String.Format(GetString("wf.sourcepoint.label"), sp.Label);
        WorkflowTransitionInfo conn = connections.FirstOrDefault(i => i.TransitionSourcePointGUID == sp.Guid);
        if (conn != null)
        {
            WorkflowStepInfo target = WorkflowStepInfoProvider.GetWorkflowStepInfo(conn.TransitionEndStepID);
            if (target != null)
            {
                label = String.Format("{0} {1}", label, string.Format(GetString("wf.sourcepoint.step"), target.StepDisplayName));
            }
        }

        ddlSourcePoints.Items.Add(new ListItem(ResHelper.LocalizeString(label), sp.Guid.ToString()));
    }
 /// <summary>
 /// Sets values from UI to provided source point object.
 /// </summary>
 /// <param name="sourcePoint">Source point</param>
 private void SetValues(SourcePoint sourcePoint)
 {
     if (sourcePoint != null)
     {
         sourcePoint.Label = txtLabel.Text;
         sourcePoint.Text = txtText.Text;
         sourcePoint.Tooltip = txtTooltip.Text;
         if (ShowCondition && (sourcePoint.Type != SourcePointTypeEnum.SwitchDefault))
         {
             sourcePoint.Condition = cbCondition.Text;
         }
     }
 }
Esempio n. 60
0
        private void WrapInTryFunction_Apply(Object sender, ApplyContentEventArgs ea)
        {
            // INITIALIZE
            Class activeClass = CodeRush.Source.ActiveClass;
            Method activeMethod = CodeRush.Source.ActiveMethod;
            var builder = new ElementBuilder();

            Logger.Log("WITF:Builder Built");

            var method = builder.AddMethod(activeClass, "bool", "Try" + activeMethod.Name);
            method.IsStatic = activeMethod.IsStatic;
            Logger.Log("WITF:Method Created");

            // PARAMS
            foreach (Param param in activeMethod.Parameters)
            {
                method.Parameters.Add(new Param(param.ParamType, param.Name));
            }
            Param resultParam = builder.BuildParameter(activeMethod.GetTypeName(), "result", ArgumentDirection.Out);
            method.Parameters.Add(resultParam);
            Logger.Log("WITF:Params Added");

            // METHOD CALL
            var arguments = new List<string>();
            foreach (IParameterElement SourceParam in activeMethod.Parameters)
            {
                arguments.Add(SourceParam.Name);
            }
            Logger.Log("WITF:Arguments Built");

            var methodCall = builder.BuildMethodCall(activeMethod.Name, arguments.ToArray());
            Logger.Log("WITF:Methodcall Added");

            var Try = builder.AddTry(method);
            Try.AddNode(builder.BuildAssignment("result", methodCall));
            Try.AddNode(builder.BuildReturn("true"));
            Logger.Log("WITF:Try Added");

            var ExCatch = builder.AddCatch(method);
            ExCatch.AddNode(builder.BuildAssignment("result", CodeRush.Language.GetNullReferenceExpression()));
            ExCatch.AddNode(builder.BuildReturn("false"));
            Logger.Log("WITF:Catch Added");

            // RENDER METHOD
            activeClass.AddNode(method);
            var Code = CodeRush.CodeMod.GenerateCode(method, false);
            Logger.Log("WITF:Code Generated");

            int LastLine = activeMethod.Range.End.Line;
            Logger.Log(String.Format("WITF:Last Line calculated = {0}", LastLine));

            SourcePoint InsertionPoint = new SourcePoint(LastLine + 1, 1);
            Logger.Log(String.Format("WITF:InsertionPoint Calculated=(Line:{0},Offset:{1})",
                                     InsertionPoint.Line, InsertionPoint.Offset));

            var newMethodRange = CodeRush.Documents.ActiveTextDocument.InsertText(InsertionPoint, Code);
            Logger.Log("WITF:Code Inserted");

            CodeRush.Documents.Format(newMethodRange);
            Logger.Log("WITF:Code Formatted");
        }