示例#1
0
 internal override object GetImplementationOf()
 {
     if (Lifetime == Lifetime.Singleton && _instance != null)
     {
         return(_instance);
     }
     _instance = _typeActivator.CreateInstance(_implementingTypes.First());
     return(_instance);
 }
        public async Task GenerateCode([NotNull] ControllerGeneratorModel controllerGeneratorModel)
        {
            // Validate model
            string      validationMessage;
            ITypeSymbol model, dataContext;

            // Review: MVC scaffolding used ActiveProject's MSBuild RootNamespace property
            // That's not possible in command line scaffolding - the closest we can get is
            // the name of assembly??
            var appName             = _libraryManager.GetLibraryInformation(_applicationEnvironment.ApplicationName).Name;
            var controllerNameSpace = appName + "." + Constants.ControllersFolderName;

            var layoutDependencyInstaller = _typeActivator.CreateInstance <MvcLayoutDependencyInstaller>(_serviceProvider);

            if (!string.IsNullOrEmpty(controllerGeneratorModel.ModelClass) && !string.IsNullOrEmpty(controllerGeneratorModel.DataContextClass))
            {
                if (!ValidationUtil.TryValidateType(controllerGeneratorModel.ModelClass, "model", _modelTypesLocator, out model, out validationMessage))
                {
                    throw new ArgumentException(validationMessage);
                }

                ValidationUtil.TryValidateType(controllerGeneratorModel.DataContextClass, "dataContext", _modelTypesLocator, out dataContext, out validationMessage);
                await GenerateController(controllerGeneratorModel, model, dataContext, controllerNameSpace, layoutDependencyInstaller);
            }
            else
            {
                await layoutDependencyInstaller.Execute();
                await GenerateEmptyController(controllerGeneratorModel, controllerNameSpace);
            }

            await layoutDependencyInstaller.InstallDependencies();
        }
示例#3
0
        private Key ParseKeyElement(XElement keyElement)
        {
            Debug.Assert(keyElement.Name == KeyElementName);

            int version = (int)keyElement.Attribute(VersionAttributeName);

            CryptoUtil.Assert(version == 1, "TODO: version == 1");

            XElement encryptorConfigurationAsXml          = keyElement.Element(AuthenticatedEncryptorElementName).Elements().Single();
            string   encryptorConfigurationParserTypeName = (string)encryptorConfigurationAsXml.Attribute(ReaderAttributeName);
            Type     encryptorConfigurationParserType     = Type.GetType(encryptorConfigurationParserTypeName, throwOnError: true);

            CryptoUtil.Assert(typeof(IAuthenticatedEncryptorConfigurationXmlReader).IsAssignableFrom(encryptorConfigurationParserType),
                              "TODO: typeof(IAuthenticatedEncryptorConfigurationXmlReader).IsAssignableFrom(encryptorConfigurationParserType)");

            var parser = (IAuthenticatedEncryptorConfigurationXmlReader)_typeActivator.CreateInstance(_serviceProvider, encryptorConfigurationParserType);
            var encryptorConfiguration = parser.FromXml(encryptorConfigurationAsXml);

            Guid           keyId          = (Guid)keyElement.Attribute(IdAttributeName);
            DateTimeOffset creationDate   = (DateTimeOffset)keyElement.Element(CreationDateElementName);
            DateTimeOffset activationDate = (DateTimeOffset)keyElement.Element(ActivationDateElementName);
            DateTimeOffset expirationDate = (DateTimeOffset)keyElement.Element(ExpirationDateElementName);

            return(new Key(
                       keyId: keyId,
                       creationDate: creationDate,
                       activationDate: activationDate,
                       expirationDate: expirationDate,
                       encryptorConfiguration: encryptorConfiguration));
        }
        private object CreateComponent([NotNull] ViewContext context)
        {
            var component = _activator.CreateInstance(_serviceProvider, _componentType.AsType());

            _viewComponentActivator.Activate(component, context);
            return(component);
        }
        /// <inheritdoc />
        public IRazorPage CreateInstance([NotNull] string relativePath)
        {
            if (relativePath.StartsWith("~/", StringComparison.Ordinal))
            {
                // For tilde slash paths, drop the leading ~ to make it work with the underlying IFileSystem.
                relativePath = relativePath.Substring(1);
            }

            var fileInfo = _fileSystemCache.GetFileInfo(relativePath);

            if (fileInfo.Exists)
            {
                var relativeFileInfo = new RelativeFileInfo(fileInfo, relativePath);

                var result = _compilerCache.GetOrAdd(
                    relativeFileInfo,
                    RazorCompilationService.Compile);

                var page = (IRazorPage)_activator.CreateInstance(_serviceProvider, result.CompiledType);
                page.Path = relativePath;

                return(page);
            }

            return(null);
        }
