public ChangeSignatureOptionsResult?GetChangeSignatureOptions(
            Document document,
            int positionForTypeBinding,
            ISymbol symbol,
            ParameterConfiguration parameters)
        {
            var viewModel = new ChangeSignatureDialogViewModel(
                parameters,
                symbol,
                document,
                positionForTypeBinding,
                _classificationFormatMap,
                _classificationTypeMap);

            ChangeSignatureLogger.LogChangeSignatureDialogLaunched();

            var dialog = new ChangeSignatureDialog(viewModel);
            var result = dialog.ShowModal();

            if (result.HasValue && result.Value)
            {
                ChangeSignatureLogger.LogChangeSignatureDialogCommitted();

                var signatureChange = new SignatureChange(parameters, viewModel.GetParameterConfiguration());
                signatureChange.LogTelemetry();

                return(new ChangeSignatureOptionsResult(signatureChange, previewChanges: viewModel.PreviewChanges));
            }

            return(null);
        }
コード例 #2
0
        internal ChangeSignatureDialogViewModel(INotificationService notificationService, ParameterConfiguration parameters, ISymbol symbol, ClassificationTypeMap classificationTypeMap)
        {
            _originalParameterConfiguration = parameters;
            _notificationService            = notificationService;
            _classificationTypeMap          = classificationTypeMap;

            int startingSelectedIndex = 0;

            if (parameters.ThisParameter != null)
            {
                startingSelectedIndex++;

                _thisParameter = new ParameterViewModel(this, parameters.ThisParameter);
                _disabledParameters.Add(parameters.ThisParameter);
            }

            if (parameters.ParamsParameter != null)
            {
                _paramsParameter = new ParameterViewModel(this, parameters.ParamsParameter);
            }

            _symbol           = symbol;
            _declarationParts = symbol.ToDisplayParts(s_symbolDeclarationDisplayFormat);

            _parameterGroup1   = parameters.ParametersWithoutDefaultValues.Select(p => new ParameterViewModel(this, p)).ToList();
            _parameterGroup2   = parameters.RemainingEditableParameters.Select(p => new ParameterViewModel(this, p)).ToList();
            this.SelectedIndex = startingSelectedIndex;
        }
コード例 #3
0
        internal ChangeSignatureDialogViewModel(
            ParameterConfiguration parameters,
            ISymbol symbol,
            Document document,
            int positionForTypeBinding,
            IClassificationFormatMap classificationFormatMap,
            ClassificationTypeMap classificationTypeMap)
        {
            _originalParameterConfiguration = parameters;
            _document = document;
            _positionForTypeBinding  = positionForTypeBinding;
            _classificationFormatMap = classificationFormatMap;
            _classificationTypeMap   = classificationTypeMap;

            _notificationService = document.Project.Solution.Workspace.Services.GetRequiredService <INotificationService>();

            // This index is displayed to users. That is why we start it from 1.
            var initialDisplayIndex = 1;

            if (parameters.ThisParameter != null)
            {
                _thisParameter = new ExistingParameterViewModel(this, parameters.ThisParameter, initialDisplayIndex++);
                _disabledParameters.Add(_thisParameter);
            }

            _declarationParts = symbol.ToDisplayParts(s_symbolDeclarationDisplayFormat);

            _parametersWithoutDefaultValues = CreateParameterViewModels(parameters.ParametersWithoutDefaultValues, ref initialDisplayIndex);
            _parametersWithDefaultValues    = CreateParameterViewModels(parameters.RemainingEditableParameters, ref initialDisplayIndex);

            if (parameters.ParamsParameter != null)
            {
                _paramsParameter = new ExistingParameterViewModel(this, parameters.ParamsParameter, initialDisplayIndex++);
            }

            UpdateNameConflictMarkers();

            var selectedIndex = parameters.SelectedIndex;

            // Currently, we do not support editing the ThisParameter.
            // Therefore, if there is such parameter, we should move the selectedIndex.
            if (parameters.ThisParameter != null && selectedIndex == 0)
            {
                // If we have at least one parameter after the ThisParameter, select the first one after This.
                // Otherwise, do not select anything.
                if (parameters.ParametersWithoutDefaultValues.Length + parameters.RemainingEditableParameters.Length > 0)
                {
                    this.SelectedIndex = 1;
                }
                else
                {
                    this.SelectedIndex = null;
                }
            }
            else
            {
                this.SelectedIndex = selectedIndex;
            }
        }
コード例 #4
0
 public ChangeSignatureAnalyzedSucceedContext(
     Document document, int insertPosition, ISymbol symbol, ParameterConfiguration parameterConfiguration)
 {
     Document = document;
     Symbol   = symbol;
     ParameterConfiguration = parameterConfiguration;
     InsertPosition         = insertPosition;
 }
コード例 #5
0
 public ChangeSignatureAnalyzedContext(Solution solution, ISymbol symbol, ParameterConfiguration parameterConfiguration)
 {
     this.CanChangeSignature          = true;
     this.Solution                    = solution;
     this.Symbol                      = symbol;
     this.ParameterConfiguration      = parameterConfiguration;
     this.CannotChangeSignatureReason = CannotChangeSignatureReason.None;
 }
コード例 #6
0
 public ChangeSignatureAnalysisSucceededContext(
     Document document, int positionForTypeBinding, ISymbol symbol, ParameterConfiguration parameterConfiguration)
 {
     Document = document;
     Symbol   = symbol;
     ParameterConfiguration = parameterConfiguration;
     PositionForTypeBinding = positionForTypeBinding;
 }
コード例 #7
0
 public ChangeSignatureAnalyzedContext(Solution solution, ISymbol symbol, ParameterConfiguration parameterConfiguration)
 {
     this.CanChangeSignature = true;
     this.Solution = solution;
     this.Symbol = symbol;
     this.ParameterConfiguration = parameterConfiguration;
     this.CannotChangeSignatureReason = CannotChangeSignatureReason.None;
 }
コード例 #8
0
 public RedactProcessor(ParameterConfiguration parameter)
 {
     RedactFunction = new RedactFunction(new RedactSetting()
     {
         EnablePartialAgeForRedact   = parameter.EnablePartialAgesForRedact,
         EnablePartialDatesForRedact = parameter.EnablePartialDatesForRedact,
     });
 }
コード例 #9
0
 public ChangeSignatureAnalyzedContext(
     Project project, ISymbol symbol, ParameterConfiguration parameterConfiguration)
 {
     this.CanChangeSignature          = true;
     this.Project                     = project;
     this.Symbol                      = symbol;
     this.ParameterConfiguration      = parameterConfiguration;
     this.CannotChangeSignatureReason = CannotChangeSignatureReason.None;
 }
