Esempio n. 1
0
        public override void EmitName()
        {
            var classBuilder = this.ConstructorContext.ClassContext.GetTypeBuilder();

            if (classBuilder == null)
            {
                throw new CCException();
            }
            bool               isStatic = this.ConstructorContext.IsStatic();
            MethodAttributes   methodAttributes;
            CallingConventions callingConventions;

            if (isStatic)
            {
                methodAttributes   = MethodAttributes.Private | MethodAttributes.Static;
                callingConventions = CallingConventions.Standard;
            }
            else
            {
                methodAttributes   = MethodAttributes.Public;
                callingConventions = CallingConventions.HasThis;
            }
            var argTypes = new Type[] { };
            ConstructorBuilder constructorBuilder = classBuilder.DefineConstructor(methodAttributes, callingConventions, argTypes);

            ConstructorContext.SetBuilder(constructorBuilder);
        }
Esempio n. 2
0
        public override void EmitName()
        {
            var                classBuilder = this.ConstructorContext.ClassContext.GetTypeBuilder();
            bool               isStatic     = this.ConstructorContext.IsStatic();
            MethodAttributes   methodAttributes;
            CallingConventions callingConventions;

            if (isStatic)
            {
                methodAttributes   = MethodAttributes.Private | MethodAttributes.Static;
                callingConventions = CallingConventions.Standard;
            }
            else
            {
                methodAttributes   = MethodAttributes.Public;
                callingConventions = CallingConventions.HasThis;
            }
            var argTypes = this.ConstructorContext.ZConstructorInfo.GetParameterTypes();// this.constructorDesc.GetParamTypes();
            ConstructorBuilder constructorBuilder = classBuilder.DefineConstructor(methodAttributes, callingConventions, argTypes);

            ConstructorContext.SetBuilder(constructorBuilder);

            var normalArgs = this.ConstructorContext.ZConstructorInfo.GetNormalParameters();
            int start_i    = isStatic ? 0 : 1;

            for (var i = 0; i < normalArgs.Length; i++)
            {
                constructorBuilder.DefineParameter(i + start_i, ParameterAttributes.None, normalArgs[i].GetZParamName());
            }
        }
        public void UnmockableTypesAreRejectedInNew()
        {
            var context = new ConstructorContext <SingleConstructorClass>();

            // Ints are not mockable: var value = context.Inject(123);

            Assert.Throws <ArgumentException>(() => context.New());
        }
        public void NewMayOnlyBeCalledOnce()
        {
            var context = new ConstructorContext <SingleConstructorClass>();

            context.Inject(123);

            context.New();
            Assert.Throws <InvalidOperationException>(() => context.New());
        }
        public void UninjectedMockableTypesAreMockedAutomatically()
        {
            var context = new ConstructorContext <SingleConstructorClass>();
            var value   = context.Inject(123);

            var obj = context.New();

            Assert.IsNotNull(obj.Dep1);
            Assert.IsNotNull(obj.Dep2);
            Assert.AreEqual(value, obj.Value);
        }
Esempio n. 6
0
        public static void Start()
        {
            if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                Navigator.AddSettings(new List <EntitySettings>
                {
                    new EntitySettings <SMSMessageEntity> {
                        View = e => new SMSMessage(), Icon = ExtensionsImageLoader.GetImageSortName("sms.png")
                    },
                    new EntitySettings <SMSTemplateEntity> {
                        View = e => new SMSTemplate(), Icon = ExtensionsImageLoader.GetImageSortName("smstemplate.png")
                    },
                    new EmbeddedEntitySettings <SMSTemplateMessageEmbedded>()
                    {
                        View = e => new Signum.Windows.SMS.SMSTemplateMessage()
                    },
                    new EntitySettings <SMSSendPackageEntity> {
                        View = e => new SMSSendPackage(), Icon = ExtensionsImageLoader.GetImageSortName("package.png")
                    },
                    new EntitySettings <SMSUpdatePackageEntity> {
                        View = e => new SMSUpdatePackage(), Icon = ExtensionsImageLoader.GetImageSortName("package.png")
                    },
                    new ModelEntitySettings <MultipleSMSModel> {
                        View = e => new MultipleSMS(), Icon = ExtensionsImageLoader.GetImageSortName("package.png")
                    },
                });

                OperationClient.AddSetting(new EntityOperationSettings <Entity>(SMSMessageOperation.CreateSMSWithTemplateFromEntity)
                {
                    Click = FindAssociatedTemplates
                });

                OperationClient.AddSetting(new ContextualOperationSettings <Entity>(SMSMessageOperation.SendSMSMessages)
                {
                    Click = coc =>
                    {
                        MultipleSMSModel model = Navigator.View(new MultipleSMSModel());

                        if (model == null)
                        {
                            return;
                        }

                        var result = new ConstructorContext(coc.SearchControl, coc.OperationInfo).SurroundConstruct(ctx =>
                                                                                                                    Server.Return((IOperationServer s) => s.ConstructFromMany(coc.Entities, coc.Type, coc.OperationInfo.OperationSymbol, ctx.Args)));

                        if (result != null)
                        {
                            Navigator.Navigate(result);
                        }
                    }
                });
            }
        }
