public static IPropertyDeclaration GetPropertyDeclaration(IClassDeclaration classDeclaration, IInvocationExpression invocationExpression)
        {
            IPropertyDeclaration propertyDeclaration = null;
            if (invocationExpression.ArgumentList.Arguments.Count >= 1)
            {
                string propertyName = null;
                var argument = invocationExpression.ArgumentList.Arguments[0];
                if (argument.Value is ILambdaExpression)
                {
                    var lambdaExpression = argument.Value as ILambdaExpression;
                    var referenceExpression = lambdaExpression.BodyExpression as IReferenceExpression;
                    if (referenceExpression != null)
                    {
                        propertyName = referenceExpression.NameIdentifier.Name;
                    }
                }
                else if (argument.Value != null && argument.Value.ConstantValue != null)
                {
                    propertyName = argument.Value.ConstantValue.Value.ToString();
                }

                if (!string.IsNullOrEmpty(propertyName) && classDeclaration.DeclaredElement != null)
                {
                    var property = (from member in classDeclaration.DeclaredElement.GetMembers().OfType<IProperty>() where member.ShortName == propertyName select member).FirstOrDefault();
                    if (property != null)
                    {
                        propertyDeclaration = (IPropertyDeclaration) property.GetDeclarations().FirstOrDefault();
                    }
                }
            }

            return propertyDeclaration;
        }
Exemplo n.º 2
0
 private UnitTestElementLocation GetUnitTestElementLocation(IClassDeclaration declaration)
 {
     var navigationRange = declaration.GetNameDocumentRange().TextRange;
       var containingRange = declaration.GetDocumentRange().TextRange;
       var projectFile = declaration.GetContainingFile().AssertNotNull().GetSourceFile().ToProjectFile();
       return new UnitTestElementLocation(projectFile, navigationRange, containingRange);
 }
 public override bool IsAvailable(IUserDataHolder cache)
 {
     myClassDeclaration = myProvider.GetSelectedElement<IClassDeclaration>(true, true);
       // this context action is available on every class at the moment
       // TODO: add some constraints, like: there is already a test for this class
       return myClassDeclaration != null;
 }
Exemplo n.º 4
0
        public PropertyConverter(CSharpElementFactory factory, IPsiModule psiModule, IClassDeclaration classDeclaration)
        {
            Argument.IsNotNull(() => factory);
            Argument.IsNotNull(() => psiModule);
            Argument.IsNotNull(() => classDeclaration);

            _factory = factory;
            _psiModule = psiModule;
            _classDeclaration = classDeclaration;
        }
        private void ImplementInterfaceOrBaseClass(IClassDeclaration contractClass, IProgressIndicator progress)
        {
            
            string generateKind = GeneratorStandardKinds.Implementations;
            if (_addContractForAvailability.IsAbstractClass)
                generateKind = GeneratorStandardKinds.Overrides;

            using (var workflow = GeneratorWorkflowFactory.CreateWorkflowWithoutTextControl(
                generateKind,
                contractClass,
                contractClass))
                //_addContractForAvailability.TypeDeclaration))
            {
                Contract.Assert(workflow != null);

                

                workflow.Context.SetGlobalOptionValue(CSharpBuilderOptions.PropertyBody,
                    CSharpBuilderOptions.PropertyBodyDefault);

                workflow.Context.SetGlobalOptionValue(
                  CSharpBuilderOptions.ImplementationKind,
                  CSharpBuilderOptions.ImplementationKindExplicit);
                
                //var globalActions = workflow.Context.GlobalOptions;
                //var dd = globalActions
                //    .FirstOrDefault(g => g.ID == CSharpBuilderOptions.ImplementationKind);
                //if (dd != null)
                //{
                //    dd.OverridesGlobalOption = true;
                //    dd.Value = CSharpBuilderOptions.ImplementationKindPublicMember;
                //}

                workflow.Context.Anchor = contractClass;
                workflow.Context.InputElements.Clear();

                Contract.Assert(workflow.Context.ProvidedElements.Count != 0);
                workflow.Context.InputElements.AddRange(workflow.Context.ProvidedElements);
                //foreach (var e in workflow.Context.ProvidedElements)
                //{
                //    workflow.Context.InputElements.Add(e);
                //}


                //workflow.Context.GlobalOptions.Clear();
                
                

                

                workflow.GenerateAndFinish("Generate contract class", progress);
            }
        }
Exemplo n.º 6
0
 public ClassTestDeclaration(
 IIdentity identity,
 IProject project,
 string text,
 IEnumerable<ITestDeclaration> testDeclarations,
 IClassDeclaration classDeclaration)
     : base(classDeclaration)
 {
     _identity = identity;
       _project = project;
       _text = text;
       _testDeclarations = testDeclarations;
 }