示例#6
0
        public async Task GenerateCode(DependencyGeneratorModel model)
        {
            DependencyInstaller dependencyInstaller = null;

            if (model.AddStaticFiles)
            {
                dependencyInstaller = _typeActivator.CreateInstance <StaticFilesDependencyInstaller>(_serviceProvider);
            }

            if (model.AddMvcLayout)
            {
                dependencyInstaller = _typeActivator.CreateInstance <MvcLayoutDependencyInstaller>(_serviceProvider);
            }

            await dependencyInstaller.Execute();

            await dependencyInstaller.InstallDependencies();
        }
        public static T CreateInstance <T>(this ITypeActivator activator, IServiceProvider serviceProvider, params object[] parameters)
        {
            if (activator == null)
            {
                throw new ArgumentNullException("activator");
            }

            return((T)activator.CreateInstance(serviceProvider, typeof(T), parameters));
        }
        private static object CreateInstance(this ITypeActivator activator, IServiceProvider serviceProvider, Type serviceType, params object[] parameters)
        {
            if (activator == null)
            {
                throw new ArgumentNullException(nameof(activator));
            }

            return(activator.CreateInstance(serviceProvider, serviceType, parameters));
        }
        public TransportManager(IServiceProvider serviceProvider,
                                ITypeActivator typeActivator,
                                IOptions <SignalROptions> optionsAccessor)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }
            if (typeActivator == null)
            {
                throw new ArgumentNullException("typeActivator");
            }
            if (optionsAccessor == null)
            {
                throw new ArgumentNullException("optionsAccessor");
            }

            var enabledTransports = optionsAccessor.Options.Transports.EnabledTransports;

            if (enabledTransports.HasFlag(TransportType.WebSockets))
            {
                Register("webSockets", context => typeActivator.CreateInstance <WebSocketTransport>(serviceProvider, context));
            }
            if (enabledTransports.HasFlag(TransportType.ServerSentEvents))
            {
                Register("serverSentEvents", context => typeActivator.CreateInstance <ServerSentEventsTransport>(serviceProvider, context));
            }
            if (enabledTransports.HasFlag(TransportType.ForeverFrame))
            {
                Register("foreverFrame", context => typeActivator.CreateInstance <ForeverFrameTransport>(serviceProvider, context));
            }
            if (enabledTransports.HasFlag(TransportType.LongPolling))
            {
                Register("longPolling", context => typeActivator.CreateInstance <LongPollingTransport>(serviceProvider, context));
            }

            if (_transports.Count == 0)
            {
                throw new InvalidOperationException(Resources.Error_NoTransportsEnabled);
            }
        }
示例#10
0
        public Task <bool> BindModelAsync(ModelBindingContext bindingContext)
        {
            var binderType = ResolveBinderType(bindingContext.ModelType);

            if (binderType != null)
            {
                var binder = (IModelBinder)_activator.CreateInstance(_serviceProvider, binderType);
                return(binder.BindModelAsync(bindingContext));
            }

            return(Task.FromResult(false));
        }
示例#11
0
        public ICommand CreateInstance(
            IReadOnlyList <CommandUnboundArgumentInput> parameterInputs,
            IReadOnlyList <CommandOptionInput> optionInputs,
            IReadOnlyDictionary <string, string> environmentVariables,
            ITypeActivator activator)
        {
            var command = (ICommand)activator.CreateInstance(Type);

            InjectParameters(command, parameterInputs);
            InjectOptions(command, optionInputs, environmentVariables);

            return(command);
        }
        public IHub Create(HubDescriptor descriptor)
        {
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }

            if (descriptor.HubType == null)
            {
                return(null);
            }

            return(_typeActivator.CreateInstance(_serviceProvider, descriptor.HubType) as IHub);
        }
示例#13
0
        /// <inheritdoc />
        public IRazorPage CreateInstance([NotNull] string path)
        {
            var fileInfo = _fileInfoCache.GetFileInfo(path);

            if (fileInfo != null)
            {
                var result = _compilationService.Compile(fileInfo);
                var page   = (IRazorPage)_activator.CreateInstance(_serviceProvider, result.CompiledType);
                page.Path = path;
                return(page);
            }

            return(null);
        }