Esempio n. 7
0
        private OperationInfo GetConstructor(ConstructorContext ctx)
        {
            OperationInfo constructor = OperationInfos(ctx.Type).SingleOrDefaultEx(a => a.OperationType == OperationType.Constructor &&
                                                                                   (ctx.OperationInfo == null || a.OperationSymbol.Equals(ctx.OperationInfo.OperationSymbol)));

            if (constructor == null)
            {
                throw new InvalidOperationException("No Constructor operation found");
            }

            return(constructor);
        }
        public void TheCorrectMocksAndValuesAreUsedForTargetConstructor()
        {
            var context = new ConstructorContext <SingleConstructorClass>();
            var dep1    = context.Inject(new Mock <IDependency1>());
            var dep2    = context.Inject(new Mock <IDependency2>(), parameterName: "dep2");
            var value   = context.Inject(123);

            var obj = context.New();

            Assert.AreSame(dep1.Object, obj.Dep1);
            Assert.AreSame(dep2.Object, obj.Dep2);
            Assert.AreEqual(value, obj.Value);
        }
Esempio n. 9
0
        protected internal virtual Entity Construct(ConstructorContext ctx)
        {
            OperationInfo constructor = GetConstructor(ctx);

            var settings = GetSettings <ConstructorOperationSettingsBase>(ctx.Type, constructor.OperationSymbol);

            var result = settings != null && settings.HasConstructor ? settings.OnConstructor(newConstructorOperationContext.GetInvoker(ctx.Type)(constructor, ctx, settings)) :
                         OperationLogic.ServiceConstruct(ctx.Type, constructor.OperationSymbol);

            ctx.Controller.ViewData[ViewDataKeys.WriteEntityState] = true;

            return(result);
        }
Esempio n. 10
0
        public void ClickMeRequestsMessageBox()
        {
            // Arrange
            var context           = new ConstructorContext <MainViewModel>();
            var messageBoxService = context.Inject(new Mock <Services.UI.IMessageBoxService>());

            messageBoxService.Setup(s => s.Show("Hello!", "Test"))
            .Returns(MessageBoxResult.OK);

            var viewModel = context.New();

            // Act
            viewModel.ClickMe.Execute(null);
        }
Esempio n. 11
0
        public void DataIsFetchedFromService()
        {
            // Arrange
            var context = new ConstructorContext <MainViewModel>();
            var service = context.Inject(new Mock <Services.IService>());

            service.Setup(s => s.GetData()).Returns(new[] { "a", "b", "c" });

            var viewModel = context.New();

            // Act
            var result = viewModel.Data;

            // Assert
            CollectionAssert.AreEqual(new[] { "a", "b", "c" }, result);
        }
 public void InjectionsOfNamedValuesThatDoNotMatchAnyConstructorArgumentNameAreRejected()
 {
     try
     {
         var context = new ConstructorContext <SingleConstructorClass>();
         context.Inject(123, parameterName: "lukeSkywalker");
     }
     catch (ArgumentException ex)
     {
         Assert.AreEqual("Named parameter lukeSkywalker is not among formal parameters of constructor.", ex.Message);
     }
     catch (Exception ex)
     {
         Assert.Fail("Unexpected exception: " + ex.GetType().Name);
     }
 }
 public void InjectionsOfNamedValuesThatDoNotMatchConstructorArgumentTypeAreRejected()
 {
     try
     {
         var context = new ConstructorContext <SingleConstructorClass>();
         context.Inject(123, parameterName: "dep2");
     }
     catch (ArgumentException ex)
     {
         Assert.AreEqual("Named parameter dep2 is not of type IDependency2", ex.Message);
     }
     catch (Exception ex)
     {
         Assert.Fail("Unexpected exception: " + ex.GetType().Name);
     }
 }
 public void InjectionsOfUnnamedValuesThatDoNotMatchAnyConstructorArgumentAreRejected()
 {
     try
     {
         var context = new ConstructorContext <SingleConstructorClass>();
         context.Inject(123.45);
     }
     catch (ArgumentException ex)
     {
         Assert.AreEqual("Cannot autoinject parameter of type Double as it is not used in any constructor of SingleConstructorClass", ex.Message);
     }
     catch (Exception ex)
     {
         Assert.Fail("Unexpected exception: " + ex.GetType().Name);
     }
 }