コード例 #10
0
 public DateShiftProcessor(ParameterConfiguration parameter)
 {
     DateShiftFunction = new DateShiftFunction(new DateShiftSetting()
     {
         DateShiftRange = parameter.DateShiftRange,
         DateShiftKey   = parameter.DateShiftKey,
     });
     DateShiftScope = parameter.DateShiftScope;
 }
コード例 #11
0
 public ChangeSignatureAnalyzedContext(
     Project project, ISymbol symbol, ParameterConfiguration parameterConfiguration)
 {
     this.CanChangeSignature = true;
     this.Project = project;
     this.Symbol = symbol;
     this.ParameterConfiguration = parameterConfiguration;
     this.CannotChangeSignatureReason = CannotChangeSignatureReason.None;
 }
コード例 #12
0
ファイル: Z3AxiomProfiler.cs プロジェクト: edgar-pek/VCDryad
        //New Entry, witch is called from the AddIn
        public void load(string BPLFileName, string FunctionName, string PreludeFileName, 
                     int randomSeed, bool randomSeedEnabled, string vcccmdswitches)
        {
            parameterConfiguration = new ParameterConfiguration();
              parameterConfiguration.functionName = FunctionName;
              parameterConfiguration.preludeBplFileInfo = new FileInfo(PreludeFileName);
              parameterConfiguration.codeBplFileInfo = new FileInfo(BPLFileName);
              parameterConfiguration.z3Options = getZ3Setting(randomSeed, randomSeedEnabled);

              loadModelFromBoogie();
        }
コード例 #13
0
        public ChangeSignatureOptionsResult GetChangeSignatureOptions(ISymbol symbol, ParameterConfiguration parameters, INotificationService notificationService)
        {
            var list = parameters.ToListOfParameters();

            return(new ChangeSignatureOptionsResult
            {
                IsCancelled = IsCancelled,
                UpdatedSignature = new SignatureChange(
                    parameters,
                    UpdatedSignature == null ? parameters : ParameterConfiguration.Create(UpdatedSignature.Select(i => list[i]).ToList(), parameters.ThisParameter != null, selectedIndex: 0))
            });
        }
コード例 #14
0
        ChangeSignatureOptionsResult IChangeSignatureOptionsService.GetChangeSignatureOptions(
            Document document,
            int insertPosition,
            ISymbol symbol,
            ParameterConfiguration parameters)
        {
            var list             = parameters.ToListOfParameters();
            var updateParameters = UpdatedSignature != null
                ? UpdatedSignature.Select(item => item.IsExisting?list[item.OldIndex ?? -1] : item.GetAddedParameter(document)).ToImmutableArray()
                : new ImmutableArray <Parameter>();

            return(new ChangeSignatureOptionsResult(new SignatureChange(
                                                        parameters,
                                                        UpdatedSignature == null
                    ? parameters
                    : ParameterConfiguration.Create(updateParameters, parameters.ThisParameter != null, selectedIndex: 0)), previewChanges: false));
        }
コード例 #15
0
ファイル: LoadZ3Form.cs プロジェクト: edgar-pek/VCDryad
 public void setParameterConfiguration(ParameterConfiguration config)
 {
     string allZ3Options = config.z3Options;
       z3FilePath.Text = (config.z3InputFile == null) ? "" : config.z3InputFile;
       z3Timeout.Text = config.timeout.ToString();
       if ( allZ3Options.Contains("PROOF_MODE=2") && allZ3Options.Contains("DISPLAY_PROOF=true") ) {
       rb_proofLogging.Checked = true;
       allZ3Options = allZ3Options.Replace("PROOF_MODE=2", "");
       allZ3Options = allZ3Options.Replace("DISPLAY_PROOF=true", "");
       allZ3Options = allZ3Options.Replace("  ", " ");
       allZ3Options = allZ3Options.Trim();
       }
       else
       {
       rb_proofLogging.Checked = false;
       }
       z3Options.Text = allZ3Options;
 }
コード例 #16
0
ファイル: LoadBoogieForm.cs プロジェクト: edgar-pek/VCDryad
 public void setParameterConfiguration(ParameterConfiguration config)
 {
     string allZ3Options = config.z3Options;
       preludeFileTextBox.Text = (config.preludeBplFileInfo == null) ? "" : config.preludeBplFileInfo.FullName;
       codeFileTextBox.Text = (config.codeBplFileInfo == null) ? "" : config.codeBplFileInfo.FullName;
       boogieOptionTextBox.Text = config.boogieOptions;
       functionTextBox.Text = config.functionName;
       timeoutTextBox.Text = config.timeout.ToString();
       if (allZ3Options.Contains("PROOF_MODE=2") && allZ3Options.Contains("DISPLAY_PROOF=true"))
       {
     rb_proofLogging.Checked = true;
     allZ3Options = allZ3Options.Replace("PROOF_MODE=2", "");
     allZ3Options = allZ3Options.Replace("DISPLAY_PROOF=true", "");
     allZ3Options = allZ3Options.Replace("  ", " ");
     allZ3Options = allZ3Options.Trim();
       }
       else
       {
     rb_proofLogging.Checked = false;
       }
       z3OptionsTextBox.Text = allZ3Options;
 }
        public ChangeSignatureOptionsResult?GetChangeSignatureOptions(
            Document document,
            int insertPosition,
            ISymbol symbol,
            ParameterConfiguration parameters)
        {
            var viewModel = new ChangeSignatureDialogViewModel(
                parameters,
                symbol,
                document,
                insertPosition,
                _classificationFormatMap,
                _classificationTypeMap);

            var dialog = new ChangeSignatureDialog(viewModel);
            var result = dialog.ShowModal();

            if (result.HasValue && result.Value)
            {
                return(new ChangeSignatureOptionsResult(new SignatureChange(parameters, viewModel.GetParameterConfiguration()), previewChanges: viewModel.PreviewChanges));
            }

            return(null);
        }
コード例 #18
0
 public InputParameter(string name, object value, ParameterConfiguration factory = null)
 {
     this.Name          = name;
     this.Value         = value;
     this.Configuration = factory;
 }