Exemplo n.º 7
0
        public string Present(IClassDeclaration classDeclaration)
        {
            var clazz = (IClass) classDeclaration.DeclaredElement;

              var subjectAttributeData = clazz.GetAttributeData<SubjectAttributeBase>();
              if (subjectAttributeData == null)
            return null;

              var subjectAttribute = subjectAttributeData.ToCommon();
              var subjectAttributeClass = subjectAttributeData.GetAttributeType().GetTypeElement<IClass>().AssertNotNull();
              var subjectAttributeConstructor = subjectAttributeClass.Constructors.Single();
              var displayFormatAttribute = subjectAttributeConstructor.GetAttributeData<DisplayFormatAttribute>().ToCommon();
              return _introspectionPresenter.Present(displayFormatAttribute, subjectAttribute);
        }
Exemplo n.º 8
0
        public string Present(IClassDeclaration classDeclaration)
        {
            var clazz = (IClass) classDeclaration.DeclaredElement;

              var subjectAttributeData = clazz.GetAttributeData<SuiteAttributeBase>();
              if (subjectAttributeData == null)
            return null;

              var subjectAttribute = subjectAttributeData.ToCommon();

              var subjectAttributeConstructor = subjectAttributeData.Constructor;
              var displayFormatAttribute = subjectAttributeConstructor.GetAttributeData<DisplayFormatAttribute>().ToCommon();

              return _introspectionPresenter.Present(displayFormatAttribute, clazz.ToCommon(), subjectAttribute);
        }
        public override bool IsAvailable(IUserDataHolder cache)
        {
            using (ReadLockCookie.Create())
            {
                if (Provider.SelectedElement != null)
                {
                    _superType = TypeHelper.CreateTypeByCLRName(SuperTypeName, Provider.PsiModule, Provider.SelectedElement.GetResolveContext());
                    if (_superType.GetTypeElement() != null)
                    {
                        _classDeclaration = Provider.SelectedElement.Parent as IClassDeclaration;
                    }
                }
            }

            // !_classDeclaration.IsStatic doesn't work, IsStatic is returns true
            return _classDeclaration != null && !_classDeclaration.IsStaticEx() && _classDeclaration.SuperTypes.IsEmpty();
        }
        private void SetClassAndMembersUsed(IClassDeclaration classDeclaration)
        {
            ITypeElement typeElement = classDeclaration.DeclaredElement;
            if (typeElement == null || (typeElement is IClass == false))
            {
                return;
            }

            foreach (ITypeMember typeMember in typeElement.GetMembers())
            {
                var method = typeMember as IMethod;
                if (method != null)
                {
                    usages.SetElementState(method, UsageState.ALL_MASK);
                }
            }

            usages.SetElementState(typeElement, UsageState.ALL_MASK);
        }
Exemplo n.º 11
0
		public override void VisitClassDeclaration(IClassDeclaration classDeclarationParam, IHighlightingConsumer context) {
			base.VisitClassDeclaration(classDeclarationParam, context);

			if (!classDeclarationParam.IsSynthetic()
			|| !T4CSharpCodeGenerator.ClassName.Equals(classDeclarationParam.DeclaredName, StringComparison.Ordinal))
				return;

			IDeclaredTypeUsage superTypeUsage = classDeclarationParam.SuperTypeUsageNodes.FirstOrDefault();
			if (superTypeUsage == null
			|| T4CSharpCodeGenerator.DefaultBaseClassName.Equals(superTypeUsage.GetText(), StringComparison.Ordinal))
				return;

			ITypeElement typeElement = CSharpTypeFactory.CreateDeclaredType(superTypeUsage).GetTypeElement();
			if (typeElement == null)
				return;

			if (!typeElement.Methods.Any(IsTransformTextMethod))
				context.AddHighlighting(new MissingTransformTextMethodHighlighting(superTypeUsage));
		}
