コード例 #1
0
 /// <summary>
 /// Returns composed reference text
 /// </summary>
 public override string GetReferenceText(ReferenceString referenceText)
 {
     if (!ComesFromCodeBlock && !ComesFromInlineExpression)
     {
         string reference;
         if (SourceItem.ContainingProject.Kind.ToUpper() == StringConstants.WebSiteProject)
         {
             reference = string.Format(StringConstants.AspElementExpressionFormat, referenceText.NamespacePart, referenceText.ClassPart, referenceText.KeyPart);
         }
         else
         {
             reference = string.Format(StringConstants.AspElementReferenceFormat,
                                       (string.IsNullOrEmpty(referenceText.NamespacePart) ? "" : referenceText.NamespacePart + ".") + referenceText.ClassPart + "." + referenceText.KeyPart);
         }
         if (ComesFromPlainText)
         {
             return(string.Format(StringConstants.AspLiteralFormat, reference));
         }
         else
         {
             return(reference);
         }
     }
     else
     {
         return((string.IsNullOrEmpty(referenceText.NamespacePart) ? "" : referenceText.NamespacePart + ".") + referenceText.ClassPart + "." + referenceText.KeyPart);
     }
 }
コード例 #2
0
        public void ExistValue()
        {
            var m = ReferenceString.ToMaybe();

            m.IsInstanceOf <Maybe <string> >();
            m.Value.Is(ReferenceString);
            m.Map(s => s.Substring(999)).HasValue.IsFalse();
        }
コード例 #3
0
        public override void Convert(IUnitOfWork unitOfWork, T dto, U entity, PropertyInfo sourcePropertyInfo)
        {
            ReferenceAttribute referenceAttribute  = sourcePropertyInfo.GetCustomAttribute <ReferenceAttribute>();
            ReferenceString    referenceString     = sourcePropertyInfo.GetValue(dto) as ReferenceString;
            Type referencedEntityType              = GetReferencedEntityType(entity, referenceAttribute);
            IReferenceConverter referenceConverter = GetReferenceConverter(referenceAttribute, typeof(U), referencedEntityType);

            referenceConverter.Convert(unitOfWork, entity, dto, sourcePropertyInfo, referenceAttribute, referenceString);
        }
コード例 #4
0
 public override ExhibitionDto Persist(ExhibitionDto exhibitionDto)
 {
     if (exhibitionDto.PaintingsCheckedDto != null)
     {
         List <PaintingCheckedDto> paintingCheckedDtos = exhibitionDto.PaintingsCheckedDto.Where(x => x.Checked == true).Select(x => x).ToList();
         exhibitionDto.PaintingsReference = ReferenceString.Create <PaintingCheckedDto>(paintingCheckedDtos);
     }
     return(base.Persist(exhibitionDto));
 }
コード例 #5
0
        public override void Convert(Connection connection, T entity, U dto, PropertyInfo sourcePropertyInfo)
        {
            ReferenceAttribute referenceAttribute  = sourcePropertyInfo.GetCustomAttribute <ReferenceAttribute>();
            ReferenceString    referenceString     = sourcePropertyInfo.GetValue(dto) as ReferenceString;
            Type referencedEntityType              = GetReferencedEntityType(entity, referenceAttribute);
            IReferenceConverter referenceConverter = GetReferenceConverter(referenceAttribute, typeof(T), referencedEntityType);

            referenceConverter.Convert(connection, entity, dto, sourcePropertyInfo, referenceAttribute, referenceString);
        }
コード例 #6
0
        public UIElement GenerateUiControl(BaseDto dto, PropertyInfo propertyInfo, Grid grid, int rowIndex)
        {
            CreateLabel(propertyInfo, grid, rowIndex);

            Grid referenceGrid = new Grid();

            referenceGrid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = new GridLength(1, GridUnitType.Star)
            });
            referenceGrid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = GridLength.Auto
            });
            referenceGrid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = GridLength.Auto
            });

            Label referenceLabel = CreateReferenceLabel(dto, propertyInfo);

            Button referenceButton = CreateButton("...", delegate
            {
                IReferenceEditor referenceEditor = CreateReferenceEditor(dto, propertyInfo); //(BaseReferenceEditor)Activator.CreateInstance(Type.GetType(editorAttribute.CompleteAssembly));
                TreeNavigationItem selectedTreeNavigationItem = DialogUtils.OpenReferenceWindow(referenceEditor.GetProposals);
                if (selectedTreeNavigationItem != null)
                {
                    ReferenceString referenceString = new ReferenceString(selectedTreeNavigationItem.Id, selectedTreeNavigationItem.Name);
                    propertyInfo.SetValue(dto, referenceString);
                    referenceLabel.Content = referenceString.GetValue();
                }
            });

            Image image = new Image();

            image.Source = new BitmapImage(RemoveReferenceImage);
            Button removeReferenceButton = CreateButton(image, delegate
            {
                propertyInfo.SetValue(dto, null);
                referenceLabel.Content = string.Empty;
            });

            referenceGrid.Children.Add(referenceLabel);
            referenceGrid.Children.Add(referenceButton);
            referenceGrid.Children.Add(removeReferenceButton);

            Grid.SetColumn(referenceLabel, 0);
            Grid.SetColumn(referenceButton, 1);
            Grid.SetColumn(removeReferenceButton, 2);

            grid.Children.Add(referenceGrid);
            Grid.SetRow(referenceGrid, rowIndex);
            Grid.SetColumn(referenceGrid, 1);

            return(referenceGrid);
        }