示例#14
0
        public async Task <bool> BindModelAsync(ModelBindingContext bindingContext)
        {
            var binderType = ResolveBinderType(bindingContext.ModelType);

            if (binderType != null)
            {
                var binder = (IModelBinder)_activator.CreateInstance(_serviceProvider, binderType);
                await binder.BindModelAsync(bindingContext);

                // Was able to resolve a binder type, hence we should tell the model binding system to return
                // true so that none of the other model binders participate.
                return(true);
            }

            return(false);
        }
示例#15
0
        public IAuthenticatedEncryptorConfiguration FromXml([NotNull] XElement element)
        {
            // <cbcEncryptor reader="{TYPE}">
            //   <encryption algorithm="{STRING}" provider="{STRING}" keyLength="{INT}" />
            //   <validation algorithm="{STRING}" provider="{STRING}" />
            //   <secret>...</secret>
            // </cbcEncryptor>

            CryptoUtil.Assert(element.Name == CngCbcAuthenticatedEncryptorConfiguration.CbcEncryptorElementName,
                              @"TODO: Bad element.");

            var options = new CngCbcAuthenticatedEncryptorConfigurationOptions();

            // read <encryption> element
            var encryptionElement = element.Element(CngCbcAuthenticatedEncryptorConfiguration.EncryptionElementName);

            options.EncryptionAlgorithm         = (string)encryptionElement.Attribute("algorithm");
            options.EncryptionAlgorithmProvider = (string)encryptionElement.Attribute("provider");
            options.EncryptionAlgorithmKeySize  = (int)encryptionElement.Attribute("keyLength");

            // read <validation> element
            var validationElement = element.Element(CngCbcAuthenticatedEncryptorConfiguration.ValidationElementName);

            options.HashAlgorithm         = (string)validationElement.Attribute("algorithm");
            options.HashAlgorithmProvider = (string)validationElement.Attribute("provider");

            // read the child of the <secret> element, then decrypt it
            var encryptedSecretElement         = element.Element(CngCbcAuthenticatedEncryptorConfiguration.SecretElementName).Elements().Single();
            var secretElementDecryptorTypeName = (string)encryptedSecretElement.Attribute("decryptor");
            var secretElementDecryptorType     = Type.GetType(secretElementDecryptorTypeName, throwOnError: true);
            var secretElementDecryptor         = (IXmlDecryptor)_typeActivator.CreateInstance(_serviceProvider, secretElementDecryptorType);
            var decryptedSecretElement         = secretElementDecryptor.Decrypt(encryptedSecretElement);

            CryptoUtil.Assert(decryptedSecretElement.Name == CngCbcAuthenticatedEncryptorConfiguration.SecretElementName,
                              @"TODO: Bad element.");

            byte[] decryptedSecretBytes = Convert.FromBase64String((string)decryptedSecretElement);
            try
            {
                var protectedMemoryBlob = new ProtectedMemoryBlob(decryptedSecretBytes);
                return(new CngCbcAuthenticatedEncryptorConfiguration(options, protectedMemoryBlob));
            }
            finally
            {
                Array.Clear(decryptedSecretBytes, 0, decryptedSecretBytes.Length);
            }
        }
        public object Create(Type moduleType, IServiceProvider services)
        {
            var instance = _typeActivator.CreateInstance(moduleType, services);

            if (instance is ICommandsModule standard)
            {
                try
                {
                    standard.Output = services.GetRequiredService <ICommandLineOutput>();
                }
                catch
                {
                    (instance as IDisposable)?.Dispose();
                    throw;
                }
            }
            return(instance);
        }
示例#17
0
        public object CreateController(ActionContext actionContext)
        {
            var actionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;

            if (actionDescriptor == null)
            {
                throw new ArgumentException(
                          Resources.FormatActionDescriptorMustBeBasedOnControllerAction(
                              typeof(ControllerActionDescriptor)),
                          nameof(actionContext));
            }

            var controller = _typeActivator.CreateInstance(
                _serviceProvider,
                actionDescriptor.ControllerTypeInfo.AsType());

            _controllerActivator.Activate(controller, actionContext);

            return(controller);
        }
