Question

I want to create a resharper plugin that removes properties with return type string from a class. I already created a IActionHandler which gets all properties from the selected class, but I don't know how I can modify code structure to remove the properties from the class.

Here is the Execute method of the IActionHandler:

public void Execute(IDataContext context, DelegateExecute nextExecute)
{
    // Fetch active solution from context.
    ISolution solution = context.GetData(JetBrains.ProjectModel.DataContext.DataConstants.SOLUTION);
    if (solution == null)
        return;

    var declaredElements = context.GetData(DataConstants.DECLARED_ELEMENTS);
    if (declaredElements == null || declaredElements.IsEmpty())
        return;

    IDeclaredElement declaredElement = declaredElements.First();

    var classElement = declaredElement as IClass;
    if (classElement != null)
    {
        var properties = classElement.Properties.Where(p => p.Type.IsString());

        foreach (IProperty property in properties)
        {
            // Remove IProperty from IClass   <--
        }
    }
}

Any ideas?

Was it helpful?

Solution

I found the answer:

public void Execute(IDataContext context, DelegateExecute nextExecute)
{
    // Fetch active solution from context.
    ISolution solution = context.GetData(JetBrains.ProjectModel.DataContext.DataConstants.SOLUTION);
    if (solution == null)
        return;

    var declaredElements = context.GetData(DataConstants.DECLARED_ELEMENTS);
    if (declaredElements == null || declaredElements.IsEmpty())
        return;

    IDeclaredElement declaredElement = declaredElements.First();

    var classElement = declaredElement as IClass;
    if (classElement != null)
    {
        // As a class can be declared in multiple files (partial classes) we enumerate all
        // declarations and choose the first one
        var declarations = classElement.GetDeclarations();
        var classDeclaration = declarations.First() as IClassDeclaration;

        var properties = classDeclaration.PropertyDeclarations.Where(p => p.Type.IsString());

        foreach (var propertyDeclaration in properties)
        {       
            PsiManager.GetInstance(solution).DoTransaction(() =>
            {
                classDeclaration.RemoveClassMemberDeclaration(propertyDeclaration);
            },
            "PsiTransactionCommand");
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top