コード例 #19
0
        public ChangeSignatureOptionsResult GetChangeSignatureOptions(ISymbol symbol, ParameterConfiguration parameters, INotificationService notificationService)
        {
            var dialog = new SignatureChangeDialog();

            try {
                dialog.Init(symbol, parameters);
                bool performChange = dialog.Run() == (int)Gtk.ResponseType.Ok;
                if (!performChange)
                {
                    return(cancelled);
                }

                return(new ChangeSignatureOptionsResult {
                    IsCancelled = false,
                    UpdatedSignature = new Microsoft.CodeAnalysis.ChangeSignature.SignatureChange(parameters, ParameterConfiguration.Create(dialog.ParameterList, parameters.ThisParameter != null, -1))
                });
            } catch (Exception ex) {
                LoggingService.LogError("Error while signature changing.", ex);
                return(cancelled);
            } finally  {
                dialog.Destroy();
            }
        }
コード例 #20
0
        private void BuildControllerOperations <TDto>(ODataModelBuilder modelBuilder, TypeInfo apiController)
            where TDto : class
        {
            TypeInfo dtoType        = typeof(TDto).GetTypeInfo();
            string   controllerName = GetControllerName(apiController);
            EntitySetConfiguration <TDto> entitySet = modelBuilder.EntitySet <TDto>(controllerName);

            foreach (MethodInfo method in apiController.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                IActionHttpMethodProvider actionHttpMethodProvider =
                    method.GetCustomAttributes().OfType <FunctionAttribute>().Cast <IActionHttpMethodProvider>()
                    .Union(method.GetCustomAttributes().OfType <ActionAttribute>().Cast <IActionHttpMethodProvider>())
                    .SingleOrDefault();

                if (actionHttpMethodProvider != null)
                {
                    bool isFunction = actionHttpMethodProvider is FunctionAttribute;
                    bool isAction   = actionHttpMethodProvider is ActionAttribute;

                    if (!isFunction && !isAction)
                    {
                        continue;
                    }

                    List <ParameterAttribute> actionParameters =
                        method.GetCustomAttributes <ParameterAttribute>().ToList();

                    OperationConfiguration operationConfiguration = null;

                    if (isAction)
                    {
                        operationConfiguration = entitySet.EntityType.Collection.Action(method.Name);
                    }
                    else if (isFunction)
                    {
                        operationConfiguration = entitySet.EntityType.Collection.Function(method.Name);
                    }

                    foreach (ParameterAttribute actionParameter in actionParameters)
                    {
                        if (actionParameter.Type.GetTypeInfo() != typeof(string).GetTypeInfo() &&
                            typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(actionParameter.Type.GetTypeInfo()))
                        {
                            TypeInfo parameterType = actionParameter.Type.GetTypeInfo();

                            if (parameterType.IsArray)
                            {
                                throw new InvalidOperationException($"Use IEnumerable<{parameterType.GetElementType().GetTypeInfo().Name}> instead of {parameterType.GetElementType().GetTypeInfo().Name}[] for parameter {actionParameter.Name} of {actionParameter.Name} in {controllerName} controller");
                            }

                            if (parameterType.IsGenericType)
                            {
                                parameterType = parameterType.GetGenericArguments().Single().GetTypeInfo();
                            }

                            ParameterConfiguration parameter = (ParameterConfiguration)_collectionParameterMethodInfo
                                                               .MakeGenericMethod(parameterType)
                                                               .Invoke(operationConfiguration, new object[] { actionParameter.Name });

                            parameter.OptionalParameter = actionParameter.IsOptional;
                        }
                        else
                        {
                            operationConfiguration.Parameter(actionParameter.Type, actionParameter.Name)
                            .OptionalParameter =
                                actionParameter.IsOptional;
                        }
                    }

                    TypeInfo type = method.ReturnType.GetTypeInfo();

                    if (type.Name != "Void" && type.Name != typeof(Task).GetTypeInfo().Name)
                    {
                        operationConfiguration.OptionalReturn = false;

                        bool isCollection = false;

                        if (typeof(Task).GetTypeInfo().IsAssignableFrom(type))
                        {
                            if (type.IsGenericType)
                            {
                                type = type.GetGenericArguments().Single().GetTypeInfo();
                            }
                        }

                        if (typeof(string) != type && typeof(IEnumerable).IsAssignableFrom(type))
                        {
                            if (type.IsGenericType)
                            {
                                type = type.GetGenericArguments().Single().GetTypeInfo();
                            }
                            else if (type.IsArray)
                            {
                                type = type.GetElementType().GetTypeInfo();
                            }
                            isCollection = true;
                        }

                        if (IsDto(type))
                        {
                            type = GetFinalDtoType(type);

                            if (isCollection == true)
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).ReturnsCollectionFromEntitySet <TDto>(controllerName);
                                }
                                else
                                {
                                    ((FunctionConfiguration)operationConfiguration).ReturnsCollectionFromEntitySet <TDto>(controllerName);
                                }
                            }
                            else
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).ReturnsFromEntitySet <TDto>(controllerName);
                                }
                                else if (isFunction)
                                {
                                    ((FunctionConfiguration)operationConfiguration).ReturnsFromEntitySet <TDto>(controllerName);
                                }
                            }
                        }
                        else
                        {
                            if (isCollection == false)
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).Returns(type);
                                }
                                else if (isFunction)
                                {
                                    ((FunctionConfiguration)operationConfiguration).Returns(type);
                                }
                            }
                            else
                            {
                                operationConfiguration.GetType()
                                .GetTypeInfo()
                                .GetMethod("ReturnsCollection")
                                .MakeGenericMethod(type)
                                .Invoke(operationConfiguration, new object[] { });
                            }
                        }
                    }
                    else
                    {
                        if (isFunction)
                        {
                            throw new InvalidOperationException("Function must have a return type, use action instead");
                        }

                        operationConfiguration.OptionalReturn = true;
                    }
                }
            }
        }