Esempio n. 15
0
        /// <summary>
        /// Gets the type dependencies for a constructor.
        /// </summary>
        /// <param name="ctr"></param>
        /// <param name="visited">The set of type dependent symbols which have already been visited.</param>
        /// <returns></returns>
        public IEnumerable <TypeContext> GetTypeDependencies(ConstructorContext ctr, HashSet <ITypeDependent> visited = null)
        => GetTypeDependencies(ctr, () =>
        {
            var result =
                //The type of the constructor's parameters
                ctr.Symbol.Parameters.Select(x => new TypeContext(x.Type, ctr.SemanticModel))
                //The types directly mentioned in the body
                .Union(
                    GetBodyDeclaredTypes(ctr.Declaration, ctr.SemanticModel, visited)
                    .Select(x => new TypeContext(x, ctr.SemanticModel))
                    )
                //The local methods and properties mentioned in the body (which themselves may have dependencies)
                .Union(GetBodyInvocationSymbols(ctr.Declaration, ctr.SemanticModel, visited))
                .Distinct();

            return(result);
        }, ref visited);
 public void MultipleInjectionsOfNamedMocksAreRejected()
 {
     try
     {
         var context = new ConstructorContext <SingleConstructorClass>();
         context.Inject(new Mock <IDependency2>(), parameterName: "dep2");
         context.Inject(new Mock <IDependency2>(), parameterName: "dep2");
     }
     catch (ArgumentException ex)
     {
         Assert.AreEqual("Named parameter dep2 has already been injected.", ex.Message);
     }
     catch (Exception ex)
     {
         Assert.Fail("Unexpected exception: " + ex.GetType().Name);
     }
 }
 public void MultipleInjectionsOfNamedValuesAreRejected()
 {
     try
     {
         var context = new ConstructorContext <SingleConstructorClass>();
         context.Inject(123, parameterName: "value");
         context.Inject(123, parameterName: "value");
     }
     catch (ArgumentException ex)
     {
         Assert.AreEqual("Named parameter value has already been injected.", ex.Message);
     }
     catch (Exception ex)
     {
         Assert.Fail("Unexpected exception: " + ex.GetType().Name);
     }
 }
Esempio n. 18
0
        static IDisposable Constructor_PreConstructors(ConstructorContext ctx)
        {
            if (MixinDeclarations.IsDeclared(ctx.Type, typeof(IsolationMixin)))
            {
                Lite <IsolationEntity> isolation = GetIsolation(ctx, IsValid.TryGetC(ctx.Type));

                if (isolation == null)
                {
                    ctx.CancelConstruction = true;
                    return(null);
                }
                ctx.Args.Add(isolation);

                return(IsolationEntity.Override(isolation));
            }

            return(null);
        }