コード例 #7
0
        /// <summary>
        /// Creates the links of the references.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="htmlHelper">The html helper</param>
        /// <param name="referencies">The referencies contained IDs and labels</param>
        /// <param name="action">The action name</param>
        /// <param name="controller">The controller name</param>
        /// <param name="htmlAttributes">The html attributes</param>
        /// <returns>Returns the created links of the references</returns>
        public static string CreateLinks <T>(this HtmlHelper <T> htmlHelper, ReferenceString referenceString, string action, string controller, object htmlAttributes)
        {
            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair <Guid, string> reference in referenceString.GetReferencies())
            {
                sb.Append(LinkExtensions.ActionLink(htmlHelper, reference.Value, action, controller, new { id = reference.Key, name = UrlUtils.ToSeoUrl(reference.Value) }, htmlAttributes).ToString());
            }
            return(sb.ToString());
        }
コード例 #8
0
 /// <summary>
 /// Returns composed reference text
 /// </summary>
 public override string GetReferenceText(ReferenceString referenceText)
 {
     if (DestinationItem.IsProjectDefault(SourceItem.ContainingProject))   // employ My.Resources feature
     {
         return("My.Resources." + referenceText.KeyPart);
     }
     else
     {
         return((string.IsNullOrEmpty(referenceText.NamespacePart) ? "" : referenceText.NamespacePart + ".") + referenceText.ClassPart + "." + referenceText.KeyPart);
     }
 }
コード例 #9
0
        private Label CreateReferenceLabel(BaseDto dto, PropertyInfo propertyInfo)
        {
            Label label = new Label();

            label.Margin = new Thickness(0, 2, 0, 2);
            ReferenceString referenceString = (ReferenceString)propertyInfo.GetValue(dto);

            if (referenceString != null)
            {
                label.Content = referenceString.GetValue();
            }
            return(label);
        }
コード例 #10
0
        public static MvcHtmlString LocalizedDisplayFor <T, U>(this HtmlHelper <T> htmlHelper, Expression <Func <T, U> > expression, string defaultValue = null)
        {
            ModelMetadata expressionModelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            if (expressionModelMetadata.Model == null)
            {
                return(MvcHtmlString.Create(defaultValue));
            }
            if (expressionModelMetadata.Model is ReferenceString)
            {
                ReferenceString referenceString = expressionModelMetadata.Model as ReferenceString;
                return(MvcHtmlString.Create(referenceString.GetValue()));
            }
            return(DisplayExtensions.DisplayFor(htmlHelper, expression));
        }
コード例 #11
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            ObservableCollection <TreeNavigationItem> treeNavigationItems = new ObservableCollection <TreeNavigationItem>();

            if (value == null)
            {
                return(null);
            }
            Dictionary <Guid, string> dictionary = ReferenceString.Parse(value.ToString());

            foreach (KeyValuePair <Guid, string> referenceString in dictionary)
            {
                treeNavigationItems.Add(new TreeNavigationItem(referenceString.Key, referenceString.Value, NavigationType.FOLDER));
            }
            return(treeNavigationItems);
        }
        public void Convert(Connection connection, BaseEntity sourceEntity, BaseDto dto, PropertyInfo sourcePropertyInfo, ReferenceAttribute referenceAttribute, ReferenceString referenceString)
        {
            PropertyInfo    referencedEntityPropertyInfo = sourceEntity.GetType().GetProperty(referenceAttribute.RefencedPropertyName);
            IEnumerable <U> referencedEntities           = (IEnumerable <U>)referencedEntityPropertyInfo.GetValue(sourceEntity, null);

            if (referencedEntities == null)
            {
                return;
            }

            ReferenceString referencedString = new ReferenceString(string.Empty);

            foreach (U referencedEntity in referencedEntities)
            {
                referencedString.Append(referencedEntity.Id, referencedEntity.ToString());
            }
            sourcePropertyInfo.SetValue(dto, referencedString);
        }