コード例 #21
0
ファイル: Z3AxiomProfiler.cs プロジェクト: edgar-pek/VCDryad
        public bool parseCommandLineArguments(string[] args, out string error)
        {
            bool retval = false;
            int idx;

            ParameterConfiguration config = new ParameterConfiguration();

            config.boogieOptions = "/bv:z /trace";
            config.z3Options = "/rs:0";
            error = "";

            for (idx = 0; idx < args.Length; idx++)
            {
            args[idx] = stripCygdrive(args[idx]);
            if (args[idx].StartsWith("/")) {
              // parse command line parameter switches
              if (args[idx].StartsWith("/f:")) {
                config.functionName = args[idx].Substring(3);
              } else if (args[idx].StartsWith("/l:")) {
                config.z3LogFile = args[idx].Substring(3);
                // minimum requirements have been fulfilled.
                retval = true;
              } else if (args[idx].StartsWith("/t:")) {
                uint timeout;
                if (!UInt32.TryParse(args[idx].Substring(3), out timeout)) {
                  error = String.Format("Cannot parse timeout duration \"{0}\"", args[idx].Substring(3));
                  return false;
                }
                config.timeout = (int)timeout;
              }
              else if (args[idx].StartsWith("/c:"))
              {
                uint ch;
                if (!UInt32.TryParse(args[idx].Substring(3), out ch))
                {
                  error = String.Format("Cannot parse check number \"{0}\"", args[idx].Substring(3));
                  return false;
                }
                config.checkToConsider = (int)ch;
              }
              else if (args[idx] == "/v2")
              {
                // Silently accept old command line argument
              } else if (args[idx] == "/v1") {
                error = String.Format("Z3 version 1 is no longer supported.");
                return false;
              } else if (args[idx] == "/s") {
                config.skipDecisions = true;
              } else {
                error = String.Format("Unknown command line argument \"{0}\".", args[idx]);
                return false;
              }
            } else {
              bool isLogFile = false;
              try {
                using (var s = File.OpenText(args[idx])) {
                  var l = s.ReadLine();
                  if (l.StartsWith("[mk-app]") || l.StartsWith("Z3 error model") || l.StartsWith("partitions:") || l.StartsWith("*** MODEL"))
                    isLogFile = true;
                }
              } catch (Exception) {
              }

              if (isLogFile) {
                config.z3LogFile = args[idx];
                retval = true;
              } else if (config.preludeBplFileInfo == null) {
                config.preludeBplFileInfo = new FileInfo(args[idx]);
              } else if (config.codeBplFileInfo == null) {
                config.codeBplFileInfo = new FileInfo(args[idx]);
                // minimum requirements have been fulfilled.
                retval = true;
              } else {
                error = "Multiple inputs files specified.";
                return false;
              }
            }
            }

            if (retval)
            {
              parameterConfiguration = config;
            }
            return true;
        }
コード例 #22
0
 public SignatureChange(ParameterConfiguration originalConfiguration, ParameterConfiguration updatedConfiguration)
 {
     OriginalConfiguration = originalConfiguration;
     UpdatedConfiguration  = updatedConfiguration;
 }
コード例 #23
0
ファイル: Z3AxiomProfiler.cs プロジェクト: edgar-pek/VCDryad
        private void loadModel(ParameterConfiguration config, Loader.LoaderTask task)
        {
            try {
            // Create a new loader and LoadingProgressForm and execute the loading
            Loader loader = new Loader(config, task);
            LoadingProgressForm lprogf = new LoadingProgressForm(loader);
            lprogf.ShowDialog();

            model = loader.GetModel();
            loadTree();
              } catch (Exception e) {
            MessageBox.Show(String.Format("Cannot load model for current configuration:\n\n\"{0}\"", e));
            return;
              }
        }
コード例 #24
0
        private IFactoryConfiguration ConfigureFactory(XmlNode configNode, IContainer container)
        {
            string factoryName                  = configNode.Attributes["name"].Value;
            string factoryMethodName            = configNode.Attributes["method"].Value;
            IFactoryConfiguration factoryConfig = GetFactoryConfiguration(factoryName, container);

            factoryConfig.Name       = factoryName;
            factoryConfig.MethodName = factoryMethodName;


            if (configNode.Attributes["type"] != null)             //
            {
                string objectTypeString = configNode.Attributes["type"].Value;
                Type   objectType       = ResolveType(objectTypeString);

                factoryConfig.Type = objectType;
            }
            else if (configNode.Attributes["object"] != null)             //instance
            {
                string objectName = configNode.Attributes["object"].Value;
                IObjectConfiguration objectConfig = GetObjectConfiguration(objectName, container);
                factoryConfig.Object = objectConfig;
            }

            foreach (XmlNode factoryNode in configNode)
            {
                #region Parameter

                if (factoryNode.Name == "parameter")
                {
                    ParameterConfiguration parameterConfig = new ParameterConfiguration();
                    parameterConfig.Index = Convert.ToInt32(factoryNode.Attributes["index"].Value);


                    if (factoryNode.Attributes["value"] != null)
                    {
                        string             propertyValueString = factoryNode.Attributes["value"].Value;
                        ValueConfiguration propertyValueConfig = new ValueConfiguration();
                        if (factoryNode.Attributes["type"] != null)
                        {
                            //typed parameter
                            string parameterTypeString = factoryNode.Attributes["type"].Value;
                            Type   parameterType       = ResolveType(parameterTypeString);
                            parameterConfig.Type      = parameterType;
                            propertyValueConfig.Value = Convert.ChangeType(propertyValueString, parameterConfig.Type);
                        }
                        else
                        {
                            //untyped parameter
                            propertyValueConfig.Value = propertyValueString;
                            //		parameterConfig.UntypedStringValue = propertyValueString;
                            parameterConfig.Type = null;
                        }

                        parameterConfig.Value = propertyValueConfig;
                    }

                    if (factoryNode.Attributes["object"] != null)
                    {
                        string parameterObjectName = factoryNode.Attributes["object"].Value;
                        IObjectConfiguration propertyObjectConfig = GetObjectConfiguration(parameterObjectName, container);

                        parameterConfig.Value = propertyObjectConfig;

                        //done
                        if (factoryNode.Attributes["instance-mode"] != null)
                        {
                            string instanceModeString = factoryNode.Attributes["instance-mode"].Value;
                            parameterConfig.InstanceMode = (InstanceMode)InstanceMode.Parse(typeof(InstanceMode), instanceModeString);
                        }
                    }

                    factoryConfig.ParameterConfigurations.Add(parameterConfig);
                }

                #endregion
            }

            return(factoryConfig);
        }
コード例 #25
0
ファイル: LoadZ3LogForm.cs プロジェクト: edgar-pek/VCDryad
 public void setParameterConfiguration(ParameterConfiguration config)
 {
     logFilePath.Text = (config.z3LogFile == null) ? "" : config.z3LogFile;
 }
コード例 #26
0
 public EncryptionProcessor(ParameterConfiguration parameter)
 {
     _key = Encoding.UTF8.GetBytes(parameter.EncryptKey);
 }