Exemplo n.º 12
0
        public override bool IsAvailable(IUserDataHolder cache)
        {
            //reset
            this._class = null;

            ITreeNode element = this._actionDataProvider.SelectedElement;

            if (null == element)
            {
                return false;
            }

            this._class = element.Parent as IClassDeclaration;

            if (null == this._class)
            {
                return false;
            }

            return this.HasDataMembers(this._class);
        }
        public override sealed bool IsAvailable(IUserDataHolder cache)
        {
            using (ReadLockCookie.Create())
            {
                var selectedElement = Provider.SelectedElement;
                var moduleReferenceResolveContext = selectedElement.GetResolveContext();
                if (selectedElement != null && selectedElement.Parent is IPropertyDeclaration)
                {
                    _propertyDeclaration = selectedElement.Parent as IPropertyDeclaration;
                    if (_propertyDeclaration.IsAuto && _propertyDeclaration.Parent != null
                        && _propertyDeclaration.Parent.Parent is IClassDeclaration)
                    {
                        _classDeclaration = _propertyDeclaration.Parent.Parent as IClassDeclaration;
                    }
                }
            }

            return _classDeclaration != null && _classDeclaration.DeclaredElement != null
                   && (_classDeclaration.DeclaredElement.IsDescendantOf(CatelCore.GetDataObjectBaseTypeElement(Provider.PsiModule, _classDeclaration.GetResolveContext()))
                       || _classDeclaration.DeclaredElement.IsDescendantOf(CatelCore.GetModelBaseTypeElement(Provider.PsiModule, _classDeclaration.GetResolveContext())));
        }
        private void ImplementContractForAbstractClass(IClassDeclaration contractClass,
            IClassDeclaration abstractClass)
        {
            Contract.Requires(contractClass != null);
            Contract.Requires(contractClass.DeclaredElement != null);
            Contract.Requires(abstractClass != null);
            Contract.Requires(abstractClass.DeclaredElement != null);

            using (var workflow = GeneratorWorkflowFactory.CreateWorkflowWithoutTextControl(
                GeneratorStandardKinds.Overrides,
                contractClass,
                abstractClass))
            {
                Contract.Assert(workflow != null);

                // By default this input for this workflow contains too many members:
                // It contains member from the base class (required) and
                // members from the other base classes (i.e. from System.Object).
                // Using some hack to get only members defined in the "abstractClass"

                // So I'm trying to find required elements myself.

                var missingMembers = contractClass.GetMissingMembersOf(abstractClass);
                
                if (_requiredFunction != null)
                {
                    var requiredDeclaration = _requiredFunction.DeclaredElement;
                    missingMembers = 
                        missingMembers.Where(x => GetMembers(x).Any(m => m.Equals(requiredDeclaration)))
                            .ToList();

                    Contract.Assert(missingMembers.Count != 0, "Should be at least one method to add!");
                }

                var membersToOverride =
                    missingMembers
                        .Select(x => new GeneratorDeclaredElement<IOverridableMember>(x.Member, x.Substitution))
                        .ToList();

                workflow.Context.InputElements.Clear();

                workflow.Context.ProvidedElements.Clear();
                workflow.Context.ProvidedElements.AddRange(membersToOverride);

                workflow.Context.InputElements.AddRange(workflow.Context.ProvidedElements);

                workflow.Generate("Generate contract class", NullProgressIndicator.Instance);
            }
        }
Exemplo n.º 15
0
        private IClassDeclaration ImplementINotifyPropertyChangedInterface(IClassDeclaration viewModel, IClassDeclaration wrappedClass)
        {
            UsingDirectiveHelper.AddUsingDirectiveIfNeeded(wrappedClass, "System", "ComponentModel");

            IConstructLanguage language   = viewModel.Language;
            IIdentifier        identifier = language.Identifier(PropertyChangedSimpleTypeName);
            ITypeName          typeName   = language.SimpleTypeName(identifier, language.None <ITypeArguments>());

            viewModel.IntroduceInterface(typeName);

            wrappedClass.Append(viewModel);
            string name = viewModel.Identifier.Name;

            viewModel = RebuildSolutionModel(wrappedClass, name);

            AddStubsHelper.CreateAllUnimplementedMembers(viewModel, new AddStubsOptions());

            return(RebuildSolutionModel(wrappedClass, name));
        }
Exemplo n.º 16
0
 public static bool HasAnyGetSetProperty([CanBeNull] this IClassDeclaration classDeclaration)
 {
     return(classDeclaration != null && classDeclaration.PropertyDeclarations.Any(x => x.HasGetSet()));
 }