コード例 #13
0
        private ListBox CreateReferenceList(BaseDto baseDto, PropertyInfo propertyInfo)
        {
            ListBox listBox = new ListBox();

            listBox.Margin = new Thickness(2, 5, 2, 5);
            ReferenceString referenceString = (ReferenceString)propertyInfo.GetValue(baseDto);

            if (referenceString != null)
            {
                Dictionary <Guid, string> dictionary = ReferenceString.Parse(referenceString.ToString());
                foreach (KeyValuePair <Guid, string> value in dictionary)
                {
                    listBox.Items.Add(new TreeNavigationItem(value.Key, value.Value, NavigationType.FOLDER));
                }
            }
            listBox.Height = 120;
            return(listBox);
        }
コード例 #14
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
            }

            if (!(value is ReferenceString))
            {
                return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
            }

            ReferenceString referenceString = (ReferenceString)value;

            if (referenceString.Value == null)
            {
                return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
            }
            return(ValidationResult.Success);
        }
コード例 #15
0
        public void Convert(IUnitOfWork unitOfWork, BaseEntity sourceEntity, BaseDto dto, PropertyInfo sourcePropertyInfo, ReferenceAttribute referenceAttribute, ReferenceString referenceString)
        {
            PropertyInfo targetProperty = sourceEntity.GetType().GetProperty(referenceAttribute.RefencedPropertyName);
            // TODO ???
            //if(referenceString == null || referenceString.Value == null)
            //{
            //    return;
            //}
            List <Guid> referencedIds = new List <Guid>();

            if (referenceString != null && referenceString.Value != null)
            {
                referencedIds = referenceString.GetIds();
            }

            ICollection <U> referencedEntities = (ICollection <U>)targetProperty.GetValue(sourceEntity);

            if (IsReferenciesCreated(referencedIds, referencedEntities))
            {
                CreateMultiReferences(unitOfWork, sourceEntity, targetProperty, referencedIds, referencedEntities);
            }
            else
            {
                UpdateMultiReference(unitOfWork, sourceEntity, targetProperty, referencedIds, referencedEntities);
            }
        }
        public void Convert(Connection connection, BaseEntity sourceEntity, BaseDto dto, PropertyInfo sourcePropertyInfo, ReferenceAttribute referenceAttribute, ReferenceString referenceString)
        {
            if (referenceString == null)
            {
                return;
            }
            PropertyInfo    targetProperty     = sourceEntity.GetType().GetProperty(referenceAttribute.RefencedPropertyName);
            List <Guid>     referencedIds      = referenceString.GetIds();
            ICollection <U> referencedEntities = (ICollection <U>)targetProperty.GetValue(sourceEntity);

            if (IsReferenciesCreated(referencedIds, referencedEntities))
            {
                CreateMultiReferences(connection, sourceEntity, targetProperty, referencedIds, referencedEntities);
            }
            else
            {
                UpdateMultiReference(connection, sourceEntity, targetProperty, referencedIds, referencedEntities);
            }
        }
コード例 #17
0
 private string GenerateLinkToSpecificLink(MenuItemEntityType menuEntityType, ReferenceString userDefinableReference)
 {
     return(string.Format("/{0}/{1}/{2}", menuEntityType.ToString().ToLower(), WebConstants.VIEW_DETAILS, userDefinableReference.GetId()));
 }
コード例 #18
0
        public void Convert(IUnitOfWork unitOfWork, BaseEntity sourceEntity, BaseDto targetDto, PropertyInfo sourcePropertyInfo, ReferenceAttribute referenceAttribute, ReferenceString referenceString)
        {
            PropertyInfo referencedEntityPropertyInfo   = sourceEntity.GetType().GetProperty(referenceAttribute.RefencedPropertyName);
            PropertyInfo referencedEntityIdPropertyInfo = ReferenceConversionUtils.GetReferencedPropertyId(sourceEntity, referenceAttribute); //sourceEntity.GetType().GetProperty(ReferenceConversionUtils.GetReferencedId(referenceAttribute));
            U            referencedEntity = (U)referencedEntityPropertyInfo.GetValue(sourceEntity, null);

            if (referencedEntity != null)
            {
                sourcePropertyInfo.SetValue(targetDto, new ReferenceString(referencedEntity.Id, referencedEntity.ToString()));
            }
        }