コード例 #27
0
        private void BuildControllerOperations <TDto>(ODataModelBuilder odataModelBuilder, TypeInfo apiController)
            where TDto : class
        {
            string controllerName = GetControllerName(apiController);
            EntitySetConfiguration <TDto> entitySet = odataModelBuilder.EntitySet <TDto>(controllerName);

            foreach (MethodInfo method in apiController.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                IActionHttpMethodProvider actionHttpMethodProvider =
                    method.GetCustomAttributes().OfType <IActionHttpMethodProvider>()
                    .ExtendedSingleOrDefault($"Finding ${nameof(IActionHttpMethodProvider)} attribute in {method.Name}");

                if (actionHttpMethodProvider is DeleteAttribute || actionHttpMethodProvider is UpdateAttribute || actionHttpMethodProvider is PartialUpdateAttribute)
                {
                    if (!method.GetParameters().Any(p => p.Name == "key"))
                    {
                        string dtoTypeName       = typeof(TDto).Name;
                        string keyColumnTypeName = DtoMetadataWorkspace.Current.GetKeyColums(typeof(TDto).GetTypeInfo()).ExtendedSingle($"Getting key columns for {dtoTypeName}").PropertyType.Name;
                        string methodDeclartion  = null;
                        if (actionHttpMethodProvider is DeleteAttribute)
                        {
                            methodDeclartion = $"public virtual async Task Delete({keyColumnTypeName} key, CancellationToken cancellationToken)";
                        }
                        else if (actionHttpMethodProvider is PartialUpdateAttribute)
                        {
                            methodDeclartion = $"public virtual async Task<{dtoTypeName}> PartialUpdate({keyColumnTypeName} key, Delta<{dtoTypeName}>, CancellationToken cancellationToken)";
                        }
                        else if (actionHttpMethodProvider is UpdateAttribute)
                        {
                            methodDeclartion = $"public virtual async Task<{dtoTypeName}> Update({keyColumnTypeName} key, {dtoTypeName}, CancellationToken cancellationToken)";
                        }
                        throw new InvalidOperationException($"{apiController.Name}.{method.Name} must have a signature 'like' followings: {methodDeclartion}");
                    }
                }

                if (actionHttpMethodProvider != null)
                {
                    bool isFunction = actionHttpMethodProvider is FunctionAttribute;
                    bool isAction   = actionHttpMethodProvider is ActionAttribute;

                    TypeInfo returnType = method.ReturnType.GetTypeInfo();

                    if (typeof(Task).GetTypeInfo().IsAssignableFrom(returnType))
                    {
                        if (returnType.IsGenericType)
                        {
                            returnType = returnType.GetGenericArguments().ExtendedSingle($"Finding Return type of {method.Name}").GetTypeInfo();
                        }
                    }

                    if (DtoMetadataWorkspace.Current.IsDto(returnType))
                    {
                        throw new InvalidOperationException($"Use SingleResult<{returnType.Name}> to return one {returnType.Name} in {apiController.Name}.{method.Name}");
                    }

                    if (!isFunction && !isAction)
                    {
                        continue;
                    }

                    List <DefaultAutoODataModelBuilderParameterInfo> operationParameters = new List <DefaultAutoODataModelBuilderParameterInfo>();

                    if (isFunction)
                    {
                        foreach (ParameterInfo parameter in method.GetParameters())
                        {
                            TypeInfo parameterType = parameter.ParameterType.GetTypeInfo();
                            if (parameterType == typeof(CancellationToken).GetTypeInfo() || typeof(ODataQueryOptions).IsAssignableFrom(parameterType))
                            {
                                continue;
                            }
                            if (DtoMetadataWorkspace.Current.IsDto(parameterType) || DtoMetadataWorkspace.Current.IsComplexType(parameterType) || IsIEnumerable(parameterType))
                            {
                                // some types which are known to be problematic in functions if you accept them in function parameters. This types list is not complete for sure!
                                throw new InvalidOperationException($"Parameter {parameter.Name} of type {parameter.ParameterType.Name} is not allowed in {apiController.Name}.{method.Name} function.");
                            }
                            operationParameters.Add(new DefaultAutoODataModelBuilderParameterInfo {
                                Name = parameter.Name, Type = parameterType
                            });
                        }
                    }
                    else if (isAction)
                    {
                        ParameterInfo parameter = method
                                                  .GetParameters()
                                                  .ExtendedSingleOrDefault($"Finding parameter of {apiController.Name}.{method.Name}. It's expected to see 0 or 1 parameter only.", p => p.ParameterType.GetTypeInfo() != typeof(CancellationToken).GetTypeInfo() && !typeof(ODataQueryOptions).IsAssignableFrom(p.ParameterType.GetTypeInfo()));

                        if (parameter != null)
                        {
                            TypeInfo parameterType = parameter.ParameterType.GetTypeInfo();

                            if (DtoMetadataWorkspace.Current.IsDto(parameterType) || DtoMetadataWorkspace.Current.IsComplexType(parameterType) || IsIEnumerable(parameterType))
                            {
                                operationParameters.Add(new DefaultAutoODataModelBuilderParameterInfo {
                                    Name = parameter.Name, Type = parameterType
                                });
                            }
                            else if (Nullable.GetUnderlyingType(parameterType) != null || parameterType.IsPrimitive || typeof(string).GetTypeInfo() == parameterType || parameter.ParameterType == typeof(DateTime).GetTypeInfo() || parameter.ParameterType == typeof(DateTimeOffset).GetTypeInfo() || parameter.ParameterType.IsEnum)
                            {
                                // some types which are known to be problematic in actions if you accept them in action parameters directly without any container class. This types list is not complete for sure!
                                throw new InvalidOperationException($"Allowed parameter types for {apiController.Name}.{method.Name} action: | Dto | Complex Type | Classes like pulic class {method.Name}Args {{ public {parameter.ParameterType.Name} {parameter.Name} {{ get; set; }} }} | IEnumerable<T> (For example IEnumerable<int> or IEnumerable<MyDtoClass> | You may not define a parameter of type {parameter.ParameterType.Name}.");
                            }
                            else
                            {
                                foreach (PropertyInfo prop in parameter.ParameterType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                                {
                                    operationParameters.Add(new DefaultAutoODataModelBuilderParameterInfo {
                                        Name = prop.Name, Type = prop.PropertyType.GetTypeInfo()
                                    });
                                }
                            }
                        }
                    }

                    OperationConfiguration operationConfiguration = null;

                    if (isAction)
                    {
                        operationConfiguration = entitySet.EntityType.Collection.Action(method.Name);
                    }
                    else if (isFunction)
                    {
                        operationConfiguration = entitySet.EntityType.Collection.Function(method.Name);
                    }

                    foreach (DefaultAutoODataModelBuilderParameterInfo operationParameter in operationParameters)
                    {
                        TypeInfo parameterType = operationParameter.Type;

                        if (IsIEnumerable(operationParameter.Type))
                        {
                            if (parameterType.IsArray)
                            {
                                throw new InvalidOperationException($"Use IEnumerable<{parameterType.GetElementType().GetTypeInfo().Name}> instead of {parameterType.GetElementType().GetTypeInfo().Name}[] for parameter {operationParameter.Name} of {operationParameter.Name} in {controllerName} controller");
                            }

                            if (parameterType.IsGenericType)
                            {
                                parameterType = parameterType.GetGenericArguments().ExtendedSingle($"Finding parameter type from generic arguments of {parameterType.Name}").GetTypeInfo();
                            }

                            ParameterConfiguration parameter = (ParameterConfiguration)_collectionParameterMethodInfo
                                                               .MakeGenericMethod(parameterType)
                                                               .Invoke(operationConfiguration, new object[] { operationParameter.Name });
                            parameter.Nullable = operationParameter.IsOptional;
                        }
                        else
                        {
                            operationConfiguration.Parameter(parameterType, operationParameter.Name).Nullable = operationParameter.IsOptional;
                        }
                    }

                    if (returnType.Name != "Void" && returnType.Name != typeof(Task).GetTypeInfo().Name)
                    {
                        operationConfiguration.ReturnNullable = false;

                        if (typeof(SingleResult).GetTypeInfo().IsAssignableFrom(returnType))
                        {
                            if (returnType.IsGenericType)
                            {
                                returnType = returnType.GetGenericArguments().ExtendedSingle($"Finding Return type of {method.Name}").GetTypeInfo();
                            }
                        }

                        bool isCollection = false;

                        if (IsIEnumerable(returnType))
                        {
                            if (returnType.IsGenericType)
                            {
                                returnType = returnType.GetGenericArguments().ExtendedSingle($"Finding Return type of {method.Name}").GetTypeInfo();
                            }
                            else if (returnType.IsArray)
                            {
                                returnType = returnType.GetElementType().GetTypeInfo();
                            }
                            isCollection = true;
                        }

                        if (DtoMetadataWorkspace.Current.IsDto(returnType))
                        {
                            returnType = DtoMetadataWorkspace.Current.GetFinalDtoType(returnType);

                            if (isCollection == true)
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).ReturnsCollectionFromEntitySet <TDto>(controllerName);
                                }
                                else
                                {
                                    ((FunctionConfiguration)operationConfiguration).ReturnsCollectionFromEntitySet <TDto>(controllerName);
                                }
                            }
                            else
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).ReturnsFromEntitySet <TDto>(controllerName);
                                }
                                else if (isFunction)
                                {
                                    ((FunctionConfiguration)operationConfiguration).ReturnsFromEntitySet <TDto>(controllerName);
                                }
                            }
                        }
                        else
                        {
                            if (isCollection == false)
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).Returns(returnType);
                                }
                                else if (isFunction)
                                {
                                    ((FunctionConfiguration)operationConfiguration).Returns(returnType);
                                }
                            }
                            else
                            {
                                operationConfiguration.GetType()
                                .GetTypeInfo()
                                .GetMethod("ReturnsCollection")
                                .MakeGenericMethod(returnType)
                                .Invoke(operationConfiguration, Array.Empty <object>());
                            }
                        }
                    }
                    else
                    {
                        if (isFunction)
                        {
                            throw new InvalidOperationException($"Function {method.Name} in {apiController.Name} must have a return type, use action instead");
                        }

                        operationConfiguration.ReturnNullable = true;
                    }
                }
            }
        }