Exemplo n.º 17
0
 public SqlScriptIndexByMethodGeneratorContextAction(ICSharpContextActionDataProvider provider)
 {
     factory           = provider.ElementFactory;
     methodDeclaration = provider.GetSelectedElement <IMethodDeclaration>();
     classDeclaration  = provider.GetSelectedElement <IClassDeclaration>();
 }
 private void AddContractClassForAbstractClass(IClassDeclaration classDeclaration)
 {
     throw new System.NotImplementedException();
 }
        private void InsertWrappedProperties(IClassDeclaration viewModel, List<IPropertyDeclaration> confirmedPropertiesForWrapping, IFieldDeclaration wrappedClassField, IIdentifier onPropertyChangedIdentifier)
        {
            IConstructLanguage language = viewModel.Language;

            foreach (IPropertyDeclaration property in confirmedPropertiesForWrapping)
            {
                IMemberAccess propertyMemberAccess = language.MemberAccess(
                    language.MemberAccess(language.None<IExpression>(), wrappedClassField.Identifier),
                    property.Identifier);

                IAccessor getterOfWrapper = language.None<IAccessor>();
                IAccessor propertyGetter = property.Getter();

                if (propertyGetter.Exists && IsAccessorVisibleOutsideClass(propertyGetter.Modifiers))
                {
                    getterOfWrapper = language.Getter(
                        language.Modifiers(propertyGetter.Modifiers.Modifiers),
                        language.Block(
                            language.ReturnStatement(propertyMemberAccess)));
                }

                IAccessor setterOfWrapper = language.None<IAccessor>();
                IAccessor propertySetter = property.Setter();

                if (propertySetter.Exists && IsAccessorVisibleOutsideClass(propertySetter.Modifiers))
                {
                    IStatement assignment = language.AssignmentStatement(propertyMemberAccess, language.Expression("value"));

                    IMethodInvocation onPropertyChangedInvocation =
                        language.MethodInvocation(
                            language.None<IExpression>(),
                            onPropertyChangedIdentifier,
                            language.None<ITypeArguments>(),
                            language.Arguments(
                                language.Argument(language.StringLiteral(property.Identifier.Name))));

                    IIfStatement ifStatement =
                        language.IfStatement(
                            language.BinaryExpression(propertyMemberAccess,
                                Operator.NotEqual,
                                language.Expression("value")),
                            language.Block(assignment, language.ExpressionStatement(onPropertyChangedInvocation)));

                    setterOfWrapper = language.Setter(
                        language.Modifiers(propertyGetter.Modifiers.Modifiers),
                        language.Block(ifStatement));
                }

                if (getterOfWrapper.Exists || setterOfWrapper.Exists)
                {
                    IPropertyDeclaration wrapperProperty = language.Property(
                                                            language.None<IDocComment>(),
                                                            language.None<IAttributes>(),
                                                            property.Modifiers,
                                                            property.TypeName,
                                                            property.Identifier,
                                                            getterOfWrapper,
                                                            setterOfWrapper);
                    viewModel.Insert(wrapperProperty);
                }
            }
        }
 private void AddContractClassAttributeIfNeeded(IClassDeclaration contractClass)
 {
     if (!_addContractForAvailability.TypeDeclaration.HasAttribute(typeof (ContractClassAttribute)))
     {
         var attribute = CreateContractClassAttribute(contractClass);
         _addContractForAvailability.TypeDeclaration.AddAttributeAfter(attribute, null);
     }
 }
Exemplo n.º 21
0
 public IBulbAction[] GetClassFixes(IClassDeclaration declaration)
 {
     return(null);
 }
 public ClassNameWarning(IClassDeclaration classDeclaration, DocumentRange documentRange)
 {
     m_ClassDeclaration = classDeclaration;
     m_DocumentRange    = documentRange;
 }
Exemplo n.º 23
0
 protected ClassDeclarationBase(IClassDeclaration classDeclaration)
     : base(classDeclaration)
 {
     _classDeclaration = classDeclaration;
 }
Exemplo n.º 24
0
        private IFieldDeclaration CreateFieldToHoldWrappedClass(IConstructLanguage language, ITypeName typeName, IClassDeclaration classDeclaration)
        {
            IFieldDeclaration fieldDeclaration   = language.Field(language.Modifiers(Modifiers.Private | Modifiers.Readonly), typeName);
            NamingPolicy      fieldsNamingPolicy = fieldDeclaration.PrimaryNamingPolicy(classDeclaration.FileModel.UserSettings);
            string            fieldName          = fieldsNamingPolicy.ChangeNameAccordingToPolicy(classDeclaration.Identifier.Name, classDeclaration.Language, classDeclaration.FileModel);

            fieldDeclaration.Identifier = language.Identifier(fieldName);
            return(fieldDeclaration);
        }
 private void ImplementInterfaceOrBaseClass(IClassDeclaration contractClass)
 {
     if (_addContractForAvailability.IsAbstractClass)
     {
         ImplementContractForAbstractClass(contractClass, _addContractForAvailability.ClassDeclaration);
     }
     else
     {
         ImplementContractForInterface(contractClass, _addContractForAvailability.InterfaceDeclaration);
     }
 }
        /// <summary>
        /// Adds <paramref name="contractClass"/> after implemented interface into the physical tree.
        /// </summary>
        /// <remarks>
        /// This method is absolutely crucial, because all R# "generate workflows" works correcntly
        /// only if TreeNode.IsPhysical() returns true.
        /// </remarks>
        private IClassDeclaration AddToPhysicalDeclaration(IClassDeclaration contractClass)
        {
            var holder = CSharpTypeAndNamespaceHolderDeclarationNavigator.GetByTypeDeclaration(
                _addContractForAvailability.TypeDeclaration);
            Contract.Assert(holder != null);
            
            var physicalContractClassDeclaration =
                (IClassDeclaration) holder.AddTypeDeclarationAfter(contractClass,
                    _addContractForAvailability.TypeDeclaration);

            return physicalContractClassDeclaration;
        }