コード例 #19
0
        public UIElement GenerateUiControl(BaseDto dto, PropertyInfo propertyInfo, Grid grid, int rowIndex)
        {
            CreateLabel(propertyInfo, grid, rowIndex);

            Grid referenceGrid = new Grid();

            referenceGrid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = new GridLength(1, GridUnitType.Star)
            });
            referenceGrid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = GridLength.Auto
            });
            referenceGrid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = GridLength.Auto
            });

            ListBox referenceList = CreateReferenceList(dto, propertyInfo);

            StackPanel stackPanel = new StackPanel();

            stackPanel.Margin      = new Thickness(10, 0, 5, 0);
            stackPanel.Orientation = Orientation.Vertical;

            Button referenceButton = CreateButton("Add", delegate
            {
                //          ReferenceEdirorAttribute editorAttribute = (ReferenceEdirorAttribute)propertyInfo.GetCustomAttribute(typeof(ReferenceEdirorAttribute));
                IReferenceEditor baseReferenceEditor          = CreateReferenceEditor(dto, propertyInfo); //(BaseReferenceEditor)Activator.CreateInstance(Type.GetType(editorAttribute.CompleteAssembly));
                TreeNavigationItem selectedTreeNavigationItem = DialogUtils.OpenReferenceWindow(baseReferenceEditor.GetProposals);
                if (selectedTreeNavigationItem != null)
                {
                    ReferenceString referenceString = (ReferenceString)propertyInfo.GetValue(dto);
                    if (referenceString == null)
                    {
                        referenceString = new ReferenceString();
                    }
                    referenceString.Append(selectedTreeNavigationItem.Id, selectedTreeNavigationItem.Name);
                    propertyInfo.SetValue(dto, referenceString);
                    referenceList.Items.Add(selectedTreeNavigationItem);
                }
            });

            Button removeReferenceButton = CreateButton("Remove", delegate
            {
                TreeNavigationItem selectedTreeNavigationItem = referenceList.SelectedItem as TreeNavigationItem;
                ReferenceString referenceString = (ReferenceString)propertyInfo.GetValue(dto);
                referenceString.Remove(selectedTreeNavigationItem.Id);
                referenceList.Items.Remove(selectedTreeNavigationItem);
            });

            stackPanel.Children.Add(referenceButton);
            stackPanel.Children.Add(removeReferenceButton);

            referenceGrid.Children.Add(referenceList);
            referenceGrid.Children.Add(stackPanel);

            Grid.SetColumn(referenceList, 0);
            Grid.SetColumn(stackPanel, 1);

            grid.Children.Add(referenceGrid);
            Grid.SetRow(referenceGrid, rowIndex);
            Grid.SetColumn(referenceGrid, 1);

            return(referenceGrid);
        }
コード例 #20
0
 /// <summary>
 /// Returns composed reference text
 /// </summary>
 public abstract string GetReferenceText(ReferenceString referenceText);