Esempio n. 19
0
        protected internal virtual Entity Construct(ConstructorContext ctx)
        {
            var dic = (from oi in OperationInfos(ctx.Type)
                       where oi.OperationType == OperationType.Constructor
                       let os = GetSettings <ConstructorOperationSettingsBase>(ctx.Type, oi.OperationSymbol)
                                let coc = newConstructorOperationContext.GetInvoker(ctx.Type)(oi, ctx, os)
                                          where os != null && os.HasIsVisible ? os.OnIsVisible(coc) : true
                                          select coc).ToDictionary(a => a.OperationInfo.OperationSymbol);

            if (dic.Count == 0)
            {
                return(null);
            }

            OperationSymbol selected = null;

            if (dic.Count == 1)
            {
                selected = dic.Keys.SingleEx();
            }
            else
            {
                if (!SelectorWindow.ShowDialog(dic.Keys.ToArray(), out selected,
                                               elementIcon: k => OperationClient.GetImage(ctx.Type, k),
                                               elementText: k => OperationClient.GetText(ctx.Type, k),
                                               title: SelectorMessage.ConstructorSelector.NiceToString(),
                                               message: SelectorMessage.PleaseSelectAConstructor.NiceToString(),
                                               owner: Window.GetWindow(ctx.Element)))
                {
                    return(null);
                }
            }

            var selCoc = dic[selected];

            if (selCoc.Settings != null && selCoc.Settings.HasConstructor)
            {
                return(selCoc.Settings.OnConstructor(selCoc));
            }
            else
            {
                return(Server.Return((IOperationServer s) => s.Construct(ctx.Type, selected, ctx.Args)));
            }
        }
Esempio n. 20
0
        public override object VisitConstructor(ConstructorContext context)
        {
            if (Ignore || _currentClass == null)
            {
                return(null);
            }

            if (context.isDestructor() != null)
            {
                return(null);
            }

            var name = context.methodName().GetText();

            if (name == _currentClass.Name)
            {
                var method = new Method(context.methodName().GetText())
                {
                    IsConst        = context.FoundChild <IsConstContext>(),
                    UMeta          = _currentUMeta ?? new Dictionary <string, string>(),
                    Description    = _currentComment,
                    OwnerClass     = _currentClass,
                    Operator       = context.methodName().methodOperator()?.GetText(),
                    AccessModifier = _accessModifier,
                    ReturnType     = new ClassVariable(_currentClass),

                    InputTypes = context.FindAll <MethodParametrContext>().Reverse()
                                 .Select(ParceParam).ToList()
                };

                if (!_currentClass.Constructors.Any(m => m.Equals(method)))
                {
                    _currentClass.Constructors.Add(method);
                }
            }

            _currentUMeta   = null;
            _currentComment = "";
            return(null);
        }
        public DefinedConstructor(ParseInfo parseInfo, Scope scope, CodeType type, ConstructorContext context) : base(
                type,
                new LanguageServer.Location(parseInfo.Script.Uri, context.LocationToken.Range),
                context.Attributes.GetAccessLevel())
        {
            this.parseInfo        = parseInfo;
            this.context          = context;
            _recursiveCallHandler = new RecursiveCallHandler(this, "constructor");
            CallInfo       = new CallInfo(_recursiveCallHandler, parseInfo.Script);
            SubroutineName = context.SubroutineName?.Text.RemoveQuotes();

            ConstructorScope = scope.Child();

            if (Type is DefinedType)
            {
                ((DefinedType)Type).AddLink(DefinedAt);
            }

            parseInfo.TranslateInfo.ApplyBlock(this);
            parseInfo.TranslateInfo.GetComponent <SymbolLinkComponent>().AddSymbolLink(this, DefinedAt, true);
            parseInfo.Script.AddCodeLensRange(new ReferenceCodeLensRange(this, parseInfo, CodeLensSourceType.Constructor, DefinedAt.range));
        }