Exemplo n.º 27
0
        private static void AddMocksToClassDeclaration(IMethodDeclaration methodDeclaration, IObjectCreationExpression ctorExpression, MockInfo[] mockInfos, IClassDeclaration classDeclaration, CSharpElementFactory factory)
        {
            var ctorStatement = methodDeclaration.Body.Statements
                                .FirstOrDefault(x =>
            {
                var expression = (x as IExpressionStatement)?.Expression;
                if (expression != null && (expression == ctorExpression || (expression as IAssignmentExpression)?.Source == ctorExpression))
                {
                    return(true);
                }

                var declarationStatement = (x as IDeclarationStatement);
                if (declarationStatement?.VariableDeclarations.Any(varDeclaration => (varDeclaration.Initial as IExpressionInitializer)?.Value == ctorExpression) ?? false)
                {
                    return(true);
                }

                return(false);
            });

            foreach (var mockInfo in mockInfos)
            {
                classDeclaration.AddMemberDeclaration(mockInfo.Type, mockInfo.Name, factory, m => m.All(x => x.DeclaredName != mockInfo.Name));

                var elementHasAssigned = methodDeclaration.Body.Statements.Any(x =>
                {
                    var assignmentOperands = ((x as IExpressionStatement)?.Expression as IAssignmentExpression)?.OperatorOperands;
                    return(assignmentOperands != null && assignmentOperands.Any(operand => (operand as IReferenceExpression)?.NameIdentifier.Name == mockInfo.Name));
                });

                if (!elementHasAssigned)
                {
                    methodDeclaration.Body.AddStatementBefore(mockInfo.Statement, ctorStatement);
                }
            }
        }
Exemplo n.º 28
0
 public SqlMapGeneratorContextAction(ICSharpContextActionDataProvider provider)
 {
     this.provider    = provider;
     factory          = provider.ElementFactory;
     classDeclaration = provider.GetSelectedElement <IClassDeclaration>();
 }
Exemplo n.º 29
0
        private void InsertWrappedProperties(IClassDeclaration viewModel, List <IPropertyDeclaration> confirmedPropertiesForWrapping, IFieldDeclaration wrappedClassField, IIdentifier onPropertyChangedIdentifier)
        {
            IConstructLanguage language = viewModel.Language;

            foreach (IPropertyDeclaration property in confirmedPropertiesForWrapping)
            {
                IMemberAccess propertyMemberAccess = language.MemberAccess(
                    language.MemberAccess(language.None <IExpression>(), wrappedClassField.Identifier),
                    property.Identifier);

                IAccessor getterOfWrapper = language.None <IAccessor>();
                IAccessor propertyGetter  = property.Getter();

                if (propertyGetter.Exists && IsAccessorVisibleOutsideClass(propertyGetter.Modifiers))
                {
                    getterOfWrapper = language.Getter(
                        language.Modifiers(propertyGetter.Modifiers.Modifiers),
                        language.Block(
                            language.ReturnStatement(propertyMemberAccess)));
                }

                IAccessor setterOfWrapper = language.None <IAccessor>();
                IAccessor propertySetter  = property.Setter();

                if (propertySetter.Exists && IsAccessorVisibleOutsideClass(propertySetter.Modifiers))
                {
                    IStatement assignment = language.AssignmentStatement(propertyMemberAccess, language.Expression("value"));

                    IMethodInvocation onPropertyChangedInvocation =
                        language.MethodInvocation(
                            language.None <IExpression>(),
                            onPropertyChangedIdentifier,
                            language.None <ITypeArguments>(),
                            language.Arguments(
                                language.Argument(language.StringLiteral(property.Identifier.Name))));

                    IIfStatement ifStatement =
                        language.IfStatement(
                            language.BinaryExpression(propertyMemberAccess,
                                                      Operator.NotEqual,
                                                      language.Expression("value")),
                            language.Block(assignment, language.ExpressionStatement(onPropertyChangedInvocation)));

                    setterOfWrapper = language.Setter(
                        language.Modifiers(propertyGetter.Modifiers.Modifiers),
                        language.Block(ifStatement));
                }

                if (getterOfWrapper.Exists || setterOfWrapper.Exists)
                {
                    IPropertyDeclaration wrapperProperty = language.Property(
                        language.None <IDocComment>(),
                        language.None <IAttributes>(),
                        property.Modifiers,
                        property.TypeName,
                        property.Identifier,
                        getterOfWrapper,
                        setterOfWrapper);
                    viewModel.Insert(wrapperProperty);
                }
            }
        }
 private IClassDeclaration RebuildSolutionModel(IClassDeclaration wrappedClass, string name)
 {
     wrappedClass.SolutionModel.RebuildWithCurrentModifications();
     IClassDeclaration viewModel = wrappedClass.FileModel.All<IClassDeclaration>().First(c => string.Equals(c.Identifier.Name, name, System.StringComparison.Ordinal));
     return viewModel;
 }