コード例 #21
0
        public void Move(List <CodeStringResultItem> dataList, ref int errorRows)
        {
            // sort according to position
            dataList.Sort(new ResultItemsPositionCompararer <CodeStringResultItem>());

            for (int i = dataList.Count - 1; i >= 0; i--)
            {
                try {
                    // initialization of data
                    CodeStringResultItem resultItem   = dataList[i];
                    string              path          = resultItem.SourceItem.GetFullPath();
                    ReferenceString     referenceText = null;
                    bool                addUsingBlock = false;
                    CONTAINS_KEY_RESULT keyConflict   = CONTAINS_KEY_RESULT.DOESNT_EXIST;

                    if (resultItem.MoveThisItem) // row was checked in the toolwindow
                    {
                        Validate(resultItem);    // check that key, value and destination item was specifed and that row has no errors
                        if (!resultItem.DestinationItem.IsLoaded)
                        {
                            resultItem.DestinationItem.Load();
                        }
                        if (!loadedResxItems.Contains(resultItem.DestinationItem))
                        {
                            loadedResxItems.Add(resultItem.DestinationItem);
                        }

                        // check if such item already exists in destination file
                        keyConflict = resultItem.DestinationItem.GetKeyConflictType(resultItem.Key, resultItem.Value, true);
                        if (keyConflict == CONTAINS_KEY_RESULT.EXISTS_WITH_DIFF_VALUE)
                        {
                            throw new InvalidOperationException(string.Format("Key \"{0}\" already exists with different value.", resultItem.Key));
                        }
                        resultItem.Key = resultItem.DestinationItem.GetRealKey(resultItem.Key); // if key already exists, return its name (solves case-sensitivity problems)

                        NamespacesList usedNamespaces = GetUsedNamespacesFor(resultItem);

                        if (UseFullName || resultItem.MustUseFullName || (resultItem.Language == LANGUAGE.VB && resultItem.DestinationItem.IsProjectDefault(resultItem.SourceItem.ContainingProject)))   // reference will contain namespace
                        {
                            referenceText = new ReferenceString(resultItem.DestinationItem.Namespace, resultItem.DestinationItem.Class, resultItem.Key);
                            addUsingBlock = false; // no using block will be added
                        }
                        else
                        {
                            // use resolver whether it is ok to add using block
                            addUsingBlock = usedNamespaces.ResolveNewElement(resultItem.DestinationItem.Namespace, resultItem.DestinationItem.Class, resultItem.Key,
                                                                             resultItem.SourceItem.ContainingProject, out referenceText);
                        }
                        if (addUsingBlock)   // new using block will be added
                        {
                            if (!usedNamespacesCache.ContainsKey(resultItem.SourceItem))
                            {
                                usedNamespacesCache.Add(resultItem.SourceItem, new NamespacesList());
                            }
                            foreach (var pair in usedNamespacesCache)
                            {
                                if (!pair.Value.ContainsNamespace(resultItem.DestinationItem.Namespace))
                                {
                                    pair.Value.Add(resultItem.DestinationItem.Namespace, null, true);
                                }
                            }
                        }
                    }

                    if (RDTManager.IsFileOpen(path) && RDTManager.IsFileVisible(path))                                                    // file is open
                    {
                        if (resultItem.MoveThisItem || (MarkUncheckedStringsWithComment && !resultItem.IsMarkedWithUnlocalizableComment)) // string literal in text will be modified (referenced or marked with comment)
                        {
                            if (!buffersCache.ContainsKey(path))
                            {
                                // load file's buffer
                                IVsTextLines textLines = DocumentViewsManager.GetTextLinesForFile(path, false);
                                buffersCache.Add(path, textLines);

                                IOleUndoManager m;
                                // get file's undo manager
                                int hr = textLines.GetUndoManager(out m);
                                Marshal.ThrowExceptionForHR(hr);
                                undoManagersCache.Add(path, m);
                            }
                        }

                        if (resultItem.MoveThisItem)
                        {
                            // perform the text replacement
                            MoveToResource(buffersCache[path], resultItem, referenceText);

                            if (resultItem.IsConst && resultItem.CodeModelSource is CodeVariable2)
                            {
                                CodeVariable2 codeVar = (CodeVariable2)resultItem.CodeModelSource;
                                codeVar.ConstKind = vsCMConstKind.vsCMConstKindNone;
                            }

                            if (addUsingBlock)
                            {
                                // add using block to the source file
                                int beforeLines, afterLines;
                                buffersCache[path].GetLineCount(out beforeLines);
                                resultItem.AddUsingBlock(buffersCache[path]);
                                buffersCache[path].GetLineCount(out afterLines);
                                int diff = afterLines - beforeLines;

                                // because of the previous step, it is necessary to adjust position of all not-yet referenced result items
                                for (int j = i; j >= 0; j--)
                                {
                                    var item = dataList[j];
                                    if (item.SourceItem == resultItem.SourceItem)
                                    {
                                        TextSpan ts = new TextSpan();
                                        ts.iEndIndex     = item.ReplaceSpan.iEndIndex;
                                        ts.iEndLine      = item.ReplaceSpan.iEndLine + diff;
                                        ts.iStartIndex   = item.ReplaceSpan.iStartIndex;
                                        ts.iStartLine    = item.ReplaceSpan.iStartLine + diff;
                                        item.ReplaceSpan = ts;
                                    }
                                }
                            }

                            // previous step (replace and possibly new using block) caused undo unit to be added - remove it
                            int unitsToRemoveCount    = (resultItem.IsConst && addUsingBlock ? 3 : (resultItem.IsConst || addUsingBlock ? 2 : 1));
                            List <IOleUndoUnit> units = undoManagersCache[path].RemoveTopFromUndoStack(unitsToRemoveCount);

                            // and add custom undo unit
                            AbstractUndoUnit newUnit = null;
                            if (keyConflict == CONTAINS_KEY_RESULT.DOESNT_EXIST)
                            {
                                newUnit = new MoveToResourcesUndoUnit(resultItem.Key, resultItem.Value, resultItem.DestinationItem);
                            }
                            else if (keyConflict == CONTAINS_KEY_RESULT.EXISTS_WITH_SAME_VALUE)
                            {
                                newUnit = new MoveToResourcesReferenceUndoUnit(resultItem.Key);
                            }

                            newUnit.AppendUnits.AddRange(units);
                            undoManagersCache[path].Add(newUnit);
                        }
                        else if (MarkUncheckedStringsWithComment && !resultItem.IsMarkedWithUnlocalizableComment)     // string literal should be marked with comment
                        {
                            AspNetStringResultItem aitem = resultItem as AspNetStringResultItem;

                            // this operation is only possible if string literal comes from C# code
                            if (resultItem is CSharpStringResultItem || (aitem != null && aitem.ComesFromCodeBlock && aitem.Language == LANGUAGE.CSHARP))
                            {
                                // add the comment
                                int c = MarkAsNoLoc(buffersCache[path], resultItem);

                                // add undo unit
                                List <IOleUndoUnit> units = undoManagersCache[path].RemoveTopFromUndoStack(1);
                                MarkAsNotLocalizedStringUndoUnit newUnit = new MarkAsNotLocalizedStringUndoUnit(resultItem.Value);
                                newUnit.AppendUnits.AddRange(units);
                                undoManagersCache[path].Add(newUnit);
                            }
                        }
                    }
                    else     // file is closed
                    // same as with open file, only operating with text, not buffers

                    {
                        if (resultItem.MoveThisItem || (MarkUncheckedStringsWithComment && !resultItem.IsMarkedWithUnlocalizableComment))   // string literal will be modified
                        // load file's text into the cache
                        {
                            if (!filesCache.ContainsKey(path))
                            {
                                filesCache.Add(path, new StringBuilder(File.ReadAllText(path)));
                            }
                        }

                        if (resultItem.IsConst && resultItem.CodeModelSource is CodeVariable2)
                        {
                            CodeVariable2 codeVar = (CodeVariable2)resultItem.CodeModelSource;
                            fieldsToRemoveConst.Add(codeVar);
                        }

                        if (resultItem.MoveThisItem)
                        {
                            StringBuilder b = filesCache[path];

                            // perform the replacement
                            string insertText = resultItem.GetReferenceText(referenceText);
                            b.Remove(resultItem.AbsoluteCharOffset, resultItem.AbsoluteCharLength);
                            b.Insert(resultItem.AbsoluteCharOffset, insertText);

                            if (addUsingBlock)
                            {
                                // add using block
                                if (!newUsingsPlan.ContainsKey(path))
                                {
                                    newUsingsPlan.Add(path, new List <string>());
                                }
                                newUsingsPlan[path].Add(resultItem.DestinationItem.Namespace);
                            }
                        }
                        else if (MarkUncheckedStringsWithComment && !resultItem.IsMarkedWithUnlocalizableComment)
                        {
                            AspNetStringResultItem aitem = resultItem as AspNetStringResultItem;

                            if (resultItem is CSharpStringResultItem || (aitem != null && aitem.ComesFromCodeBlock && aitem.Language == LANGUAGE.CSHARP))
                            {
                                StringBuilder b = filesCache[path];
                                b.Insert(resultItem.AbsoluteCharOffset, resultItem.NoLocalizationComment);
                            }
                        }
                    }

                    if (resultItem.MoveThisItem && keyConflict == CONTAINS_KEY_RESULT.DOESNT_EXIST)
                    {
                        if (!resultItem.DestinationItem.IsInBatchMode)
                        {
                            resultItem.DestinationItem.BeginBatch();
                        }
                        // add the key to the ResX file
                        resultItem.DestinationItem.AddString(resultItem.Key, resultItem.Value);
                    }
                } catch (Exception ex) {
                    errorRows++;
                    VLOutputWindow.VisualLocalizerPane.WriteException(ex);
                }
            }

            // add using blocks to closed files texts
            foreach (var pair in newUsingsPlan)
            {
                foreach (string nmspc in pair.Value)
                {
                    AddUsingBlockTo(pair.Key, nmspc);
                }
            }

            // flush closed files texts
            foreach (var pair in filesCache)
            {
                if (RDTManager.IsFileOpen(pair.Key))
                {
                    RDTManager.SetIgnoreFileChanges(pair.Key, true);
                    File.WriteAllText(pair.Key, pair.Value.ToString());
                    RDTManager.SetIgnoreFileChanges(pair.Key, false);
                    RDTManager.SilentlyReloadFile(pair.Key);
                }
                else
                {
                    File.WriteAllText(pair.Key, pair.Value.ToString());
                }
            }

            // remove 'const' modifier from fields in closed files
            HashSet <ProjectItem> itemsToSave = new HashSet <ProjectItem>();

            foreach (CodeVariable2 codeVar in fieldsToRemoveConst)
            {
                codeVar.ConstKind = vsCMConstKind.vsCMConstKindNone;
                itemsToSave.Add(codeVar.ProjectItem);
            }
            foreach (ProjectItem item in itemsToSave)
            {
                item.Save(null);
            }

            foreach (ResXProjectItem item in loadedResxItems)
            {
                if (item.IsInBatchMode)
                {
                    item.EndBatch();
                }
                item.Unload();
            }
            if (errorRows > 0)
            {
                throw new Exception("Error occured while processing some rows - see Output window for details.");
            }
        }