Esempio n. 22
0
        public static Lite <IsolationEntity> GetIsolation(ConstructorContext ctx, Func <Lite <IsolationEntity>, string> isValid = null)
        {
            var element = ctx.Element;

            var result = IsolationEntity.Current;

            if (result == null)
            {
                var entity = element == null ? null : element.DataContext as Entity;
                if (entity != null)
                {
                    result = entity.TryIsolation();
                }
            }

            if (result == null)
            {
                var sc = element as SearchControl ?? (element as SearchWindow)?.SearchControl;
                if (sc != null && ctx.OperationInfo != null && (
                        ctx.OperationInfo.OperationType == OperationType.ConstructorFrom ||
                        ctx.OperationInfo.OperationType == OperationType.ConstructorFromMany))
                {
                    result = Server.Return((IIsolationServer a) => a.GetOnlyIsolation(sc.SelectedItems.ToList()));
                }
            }

            if (result != null)
            {
                var error = isValid == null ? null : isValid(result);
                if (error != null)
                {
                    throw new ApplicationException(error);
                }

                return(result);
            }

            return(SelectIsolationInteractively(element == null ? null : Window.GetWindow(element), isValid));
        }
        public DefinedConstructorProvider(IDefinedTypeInitializer provider, ParseInfo parseInfo, Scope scope, ConstructorContext context)
        {
            _parseInfo   = parseInfo;
            _scope       = scope.Child(true);
            _context     = context;
            TypeProvider = provider;

            _recursiveCallHandler = new RecursiveCallHandler(this, context.SubroutineName);
            CallInfo       = new CallInfo(_recursiveCallHandler, parseInfo.Script, ContentReady);
            SubroutineName = context.SubroutineName?.Text.RemoveQuotes();
            DefinedAt      = parseInfo.Script.GetLocation(context.ConstructorToken.Range);

            // Setup the parameters.
            ParameterProviders = ParameterProvider.GetParameterProviders(_parseInfo, _scope, _context.Parameters, SubroutineName != null);
            ParameterTypes     = ParameterProviders.Select(p => p.Type).ToArray();

            parseInfo.TranslateInfo.StagedInitiation.On(this);
            parseInfo.Script.AddCodeLensRange(new ReferenceCodeLensRange(this, parseInfo, CodeLensSourceType.Constructor, DefinedAt.range));
            parseInfo.Script.Elements.AddDeclarationCall(this, new DeclarationCall(context.ConstructorToken.Range, true));

            // Add the CallInfo to the recursion check.
            parseInfo.TranslateInfo.GetComponent <RecursionCheckComponent>().AddCheck(CallInfo);
        }
Esempio n. 24
0
        public static void Start()
        {
            if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                Navigator.AddSettings(new List<EntitySettings>
                {
                    new EntitySettings<SMSMessageEntity> { View = e => new SMSMessage(), Icon = ExtensionsImageLoader.GetImageSortName("sms.png") },
                    new EntitySettings<SMSTemplateEntity> { View = e => new SMSTemplate(), Icon = ExtensionsImageLoader.GetImageSortName("smstemplate.png") },
                    new EmbeddedEntitySettings<SMSTemplateMessageEntity>() { View = e => new Signum.Windows.SMS.SMSTemplateMessage() },
                    new EntitySettings<SMSSendPackageEntity> { View = e => new SMSSendPackage(), Icon = ExtensionsImageLoader.GetImageSortName("package.png") },
                    new EntitySettings<SMSUpdatePackageEntity> { View = e => new SMSUpdatePackage(), Icon = ExtensionsImageLoader.GetImageSortName("package.png") },
                    new EmbeddedEntitySettings<MultipleSMSModel> { View = e => new MultipleSMS(), Icon = ExtensionsImageLoader.GetImageSortName("package.png") },
                });

                OperationClient.AddSetting(new EntityOperationSettings<Entity>(SMSMessageOperation.CreateSMSWithTemplateFromEntity)
                {
                    Click = FindAssociatedTemplates
                });

                OperationClient.AddSetting(new ContextualOperationSettings<Entity>(SMSMessageOperation.SendSMSMessages)
                {
                    Click = coc =>
                    {
                        MultipleSMSModel model = Navigator.View(new MultipleSMSModel());

                        if (model == null)
                            return;

                        var result = new ConstructorContext(coc.SearchControl, coc.OperationInfo).SurroundConstruct(ctx =>
                            Server.Return((IOperationServer s) => s.ConstructFromMany(coc.Entities, coc.Type, coc.OperationInfo.OperationSymbol, ctx.Args)));

                        if (result != null)
                            Navigator.Navigate(result);
                    }
                });
            }
        }
Esempio n. 25
0
 public ConstructorOperationContext(OperationInfo info, ConstructorContext context, ConstructorOperationSettings <T> settings)
 {
     this.OperationInfo      = info;
     this.ConstructorContext = context;
     this.Settings           = settings;
 }
Esempio n. 26
0
        protected object OnCreate()
        {
            if (!CanCreate())
                return null;

            object value;
            if (Creating == null)
            {
                Type type = SelectType(t => Navigator.IsCreable(t, isSearch: false));
                if (type == null)
                    return null;

                object entity = new ConstructorContext(this).ConstructUntyped(type);

                value = entity;
            }
            else
                value = Creating();

            if (value == null)
                return null;

            if (ViewOnCreate)
            {
                value = OnViewingOrNavigating(value, creating: true);
            }

            return value;
        }