コード例 #28
0
 public CryptoHashProcessor(ParameterConfiguration parameter)
 {
     _cryptoHashKey = Encoding.UTF8.GetBytes(parameter.CryptoHashKey);
 }
コード例 #29
0
        private MethodInfo MatchMethods(FactoryConfiguration factory, Type type, string methodName, bool isStatic)
        {
            MethodInfo[] methods         = type.GetMethods();
            MethodInfo   bestMethodMatch = null;
            int          bestScore       = int.MaxValue;


            foreach (MethodInfo method in methods)
            {
                if (method.Name != methodName)
                {
                    continue;
                }

                int             score      = 0;
                ParameterInfo[] parameters = method.GetParameters();

                //if param count doesnt match , move to next ctor
                if (parameters.Length != factory.ParameterConfigurations.Count)
                {
                    continue;
                }

                if (parameters.Length == 0)
                {
                    return(method);
                }

                #region Match parameters

                for (int i = 0; i < parameters.Length; i++)
                {
                    ParameterConfiguration parameterConfig = (ParameterConfiguration)factory.ParameterConfigurations[i];
                    Type type1 = parameters[i].ParameterType;
                    Type type2 = parameterConfig.Type;
                    if (type2 == null)
                    {
                        //untyped parameter
                        try
                        {
                            ValueConfiguration parameterValueConfig = (ValueConfiguration)parameterConfig.Value;
                            object             res = Convert.ChangeType(parameterValueConfig.Value, type1);
                        }
                        catch
                        {
                            continue;
                        }
                        score++;
                    }
                    else
                    {
                        //typed parameter

                        if (type1.IsAssignableFrom(type2))
                        {
                            if (type1 == type2)
                            {
                                //same type
                                score++;
                            }
                            else if (type2.IsSubclassOf(type1))
                            {
                                //subclass
                                Type tmpType = type2;
                                while (tmpType != type1)
                                {
                                    score++;
                                    tmpType = tmpType.BaseType;
                                }
                            }
                            else
                            {
                                //interface
                                score++;
                            }
                        }
                        else
                        {
                            //ignore this
                            continue;
                        }
                    }
                }

                #endregion

                if (score < bestScore && score != 0)
                {
                    bestMethodMatch = method;
                    bestScore       = score;
                }
            }
            return(bestMethodMatch);
        }
コード例 #30
0
 public TSelf ConfigureParameters(Action <ICommandParameterizationContext, TParameters> parameters)
 {
     ParameterConfiguration.Add(parameters);
     return((TSelf)this);
 }