コード例 #22
0
        /// <summary>
        /// Perform actual replacement of the string literal
        /// </summary>
        /// <returns>Length of the reference</returns>
        private int MoveToResource(IVsTextLines textLines, CodeStringResultItem resultItem, ReferenceString referenceText)
        {
            string newText = resultItem.GetReferenceText(referenceText);
            int    hr      = textLines.ReplaceLines(resultItem.ReplaceSpan.iStartLine, resultItem.ReplaceSpan.iStartIndex, resultItem.ReplaceSpan.iEndLine, resultItem.ReplaceSpan.iEndIndex,
                                                    Marshal.StringToBSTR(newText), newText.Length, new TextSpan[] { resultItem.ReplaceSpan });

            Marshal.ThrowExceptionForHR(hr);

            return(newText.Length);
        }
コード例 #23
0
 /// <summary>
 /// Returns composed reference text
 /// </summary>
 public override string GetReferenceText(ReferenceString referenceText)
 {
     return((string.IsNullOrEmpty(referenceText.NamespacePart) ? "" : referenceText.NamespacePart + ".") + referenceText.ClassPart + "." + referenceText.KeyPart);
 }
        public void Convert(IUnitOfWork unitOfWork, BaseEntity sourceEntity, BaseDto dto, PropertyInfo sourcePropertyInfo, ReferenceAttribute referenceAttribute, ReferenceString referenceString)
        {
            //PropertyInfo targetProperty = sourceEntity.GetType().GetProperty(ReferenceConversionUtils.GetReferencedId(referenceAttribute));
            PropertyInfo targetProperty = ReferenceConversionUtils.GetReferencedPropertyId(sourceEntity, referenceAttribute);

            if (referenceString == null || string.IsNullOrEmpty(referenceString.Value))
            {
                targetProperty.SetValue(sourceEntity, null);
            }
            else
            {
                targetProperty.SetValue(sourceEntity, referenceString.GetId());
            }
        }