Exemplo n.º 31
0
 private bool ImplementsINotifyPropertyChanged(IClassDeclaration classDeclaration)
 {
     return(classDeclaration.Type().AllSuperTypesIncludingThis.Any(t => t.Is(PropertyChangedQualifiedTypeName)));
 }
        private void AddContractClassForInterface(IClassDeclaration classDeclaration)
        {
            Contract.Assert(_addContractForAvailability.InterfaceDeclaration.DeclaredElement != null);
            var interfaceType = TypeFactory.CreateType(_addContractForAvailability.InterfaceDeclaration.DeclaredElement);
            
            classDeclaration.AddSuperInterface(interfaceType, false);

            //var interfaceDeclaration = _addContractForAvailability.InterfaceDeclaration;
            //IClassMemberDeclaration previousDeclaration = null;
            //foreach (var memberDeclaration in interfaceDeclaration.ClassMemberDeclarations)
            //{
                
            //    classDeclaration.AddClassMemberDeclarationAfter(memberDeclaration, previousDeclaration);

            //    previousDeclaration = memberDeclaration;
            //}

        }
 public void SelectedClassProviderExpectGetValueOrDefault(IClassDeclaration result)
 {
     SelectedClassProvider.Expects.One
     .MethodWith(o => o.GetValueOrDefault())
     .WillReturn(result);
 }
Exemplo n.º 34
0
 public override void VisitClassDeclaration(IClassDeclaration classDecl)
 {
     //Result.Parent = classDecl;
     // TODO add type for type completion
 }
Exemplo n.º 35
0
 private IConstructEnumerable <IMemberDeclaration> GetPropertiesForWrapping(IClassDeclaration classDeclaration)
 {
     return(classDeclaration.ContainedMembers().Where(m => m.Is <IPropertyDeclaration>() && IsPropertyVisibleOutsideClass(m.Modifiers)));
 }
Exemplo n.º 36
0
 public bool ShouldFollowPattern(IClassDeclaration declaration)
 {
     return(false);
 }
        private void AddContractClassForAttributeTo(IClassDeclaration contractClass)
        {
            var attribute = CreateContractClassForAttribute(_addContractForAvailability.TypeDeclaration);

            contractClass.AddAttributeAfter(attribute, null);
        }
 public SqlRepositoryGeneratorContextAction([NotNull] ICSharpContextActionDataProvider provider)
 {
     factory          = provider.ElementFactory;
     classDeclaration = provider.GetSelectedElement <IClassDeclaration>();
 }
 public AddRequireComponentBulbActionBase(IType type, IClassDeclaration classDeclaration)
 {
     myType             = type;
     myClassDeclaration = classDeclaration;
     myFactory          = CSharpElementFactory.GetInstance(classDeclaration);
 }
Exemplo n.º 40
0
 private void AddContractClassForAbstractClass(IClassDeclaration classDeclaration)
 {
     throw new System.NotImplementedException();
 }
 public override void VisitClassDeclaration(IClassDeclaration classDeclaration, IHighlightingConsumer context)
 {
     classTooBigCheck.ExecuteIfEnabled(classDeclaration, context);
 }