示例#18
0
        public object CreateController(ActionContext actionContext)
        {
            var actionDescriptor = actionContext.ActionDescriptor as ReflectedActionDescriptor;

            if (actionDescriptor == null)
            {
                throw new ArgumentException(
                          Resources.FormatDefaultControllerFactory_ActionDescriptorMustBeReflected(
                              typeof(ReflectedActionDescriptor)),
                          "actionContext");
            }

            var controller = _typeActivator.CreateInstance(
                _serviceProvider,
                actionDescriptor.ControllerDescriptor.ControllerTypeInfo.AsType());

            actionContext.Controller = controller;
            _controllerActivator.Activate(controller, actionContext);

            return(controller);
        }
        public async Task <bool> BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelMetadata.BinderType == null)
            {
                // Return false so that we are able to continue with the default set of model binders,
                // if there is no specific model binder provided.
                return(false);
            }

            var requestServices = bindingContext.OperationBindingContext.HttpContext.RequestServices;
            var instance        = _typeActivator.CreateInstance(requestServices, bindingContext.ModelMetadata.BinderType);

            var modelBinder = instance as IModelBinder;

            if (modelBinder == null)
            {
                var modelBinderProvider = instance as IModelBinderProvider;
                if (modelBinderProvider != null)
                {
                    modelBinder = new CompositeModelBinder(modelBinderProvider.ModelBinders);
                }
                else
                {
                    throw new InvalidOperationException(
                              Resources.FormatBinderType_MustBeIModelBinderOrIModelBinderProvider(
                                  bindingContext.ModelMetadata.BinderType.FullName,
                                  typeof(IModelBinder).FullName,
                                  typeof(IModelBinderProvider).FullName));
                }
            }

            await modelBinder.BindModelAsync(bindingContext);

            // return true here, because this binder will handle all cases where the model binder is
            // specified by metadata.
            return(true);
        }
        public object CreateController(ActionContext actionContext)
        {
            Type controllerType;

            var controllerActionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;

            if (controllerActionDescriptor != null &&
                controllerActionDescriptor.ControllerDescriptor.ControllerTypeInfo.ContainsGenericParameters)
            {
                var entityName  = actionContext.RouteData.Values["entityName"].ToString();
                var genericType = DebbyAdmin.Entities.FirstOrDefault(x => x.Name == entityName) ?? typeof(object);

                controllerType = typeof(GenericController <>).MakeGenericType(genericType);
            }
            else
            {
                var actionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;
                if (actionDescriptor == null)
                {
                    throw new ArgumentException(
                              string.Format("The action descriptor must be of type '{0}'",
                                            typeof(ControllerActionDescriptor)),
                              "actionContext");
                }

                controllerType = actionDescriptor.ControllerDescriptor.ControllerTypeInfo.AsType();
            }

            var controller = _typeActivator.CreateInstance(
                _serviceProvider,
                controllerType);

            _controllerActivator.Activate(controller, actionContext);

            return(controller);
        }
示例#21
0
 private T CreateInstance <T>(Type type, IServiceProvider services)
 {
     return((T)_typeActivator.CreateInstance(type, services));
 }