コード例 #25
0
        public SelectResourceFileForm(ProjectItem sourceItem, CodeStringResultItem resultItem)
        {
            if (sourceItem == null)
            {
                throw new ArgumentNullException("sourceItem");
            }
            if (resultItem == null)
            {
                throw new ArgumentNullException("resultItem");
            }

            InitializeComponent();

            this.Icon          = VSPackage._400;
            this.resultItem    = resultItem;
            this.referenceText = new ReferenceString();

            // add suggestions of key names to suggestions list
            foreach (string s in resultItem.GetKeyNameSuggestions())
            {
                keyBox.Items.Add(s);
            }

            if (SettingsObject.Instance.SelectedKeyIndex >= 0 && SettingsObject.Instance.SelectedKeyIndex < keyBox.Items.Count)
            {
                keyBox.SelectedIndex = SettingsObject.Instance.SelectedKeyIndex;
            }
            else
            {
                keyBox.SelectedIndex = 0;
            }

            valueBox.Text = resultItem.Value;
            // add possible destination files

            int selectedPathIndex = -1;
            int i = 0;

            foreach (var item in sourceItem.ContainingProject.GetResXItemsAround(true, false))
            {
                comboBox.Items.Add(item);
                if (string.Compare(item.InternalProjectItem.GetFullPath(), SettingsObject.Instance.SelectedResourceFilePath, true) == 0)
                {
                    selectedPathIndex = i;
                }
                i++;
            }

            if (selectedPathIndex >= 0 && selectedPathIndex < comboBox.Items.Count)
            {
                comboBox.SelectedIndex = selectedPathIndex;
            }
            else
            {
                if (comboBox.Items.Count > 0)
                {
                    comboBox.SelectedIndex = 0;
                }
            }

            usingBox.Checked = !SettingsObject.Instance.SelectedUseFullName;
            fullBox.Checked  = SettingsObject.Instance.SelectedUseFullName;

            overwriteButton.Visible  = false;
            inlineButton.Visible     = false;
            existingLabel.Visible    = false;
            existingValueBox.Visible = false;

            errorLabel.Text = "";
        }