Exemplo n.º 42
0
        public string Present(IClassDeclaration classDeclaration, string suiteAttributeType)
        {
            var clazz = (IClass)classDeclaration.DeclaredElement;

            return(Present(suiteAttributeType, clazz));
        }
        private static void AddProxyClass(IClassDeclaration classDeclaration, CSharpElementFactory factory)
        {
            var builderType = string.Format("{0}Builder", classDeclaration.DeclaredName);

            var code = new StringBuilder(string.Format("public class {0} {{", builderType));

            code.AppendLine();
            var cls = classDeclaration.DeclaredElement as IClass;

            if (cls == null)
            {
                return;
            }

            var ctor = cls.Constructors.OrderByDescending(x => x.Parameters.Count).FirstOrDefault();

            if (ctor == null)
            {
                return;
            }

            var fields  = new StringBuilder();
            var methods = new StringBuilder();

            foreach (var parameter in ctor.Parameters)
            {
                var typePresentableName  = parameter.Type.GetPresentableName(cls.PresentationLanguage);
                var shortName            = parameter.ShortName;
                var capitalizedShortName = shortName.Capitalize();

                fields.AppendLine("private {0} _{1};", typePresentableName, shortName);
                methods.AppendLine("public {2} With{1}({0} value){{ ", typePresentableName, capitalizedShortName, builderType);
                methods.AppendLine(" _{0} = value;", shortName);
                methods.AppendLine("return this;");
                methods.AppendLine("}");
                methods.AppendLine();

                if (parameter.Type.IsGenericIEnumerable())
                {
                    var genericParameter = typePresentableName.Split(new[] { '<', '>' })[1];
                    var listType         = string.Format("List<{0}>", genericParameter);
                    var singularName     = NounUtil.GetSingular(capitalizedShortName);

                    methods.AppendLine("public {0} Add{1}({2} value){{", builderType, singularName, genericParameter);
                    methods.AppendLine(" if(_{0} == null){{", shortName);
                    methods.AppendLine("  _{0} = new {1}();", shortName, listType);
                    methods.AppendLine(" }");
                    methods.AppendLine("  var collection = _{0} as ICollection<{1}>;", shortName, genericParameter);
                    methods.AppendLine("  if (collection == null || collection.IsReadOnly){");
                    methods.AppendLine("     throw new InvalidOperationException(\"Add{0}() method cannot be used with this collection type\");", singularName);
                    methods.AppendLine("  }");
                    methods.AppendLine(" collection.Add(value);");
                    methods.AppendLine(" return this;");
                    methods.AppendLine("}");
                    methods.AppendLine();
                }
            }

            code.Append(fields);
            code.Append(methods);


            code.AppendLine("public {0} Build(){{", classDeclaration.DeclaredName);
            code.AppendFormat("return new  {0}(", classDeclaration.DeclaredName);
            code.Append(ctor.Parameters.Select(x => string.Format("_{0}", x.ShortName)).ToArray().Join(", "));
            code.AppendLine(");");
            code.AppendLine("}");


            code.Append("}");

            var memberDeclaration = factory.CreateTypeMemberDeclaration(code.ToString()) as IClassDeclaration;

            var namespaceDeclaration = classDeclaration.GetContainingNamespaceDeclaration();

            namespaceDeclaration.AddTypeDeclarationAfter(memberDeclaration, classDeclaration);
        }
 public void IsClassHasTestClassAttributeExpectValidate(IClassDeclaration classDeclaration, bool result)
 {
     IsClassHasTestClassAttribute.Expects.One
     .MethodWith(o => o.Validate(classDeclaration))
     .WillReturn(result);
 }
Exemplo n.º 45
0
 public SqlScriptGeneratorContextAction(ICSharpContextActionDataProvider provider)
 {
     factory             = provider.ElementFactory;
     classDeclaration    = provider.GetSelectedElement <IClassDeclaration>();;
     propertyDeclaration = provider.GetSelectedElement <IPropertyDeclaration>();
 }
 private bool ImplementsINotifyPropertyChanged(IClassDeclaration classDeclaration)
 {
     return classDeclaration.Type().AllSuperTypesIncludingThis.Any(t => t.Is(PropertyChangedQualifiedTypeName));
 }
Exemplo n.º 47
0
 public IBulbAction[] GetClassFixes(IClassDeclaration declaration)
 {
     return(new IBulbAction[] { new AddDataContractAttribute(declaration) });
 }
 private void AddExcludeFromCodeCoverageAttributeIfNeeded(IClassDeclaration contractClass)
 {
     if (ShouldUseExcludeFromCodeCoverageAttribute())
     { 
         var attribute = CreateExcludeFromCodeCoverageAttribute();
         contractClass.AddAttributeAfter(attribute, null);
     }
 }