示例#22
0
    private object?ConvertSingle(IMemberSchema memberSchema, string?rawValue, Type targetType)
    {
        // Custom converter
        if (memberSchema.ConverterType is not null)
        {
            var converter = (IBindingConverter)_typeActivator.CreateInstance(memberSchema.ConverterType);
            return(converter.Convert(rawValue));
        }

        // Assignable from string (e.g. string itself, object, etc)
        if (targetType.IsAssignableFrom(typeof(string)))
        {
            return(rawValue);
        }

        // Special case for bool
        if (targetType == typeof(bool))
        {
            return(string.IsNullOrWhiteSpace(rawValue) || bool.Parse(rawValue));
        }

        // Special case for DateTimeOffset
        if (targetType == typeof(DateTimeOffset))
        {
            return(DateTimeOffset.Parse(rawValue, _formatProvider));
        }

        // Special case for TimeSpan
        if (targetType == typeof(TimeSpan))
        {
            return(TimeSpan.Parse(rawValue, _formatProvider));
        }

        // Enum
        if (targetType.IsEnum)
        {
            // Null reference exception will be handled upstream
            return(Enum.Parse(targetType, rawValue !, true));
        }

        // Convertible primitives (int, double, char, etc)
        if (targetType.Implements(typeof(IConvertible)))
        {
            return(Convert.ChangeType(rawValue, targetType, _formatProvider));
        }

        // Nullable<T>
        var nullableUnderlyingType = targetType.TryGetNullableUnderlyingType();

        if (nullableUnderlyingType is not null)
        {
            return(!string.IsNullOrWhiteSpace(rawValue)
                ? ConvertSingle(memberSchema, rawValue, nullableUnderlyingType)
                : null);
        }

        // String-constructible (FileInfo, etc)
        var stringConstructor = targetType.GetConstructor(new[] { typeof(string) });

        if (stringConstructor is not null)
        {
            return(stringConstructor.Invoke(new object?[] { rawValue }));
        }

        // String-parseable (with IFormatProvider)
        var parseMethodWithFormatProvider = targetType.TryGetStaticParseMethod(true);

        if (parseMethodWithFormatProvider is not null)
        {
            return(parseMethodWithFormatProvider.Invoke(null, new object?[] { rawValue, _formatProvider }));
        }

        // String-parseable (without IFormatProvider)
        var parseMethod = targetType.TryGetStaticParseMethod();

        if (parseMethod is not null)
        {
            return(parseMethod.Invoke(null, new object?[] { rawValue }));
        }

        throw CliFxException.InternalError(
                  $"{memberSchema.GetKind()} {memberSchema.GetFormattedIdentifier()} has an unsupported underlying property type." +
                  Environment.NewLine +
                  $"There is no known way to convert a string value into an instance of type `{targetType.FullName}`." +
                  Environment.NewLine +
                  "To fix this, either change the property to use a supported type or configure a custom converter."
                  );
    }
 private ICollectionConstructor GetInstance(Type parserType, IServiceProvider services)
 {
     return((ICollectionConstructor)_typeActivator.CreateInstance(parserType, services));
 }
 private object CreateInstance(TypeInfo type)
 {
     return(_typeActivator.CreateInstance(_serviceProvider, type.AsType()));
 }
示例#25
0
        public async Task GenerateCode([NotNull] ViewGeneratorModel viewGeneratorModel)
        {
            // Validate model
            string      validationMessage;
            ITypeSymbol model, dataContext;

            if (!ValidationUtil.TryValidateType(viewGeneratorModel.ModelClass, "model", _modelTypesLocator, out model, out validationMessage))
            {
                throw new ArgumentException(validationMessage);
            }

            if (string.IsNullOrEmpty(viewGeneratorModel.ViewName))
            {
                throw new ArgumentException("The ViewName cannot be empty");
            }

            if (viewGeneratorModel.ViewName.EndsWith(Constants.ViewExtension, StringComparison.OrdinalIgnoreCase))
            {
                int viewNameLength = viewGeneratorModel.ViewName.Length - Constants.ViewExtension.Length;
                viewGeneratorModel.ViewName = viewGeneratorModel.ViewName.Substring(0, viewNameLength);
            }

            if (string.IsNullOrEmpty(viewGeneratorModel.TemplateName))
            {
                throw new ArgumentException("The TemplateName cannot be empty");
            }

            ValidationUtil.TryValidateType(viewGeneratorModel.DataContextClass, "dataContext", _modelTypesLocator, out dataContext, out validationMessage);

            // Validation successful
            Contract.Assert(model != null, "Validation succeded but model type not set");

            var appbasePath = _applicationEnvironment.ApplicationBasePath;
            var outputPath  = Path.Combine(
                appbasePath,
                Constants.ViewsFolderName,
                model.Name,
                viewGeneratorModel.ViewName + Constants.ViewExtension);

            if (File.Exists(outputPath) && !viewGeneratorModel.Force)
            {
                throw new InvalidOperationException(string.Format(
                                                        CultureInfo.CurrentCulture,
                                                        "View file {0} exists, use -f option to overwrite",
                                                        outputPath));
            }

            var templateName = viewGeneratorModel.TemplateName + Constants.RazorTemplateExtension;

            var dbContextFullName = dataContext != null?dataContext.ToDisplayString() : viewGeneratorModel.DataContextClass;

            var modelTypeFullName = model.ToDisplayString();

            var modelMetadata = await _entityFrameworkService.GetModelMetadata(
                dbContextFullName,
                model);

            var layoutDependencyInstaller = _typeActivator.CreateInstance <MvcLayoutDependencyInstaller>(_serviceProvider);

            bool isLayoutSelected = viewGeneratorModel.UseDefaultLayout ||
                                    !String.IsNullOrEmpty(viewGeneratorModel.LayoutPage);

            await layoutDependencyInstaller.Execute();

            var templateModel = new ViewGeneratorTemplateModel()
            {
                ViewDataTypeName      = modelTypeFullName,
                ViewDataTypeShortName = model.Name,
                ViewName                 = viewGeneratorModel.ViewName,
                LayoutPageFile           = viewGeneratorModel.LayoutPage,
                IsLayoutPageSelected     = isLayoutSelected,
                IsPartialView            = viewGeneratorModel.PartialView,
                ReferenceScriptLibraries = viewGeneratorModel.ReferenceScriptLibraries,
                ModelMetadata            = modelMetadata,
                JQueryVersion            = "1.10.2" //Todo
            };

            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, TemplateFolders, templateModel);

            _logger.LogMessage("Added View : " + outputPath.Substring(appbasePath.Length));

            await layoutDependencyInstaller.InstallDependencies();
        }