コード例 #31
0
        private void BuildControllerOperations <TDto>(ODataModelBuilder odataModelBuilder, TypeInfo apiController)
            where TDto : class
        {
            string controllerName = GetControllerName(apiController);
            EntitySetConfiguration <TDto> entitySet = odataModelBuilder.EntitySet <TDto>(controllerName);

            foreach (MethodInfo method in apiController.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                IActionHttpMethodProvider actionHttpMethodProvider =
                    method.GetCustomAttributes().OfType <FunctionAttribute>().Cast <IActionHttpMethodProvider>()
                    .Union(method.GetCustomAttributes().OfType <ActionAttribute>().Cast <IActionHttpMethodProvider>())
                    .ExtendedSingleOrDefault($"Finding ${nameof(IActionHttpMethodProvider)} attribute in {method.Name}");

                if (actionHttpMethodProvider != null)
                {
                    bool isFunction = actionHttpMethodProvider is FunctionAttribute;
                    bool isAction   = actionHttpMethodProvider is ActionAttribute;

                    if (!isFunction && !isAction)
                    {
                        continue;
                    }

                    List <DefaultAutoODataModelBuilderParameterInfo> operationParameters = new List <DefaultAutoODataModelBuilderParameterInfo>();

                    if (isFunction)
                    {
                        foreach (ParameterInfo parameter in method.GetParameters())
                        {
                            if (parameter.ParameterType.GetTypeInfo() == typeof(CancellationToken).GetTypeInfo() || typeof(ODataQueryOptions).IsAssignableFrom(parameter.ParameterType.GetTypeInfo()))
                            {
                                continue;
                            }
                            operationParameters.Add(new DefaultAutoODataModelBuilderParameterInfo {
                                Name = parameter.Name, Type = parameter.ParameterType.GetTypeInfo()
                            });
                        }
                    }
                    else if (isAction)
                    {
                        ParameterInfo parameter = method
                                                  .GetParameters()
                                                  .ExtendedSingleOrDefault($"Finding parameter of {method.Name}", p => p.ParameterType.GetTypeInfo() != typeof(CancellationToken).GetTypeInfo() && !typeof(ODataQueryOptions).IsAssignableFrom(p.ParameterType.GetTypeInfo()));

                        if (parameter != null)
                        {
                            foreach (PropertyInfo prop in parameter.ParameterType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                            {
                                operationParameters.Add(new DefaultAutoODataModelBuilderParameterInfo {
                                    Name = prop.Name, Type = prop.PropertyType.GetTypeInfo()
                                });
                            }
                        }
                    }

                    OperationConfiguration operationConfiguration = null;

                    if (isAction)
                    {
                        operationConfiguration = entitySet.EntityType.Collection.Action(method.Name);
                    }
                    else if (isFunction)
                    {
                        operationConfiguration = entitySet.EntityType.Collection.Function(method.Name);
                    }

                    foreach (DefaultAutoODataModelBuilderParameterInfo operationParameter in operationParameters)
                    {
                        TypeInfo parameterType = operationParameter.Type;

                        if (operationParameter.Type.GetTypeInfo() != typeof(string).GetTypeInfo() &&
                            typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(operationParameter.Type))
                        {
                            if (parameterType.IsArray)
                            {
                                throw new InvalidOperationException($"Use IEnumerable<{parameterType.GetElementType().GetTypeInfo().Name}> instead of {parameterType.GetElementType().GetTypeInfo().Name}[] for parameter {operationParameter.Name} of {operationParameter.Name} in {controllerName} controller");
                            }

                            if (parameterType.IsGenericType)
                            {
                                parameterType = parameterType.GetGenericArguments().ExtendedSingle($"Finding parameter type from generic arguments of {parameterType.Name}").GetTypeInfo();
                            }

                            ParameterConfiguration parameter = (ParameterConfiguration)_collectionParameterMethodInfo
                                                               .MakeGenericMethod(parameterType)
                                                               .Invoke(operationConfiguration, new object[] { operationParameter.Name });
                            parameter.Nullable = operationParameter.IsOptional;
                        }
                        else
                        {
                            operationConfiguration.Parameter(parameterType, operationParameter.Name).Nullable = operationParameter.IsOptional;
                        }
                    }

                    TypeInfo type = method.ReturnType.GetTypeInfo();

                    if (type.Name != "Void" && type.Name != typeof(Task).GetTypeInfo().Name)
                    {
                        operationConfiguration.ReturnNullable = false;

                        bool isCollection = false;

                        if (typeof(Task).GetTypeInfo().IsAssignableFrom(type))
                        {
                            if (type.IsGenericType)
                            {
                                type = type.GetGenericArguments().ExtendedSingle($"Finding Return type of {method.Name}").GetTypeInfo();
                            }
                        }

                        if (typeof(SingleResult).GetTypeInfo().IsAssignableFrom(type))
                        {
                            if (type.IsGenericType)
                            {
                                type = type.GetGenericArguments().ExtendedSingle($"Finding Return type of {method.Name}").GetTypeInfo();
                            }
                        }

                        if (typeof(string) != type && typeof(IEnumerable).IsAssignableFrom(type))
                        {
                            if (type.IsGenericType)
                            {
                                type = type.GetGenericArguments().ExtendedSingle($"Finding Return type of {method.Name}").GetTypeInfo();
                            }
                            else if (type.IsArray)
                            {
                                type = type.GetElementType().GetTypeInfo();
                            }
                            isCollection = true;
                        }

                        if (DtoMetadataWorkspace.Current.IsDto(type))
                        {
                            type = DtoMetadataWorkspace.Current.GetFinalDtoType(type);

                            if (isCollection == true)
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).ReturnsCollectionFromEntitySet <TDto>(controllerName);
                                }
                                else
                                {
                                    ((FunctionConfiguration)operationConfiguration).ReturnsCollectionFromEntitySet <TDto>(controllerName);
                                }
                            }
                            else
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).ReturnsFromEntitySet <TDto>(controllerName);
                                }
                                else if (isFunction)
                                {
                                    ((FunctionConfiguration)operationConfiguration).ReturnsFromEntitySet <TDto>(controllerName);
                                }
                            }
                        }
                        else
                        {
                            if (isCollection == false)
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).Returns(type);
                                }
                                else if (isFunction)
                                {
                                    ((FunctionConfiguration)operationConfiguration).Returns(type);
                                }
                            }
                            else
                            {
                                operationConfiguration.GetType()
                                .GetTypeInfo()
                                .GetMethod("ReturnsCollection")
                                .MakeGenericMethod(type)
                                .Invoke(operationConfiguration, Array.Empty <object>());
                            }
                        }
                    }
                    else
                    {
                        if (isFunction)
                        {
                            throw new InvalidOperationException($"Function {method.Name} in {apiController.Name} must have a return type, use action instead");
                        }

                        operationConfiguration.ReturnNullable = true;
                    }
                }
            }
        }