Exemplo n.º 49
0
        public bool ShouldFollowPattern(IClassDeclaration declaration)
        {
            var name = declaration.DeclaredName;

            return(name.EndsWith("Model") || name.EndsWith("Config") || name.EndsWith("ConfigSection"));
        }
        private void ImplementContractForInterface(IClassDeclaration contractClass,
            IInterfaceDeclaration interfaceDeclaration)
        {
            Contract.Requires(contractClass != null);
            Contract.Requires(interfaceDeclaration != null);

            if (interfaceDeclaration.MemberDeclarations.Count == 0)
                return;

            using (var workflow = GeneratorWorkflowFactory.CreateWorkflowWithoutTextControl(
                GeneratorStandardKinds.MissingMembers,
                contractClass,
                interfaceDeclaration))
            {
                Contract.Assert(workflow != null);

                workflow.Context.InputElements.Clear();
                workflow.Context.InputElements.AddRange(workflow.Context.ProvidedElements);

                workflow.Context.SetOption(
                    CSharpBuilderOptions.ImplementationKind,
                    CSharpBuilderOptions.ImplementationKindExplicit);

                workflow.Generate("Generate contract class", NullProgressIndicator.Instance);
            }
        }
 private IConstructEnumerable<IMemberDeclaration> GetPropertiesForWrapping(IClassDeclaration classDeclaration)
 {
     return classDeclaration.ContainedMembers().Where(m => m.Is<IPropertyDeclaration>() && IsPropertyVisibleOutsideClass(m.Modifiers));
 }
        private void AddNonDefaultConstructorIfNeeded(IClassDeclaration contractClass)
        {
            if (!_addContractForAvailability.IsAbstractClass)
                return;

            var abstractBaseClass = _addContractForAvailability.ClassDeclaration;

            using (var workflow = GeneratorWorkflowFactory.CreateWorkflowWithoutTextControl(
                GeneratorStandardKinds.Constructor,
                contractClass,
                abstractBaseClass))
            {
                Contract.Assert(workflow != null);

                var ctor = 
                    workflow.Context.ProvidedElements
                    .OfType<GeneratorDeclaredElement<IConstructor>>()
                    .FirstOrDefault(c => !c.DeclaredElement.IsDefault);

                if (ctor != null)
                { 
                    workflow.Context.InputElements.Clear();
                    workflow.Context.InputElements.Add(ctor);
                    workflow.BuildOptions();
                    workflow.Generate("Generate missing constructor", NullProgressIndicator.Instance);
                }
            }

        }
        private List<IPropertyDeclaration> GetPropertiesForWrappingByName(IClassDeclaration classDeclaration, List<string> confirmedPropertiesNamesForWrapping)
        {
            List<IPropertyDeclaration> properties = new List<IPropertyDeclaration>();
            IConstructEnumerable<IDeclaration> containedDeclarations = classDeclaration.ContainedDeclarations;

            foreach (string propertyName in confirmedPropertiesNamesForWrapping)
            {
                IPropertyDeclaration property = containedDeclarations.First(d => string.Equals(propertyName, d.Identifier.Name, StringComparison.Ordinal))
                    .As<IPropertyDeclaration>();
                if (property.Exists)
                {
                    properties.Add(property);
                }
            }

            return properties;
        }
        private IAttribute CreateContractClassAttribute(IClassDeclaration contractClass)
        {
            ITypeElement attributeType = TypeFactory.CreateTypeByCLRName(
                typeof(ContractClassAttribute).FullName,
                _provider.PsiModule, _currentFile.GetResolveContext()).GetTypeElement();

            var declaredType = contractClass.DeclaredElement;
            var typeofExpression = _factory.CreateExpression("typeof($0)", declaredType);

            var attribute = _factory.CreateAttribute(attributeType);

            attribute.AddArgumentAfter(
                _factory.CreateArgument(ParameterKind.VALUE, typeofExpression),
                null);

            return attribute;
        }
        private IClassDeclaration ImplementINotifyPropertyChangedInterface(IClassDeclaration viewModel, IClassDeclaration wrappedClass)
        {
            UsingDirectiveHelper.AddUsingDirectiveIfNeeded(wrappedClass, "System", "ComponentModel");

            IConstructLanguage language = viewModel.Language;
            IIdentifier identifier = language.Identifier(PropertyChangedSimpleTypeName);
            ITypeName typeName = language.SimpleTypeName(identifier, language.None<ITypeArguments>());
            viewModel.IntroduceInterface(typeName);

            wrappedClass.Append(viewModel);
            string name = viewModel.Identifier.Name;
            viewModel = RebuildSolutionModel(wrappedClass, name);

            AddStubsHelper.CreateAllUnimplementedMembers(viewModel, new AddStubsOptions());

            return RebuildSolutionModel(wrappedClass, name);
        }
 private void AddContractClassForAttributeTo(IClassDeclaration contractClass)
 {
     var attribute = CreateContractClassForAttribute(_addContractForAvailability.TypeDeclaration);
     contractClass.AddAttributeAfter(attribute, null);
 }
Exemplo n.º 57
0
 public MvvmInspectionsConvertViewModel(LanguageIndependentContextActionDataProvider dataProvider)
 {
     _classDeclaration = dataProvider.GetSelectedElement <IClassDeclaration>();
 }