示例#26
0
    private async ValueTask <int> RunAsync(ApplicationSchema applicationSchema, CommandInput commandInput)
    {
        // Handle debug directive
        if (IsDebugModeEnabled(commandInput))
        {
            await PromptDebuggerAsync();
        }

        // Handle preview directive
        if (IsPreviewModeEnabled(commandInput))
        {
            _console.Output.WriteCommandInput(commandInput);
            return(0);
        }

        // Try to get the command schema that matches the input
        var commandSchema =
            applicationSchema.TryFindCommand(commandInput.CommandName) ??
            applicationSchema.TryFindDefaultCommand() ??
            FallbackDefaultCommand.Schema;

        // Activate command instance
        var commandInstance = commandSchema == FallbackDefaultCommand.Schema
            ? new FallbackDefaultCommand() // bypass activator
            : (ICommand)_typeActivator.CreateInstance(commandSchema.Type);

        // Assemble help context
        var helpContext = new HelpContext(
            Metadata,
            applicationSchema,
            commandSchema,
            commandSchema.GetValues(commandInstance)
            );

        // Handle help option
        if (ShouldShowHelpText(commandSchema, commandInput))
        {
            _console.Output.WriteHelpText(helpContext);
            return(0);
        }

        // Handle version option
        if (ShouldShowVersionText(commandSchema, commandInput))
        {
            _console.Output.WriteLine(Metadata.Version);
            return(0);
        }

        // Starting from this point, we may produce exceptions that are meant for the
        // end user of the application (i.e. invalid input, command exception, etc).
        // Catch these exceptions here, print them to the console, and don't let them
        // propagate further.
        try
        {
            // Bind and execute command
            _commandBinder.Bind(commandInput, commandSchema, commandInstance);
            await commandInstance.ExecuteAsync(_console);

            return(0);
        }
        catch (CliFxException ex)
        {
            _console.Error.WriteException(ex);

            if (ex.ShowHelp)
            {
                _console.Output.WriteLine();
                _console.Output.WriteHelpText(helpContext);
            }

            return(ex.ExitCode);
        }
    }