コード例 #32
0
        private IObjectConfiguration ConfigureObject(XmlNode configNode, IContainer container)
        {
            string objectName = configNode.Attributes["name"].Value;
            IObjectConfiguration objectConfig = GetObjectConfiguration(objectName, container);

            objectConfig.Name = objectName;


            if (configNode.Attributes["aop-config"] != null)
            {
                string  sectionName = configNode.Attributes["aop-config"].Value;
                IEngine engine      = NAspect.Framework.ApplicationContext.ConfigureFromSection(sectionName);
                objectConfig.AopEngine = engine;
            }

            if (configNode.Attributes["type"] != null)
            {
                string objectTypeString = configNode.Attributes["type"].Value;
                Type   objectType       = ResolveType(objectTypeString);
                objectConfig.Type = objectType;
            }

            if (configNode.Attributes["factory"] != null)
            {
                string factoryName = configNode.Attributes["factory"].Value;
                IFactoryConfiguration factoryConfig = GetFactoryConfiguration(factoryName, container);
                objectConfig.InstanceValue = factoryConfig;
            }


            //done
            if (configNode.Attributes["instance-mode"] != null)
            {
                string instanceModeString = configNode.Attributes["instance-mode"].Value;
                objectConfig.InstanceMode = (InstanceMode)InstanceMode.Parse(typeof(InstanceMode), instanceModeString);
            }

            container.Configuration.AddObjectConfiguration(objectConfig);

            foreach (XmlNode objectNode in configNode)
            {
                #region property

                if (objectNode.Name == "property")
                {
                    PropertyConfiguration propertyConfig = new PropertyConfiguration();
                    propertyConfig.Name = objectNode.Attributes["name"].Value;
                    ConfigureElement(objectNode, propertyConfig, container, null);
                    if (objectNode.Attributes["action"] != null)
                    {
                        string action = objectNode.Attributes["action"].Value;
                        if (action == "Add")
                        {
                            propertyConfig.ListAction = ListAction.Add;
                        }

                        if (action == "Replace")
                        {
                            propertyConfig.ListAction = ListAction.Replace;
                        }
                    }

                    objectConfig.PropertyConfigurations.Add(propertyConfig);
                }

                #endregion

                #region Ctor Parameter

                if (objectNode.Name == "ctor-parameter")
                {
                    ParameterConfiguration parameterConfig = new ParameterConfiguration();
                    parameterConfig.Index = Convert.ToInt32(objectNode.Attributes["index"].Value);
                    ConfigureElement(objectNode, parameterConfig, container, null);
                    objectConfig.CtorParameterConfigurations.Add(parameterConfig);
                }

                #endregion
            }
            return(objectConfig);
        }
コード例 #33
0
ファイル: Z3AxiomProfiler.cs プロジェクト: edgar-pek/VCDryad
        public void loadModelFromBoogie()
        {
            LoadBoogieForm loadform = new LoadBoogieForm(launchedFromAddin, ctrl);
              if (parameterConfiguration != null)
              {
            loadform.setParameterConfiguration(parameterConfiguration);
              }
              else
              {
            loadform.reloadParameterConfiguration();
              }

              DialogResult dialogResult;

              dialogResult = loadform.ShowDialog();
              if (dialogResult != DialogResult.OK)
            return;

              parameterConfiguration = loadform.GetParameterConfiguration();
              ParameterConfiguration.saveParameterConfigurationToSettings(parameterConfiguration);

              loadModel(parameterConfiguration, Loader.LoaderTask.LoaderTaskBoogie);
        }
コード例 #34
0
        public ChangeSignatureOptionsResult GetChangeSignatureOptions(ISymbol symbol, ParameterConfiguration parameters)
        {
            var viewModel = new ChangeSignatureDialogViewModel(parameters, symbol, _classificationFormatMap, _classificationTypeMap);

            var dialog = new ChangeSignatureDialog(viewModel);
            var result = dialog.ShowModal();

            if (result.HasValue && result.Value)
            {
                return(new ChangeSignatureOptionsResult {
                    IsCancelled = false, UpdatedSignature = new SignatureChange(parameters, viewModel.GetParameterConfiguration()), PreviewChanges = viewModel.PreviewChanges
                });
            }
            else
            {
                return(new ChangeSignatureOptionsResult {
                    IsCancelled = true
                });
            }
        }
コード例 #35
0
        private ConstructorInfo MatchConstructors(ObjectConfiguration objectConfig)
        {
            try
            {
                ConstructorInfo[] constructors  = objectConfig.Type.GetConstructors();
                ConstructorInfo   bestCtorMatch = null;
                int bestScore = int.MaxValue;


                foreach (ConstructorInfo constructor in constructors)
                {
                    int             score          = 0;
                    ParameterInfo[] ctorParameters = constructor.GetParameters();

                    //if param count doesnt match , move to next ctor
                    if (ctorParameters.Length != objectConfig.CtorParameterConfigurations.Count)
                    {
                        continue;
                    }

                    if (ctorParameters.Length == 0)
                    {
                        return(constructor);
                    }

                    #region Match parameters

                    for (int i = 0; i < ctorParameters.Length; i++)
                    {
                        ParameterConfiguration parameterConfig = (ParameterConfiguration)objectConfig.CtorParameterConfigurations[i];
                        Type type1 = ctorParameters[i].ParameterType;
                        Type type2 = parameterConfig.Type;
                        if (type2 == null)
                        {
                            ValueConfiguration parameterValueConfig = (ValueConfiguration)parameterConfig.Value;

                            if (parameterValueConfig.TypeConverter != null)
                            {
                                if (parameterValueConfig.TypeConverter.CanConvertTo(type1))
                                {
                                    score++;
                                }
                                else
                                {
                                    break;
                                }
                            }
                            else
                            {
                                //untyped parameter
                                try
                                {
                                    if (type1.IsEnum && parameterValueConfig.Value is string)
                                    {
                                        object res = Enum.Parse(type1, parameterValueConfig.Value.ToString());
                                    }
                                    else
                                    {
                                        object res = Convert.ChangeType(parameterValueConfig.Value, type1);
                                    }
                                }
                                catch
                                {
                                    break;
                                }
                                score++;
                            }
                        }
                        else
                        {
                            //typed parameter

                            if (type1.IsAssignableFrom(type2))
                            {
                                if (type1 == type2)
                                {
                                    //same type
                                    score++;
                                }
                                else if (type2.IsSubclassOf(type1))
                                {
                                    //subclass
                                    Type tmpType = type2;
                                    while (tmpType != type1)
                                    {
                                        score++;
                                        tmpType = tmpType.BaseType;
                                    }
                                }
                                else
                                {
                                    //interface
                                    score++;
                                }
                            }
                            else
                            {
                                //ignore this
                                break;
                            }
                        }
                    }

                    #endregion

                    if (score < bestScore && score != 0)
                    {
                        bestCtorMatch = constructor;
                        bestScore     = score;
                    }
                }
                return(bestCtorMatch);
            }
            catch (Exception x)
            {
                throw new Exception(string.Format("could not match constructor for object '{0}'", objectConfig.Name), x);
            }
        }