コード例 #26
0
        /// <summary>
        /// Called on click - when overriden, finds object in current selection and displayes dialog offering to move it.
        /// </summary>
        public override void Process()
        {
            base.Process();                        // initialize basic variables

            T resultItem = GetReplaceStringItem(); // get result item (language specific)

            if (resultItem != null)                // result item found and ok - proceed
            {
                TextSpan replaceSpan        = resultItem.ReplaceSpan;
                string   referencedCodeText = resultItem.Value;
                resultItem.SourceItem = currentDocument.ProjectItem; // set origin project item of the result item

                // display dialog enabling user to modify resource key, select destination resource file etc.
                // also enables user to resolve conflicts (duplicate key entries)
                SelectResourceFileForm            f      = new SelectResourceFileForm(currentDocument.ProjectItem, resultItem);
                System.Windows.Forms.DialogResult result = f.ShowDialog();

                resultItem.DestinationItem = f.SelectedItem; // set destination project item - ResX file

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    bool removeConst = false;
                    if (resultItem.IsConst)
                    {
                        var deleteConst = VisualLocalizer.Library.Components.MessageBox.Show("This field is marked as 'const'. In order to continue with this operation, this modifier must be removed. Continue?", "Const", OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_WARNING);
                        if (deleteConst == DialogResult.Yes)
                        {
                            removeConst = true;
                        }
                        else
                        {
                            return;
                        }
                    }

                    bool            unitsFromStackRemoved = false;
                    bool            unitMovedToResource   = false;
                    ReferenceString referenceText;
                    bool            addUsing = false;

                    // Now we must resolve the namespaces issue. If user selected the "use full name" in previous dialog,
                    // there's no trouble. Otherwise we must find out, if necessary namespace has already been included (using)
                    // and if not, create new using block with the namespace name.

                    try {
                        resultItem.DestinationItem = f.SelectedItem;
                        if (resultItem.DestinationItem == null)
                        {
                            throw new InvalidOperationException("Destination item must be selected.");
                        }
                        if (resultItem.DestinationItem.InternalProjectItem == null)
                        {
                            throw new InvalidOperationException("Destination item must be selected.");
                        }
                        if (!File.Exists(resultItem.DestinationItem.InternalProjectItem.GetFullPath()))
                        {
                            throw new InvalidOperationException("Destination item file does not exist.");
                        }

                        if (f.UsingFullName || resultItem.MustUseFullName || (resultItem.Language == LANGUAGE.VB && resultItem.DestinationItem.IsProjectDefault(resultItem.SourceItem.ContainingProject)))
                        {
                            referenceText = new ReferenceString(f.SelectedItem.Namespace, f.SelectedItem.Class, f.Key);
                            addUsing      = false;
                        }
                        else
                        {
                            NamespacesList usedNamespaces = resultItem.GetUsedNamespaces();
                            addUsing = usedNamespaces.ResolveNewElement(f.SelectedItem.Namespace, f.SelectedItem.Class, f.Key,
                                                                        currentDocument.ProjectItem.ContainingProject, out referenceText);
                        }

                        string newText = resultItem.GetReferenceText(referenceText);

                        // perform actual replace
                        int hr = textLines.ReplaceLines(replaceSpan.iStartLine, replaceSpan.iStartIndex, replaceSpan.iEndLine, replaceSpan.iEndIndex,
                                                        Marshal.StringToBSTR(newText), newText.Length, new TextSpan[] { replaceSpan });
                        Marshal.ThrowExceptionForHR(hr);

                        // set selection to the new text
                        hr = textView.SetSelection(replaceSpan.iStartLine, replaceSpan.iStartIndex,
                                                   replaceSpan.iStartLine, replaceSpan.iStartIndex + newText.Length);
                        Marshal.ThrowExceptionForHR(hr);

                        if (removeConst)
                        {
                            CodeVariable2 codeVar = (CodeVariable2)resultItem.CodeModelSource;
                            codeVar.ConstKind = vsCMConstKind.vsCMConstKindNone;
                        }

                        if (addUsing)
                        {
                            resultItem.AddUsingBlock(textLines);
                        }

                        if (f.Result == SELECT_RESOURCE_FILE_RESULT.INLINE)
                        {
                            // conflict -> user chooses to reference existing key
                            unitsFromStackRemoved = CreateMoveToResourcesReferenceUndoUnit(f.Key, addUsing, removeConst);
                        }
                        else if (f.Result == SELECT_RESOURCE_FILE_RESULT.OVERWRITE)
                        {
                            // conflict -> user chooses to overwrite existing key and reference the new one
                            f.SelectedItem.AddString(f.Key, f.Value);
                            unitMovedToResource   = true;
                            unitsFromStackRemoved = CreateMoveToResourcesOverwriteUndoUnit(f.Key, f.Value, f.OverwrittenValue, f.SelectedItem, addUsing, removeConst);
                        }
                        else
                        {
                            // no conflict occured
                            f.SelectedItem.AddString(f.Key, f.Value);
                            unitMovedToResource   = true;
                            unitsFromStackRemoved = CreateMoveToResourcesUndoUnit(f.Key, f.Value, f.SelectedItem, addUsing, removeConst);
                        }
                    } catch (Exception) {
                        // exception occured - rollback all already performed actions in order to restore original state

                        VLOutputWindow.VisualLocalizerPane.WriteLine("Exception caught, rolling back...");
                        if (!unitsFromStackRemoved)
                        {
                            int unitsToRemoveCount    = (addUsing && removeConst) ? 3 : (addUsing || removeConst ? 2 : 1);
                            List <IOleUndoUnit> units = undoManager.RemoveTopFromUndoStack(unitsToRemoveCount);
                            foreach (var unit in units)
                            {
                                unit.Do(undoManager);
                            }
                            undoManager.RemoveTopFromUndoStack(units.Count);
                            if (unitMovedToResource)
                            {
                                f.SelectedItem.RemoveKey(f.Key);
                            }
                        }
                        else
                        {
                            AbstractUndoUnit unit = (AbstractUndoUnit)undoManager.RemoveTopFromUndoStack(1)[0];
                            int unitsToRemove     = unit.AppendUnits.Count + 1;
                            unit.Do(undoManager);
                            undoManager.RemoveTopFromUndoStack(unitsToRemove);
                        }
                        throw;
                    }
                }
            }
            else
            {
                throw new Exception("This part of code cannot be referenced");
            }
        }