示例#27
0
 private ICommand GetCommandInstance(CommandSchema command) =>
 command != StubDefaultCommand.Schema
         ? (ICommand)_typeActivator.CreateInstance(command.Type)
         : new StubDefaultCommand();
        public virtual ParameterSetResult Build(ITypeActivator typeActivator,
                                                ITypeConverter typeConverter,
                                                CultureInfo cultureInfo,
                                                NodeSequence sequence,
                                                ParameterSet paramSet)
        {
            BuildContext ctx = new BuildContext(sequence,
                                                paramSet,
                                                typeActivator.CreateInstance(paramSet.UnderlyingType));

            var requiredParameters = new HashSet<Parameter>(paramSet.Where(p => p.GetAttribute<RequiredAttribute>() != null));

            SetDefaultValues(typeConverter, cultureInfo, ctx);

            bool first = true;

            using (IEnumerator<AstNode> enumerator = sequence.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    if (first && !string.IsNullOrEmpty(ctx.ParameterSet.Command))
                    {
                        LiteralValue literal = enumerator.Current as LiteralValue;
                        if (literal == null || !StringComparer.InvariantCultureIgnoreCase.Equals(literal.Value, ctx.ParameterSet.Command))
                        {
                            // report error: missing/incorrect command
                            ctx.Errors.Add(new BindError(ErrorType.MissingCommand,
                                                         Enumerable.Empty<Parameter>(),
                                                         new AstNode[] { literal },
                                                         string.Format(ErrorMessages.MissingCommand, ctx.ParameterSet.Command)));
                        }
                        if (!enumerator.MoveNext())
                            break;
                    }
                    first = false;

                    if (enumerator.Current.Type == NodeType.Parameter || enumerator.Current.Type == NodeType.Switch)
                    {
                        ParameterName parameterName = (ParameterName)enumerator.Current;
                        Parameter[] parameters;
                        if (ctx.ParameterSet.TryGetParameter(parameterName.Name, out parameters) && parameters.Length == 1)
                        {
                            // remove from "remaining parameters" collection
                            if (!ctx.RemainingParameters.Remove(parameters[0]))
                            {
                                // report error, multiple bindings
                                string message = string.Format(ErrorMessages.MultipleBindings,
                                                               parameterName.Name);

                                ctx.Errors.Add(new BindError(ErrorType.MultipleBindings,
                                                             parameters,
                                                             new AstNode[] { parameterName },
                                                             message));

                                // if the parameter was not of type Switch, skip next node
                                if (parameters[0].Property.PropertyType != typeof(Switch))
                                    enumerator.MoveNext();

                                // handled, continue and skip
                                continue;
                            }

                            // if it's a Switch we can simply set it to "Present"
                            if (parameters[0].Property.PropertyType == typeof(Switch))
                            {
                                if (enumerator.Current.Type == NodeType.Switch)
                                {
                                    SwitchParameter switchParameter = (SwitchParameter)enumerator.Current;
                                    SetPropertyValue(ctx, parameters[0], switchParameter.Value);
                                }
                                else
                                    parameters[0].Property.SetValue(ctx.Instance, Switch.Present, null);

                                requiredParameters.Remove(parameters[0]);
                                // handled, continue and skip
                                continue;
                            }

                            // advance to value 
                            if (!enumerator.MoveNext())
                            {
                                string message = string.Format(ErrorMessages.MissingValue, parameters[0].Name);

                                ctx.Errors.Add(new BindError(ErrorType.MissingValue,
                                                             new[] { parameters[0] },
                                                             new[] { parameterName },
                                                             message));
                                break;
                            }

                            SetPropertyValue(ctx, parameters[0], enumerator.Current);
                            requiredParameters.Remove(parameters[0]);
                        }
                        else if (parameters != null && parameters.Length > 1)
                        {
                            // report error, ambigious name
                            string message = string.Format(ErrorMessages.AmbigiousName,
                                                           parameterName.Name,
                                                           string.Join(", ", parameters.Select(p => p.Name)));

                            ctx.Errors.Add(new BindError(ErrorType.AmbigiousName,
                                                         parameters,
                                                         new AstNode[] { parameterName },
                                                         message));
                        }
                        else
                        {
                            // report error, parameter not found
                            string message = string.Format(ErrorMessages.ArgumentNameMismatch, parameterName.Name);

                            ctx.Errors.Add(new BindError(ErrorType.ArgumentNameMismatch,
                                                         Enumerable.Empty<Parameter>(),
                                                         new AstNode[] { parameterName },
                                                         message));
                        }
                    }
                    else
                    {
                        // positional param
                        var positionalParam = ctx.RemainingParameters.FirstOrDefault(p => p.Position.HasValue);

                        if (positionalParam == null)
                        {
                            // report error, there are no positional parameters
                            string message = string.Format(ErrorMessages.ArgumentPositionMismatch,
                                                           ctx.Sequence.GetInputString(enumerator.Current.SourceInfo));

                            ctx.Errors.Add(new BindError(ErrorType.ArgumentPositionMismatch,
                                                         Enumerable.Empty<Parameter>(),
                                                         new[] { enumerator.Current },
                                                         message));
                        }
                        else
                        {
                            SetPropertyValue(ctx, positionalParam, enumerator.Current);
                            requiredParameters.Remove(positionalParam);
                        }
                    }
                }
            }

            foreach (Parameter missingParameter in requiredParameters)
            {
                string message = string.Format(ErrorMessages.MissingRequiredParameter, missingParameter.Name);

                ctx.Errors.Add(new BindError(ErrorType.MissingRequiredParameter,
                                             new[] { missingParameter },
                                             null,
                                             message));
            }

            return new ParameterSetResult(sequence, ctx.ParameterSet, ctx.Instance, ctx.Errors);
        }