Ejemplo n.º 1
0
		public void AddSubOption(IOption option, PolicyOptionScopeEnum policyScope)
		{
			option.PropertyChanged += OnPropertyChanged;
            if (SubOptions[(int)policyScope] != null)
                throw new InvalidOperationException("Duplicate policy scope specified for same area option");
            SubOptions[(int)policyScope] = option;
		}
Ejemplo n.º 2
0
 public override bool DisplayOptionToUser(IOption option, Interfaces.IScriptBaseObject iteratorObject)
 {
     try
     {
         if (option.DisplayToUserValue.HasValue)
         {
             return option.DisplayToUserValue.Value;
         }
         if (string.IsNullOrEmpty(option.DisplayToUserFunction))
         {
             return true;
         }
         if (iteratorObject == null)
         {
             object[] parameters = new object[0];
             return (bool)Loader.Instance.CallTemplateFunction(option.DisplayToUserFunction, ref parameters);
         }
         else
         {
             object[] parameters = new object[] { iteratorObject };
             return (bool)Loader.Instance.CallTemplateFunction(option.DisplayToUserFunction, ref parameters);
         }
     }
     catch (MissingMethodException)
     {
         object[] parameters = new object[] { iteratorObject };
         return (bool)Loader.Instance.CallTemplateFunction(option.DisplayToUserFunction, ref parameters);
     }
 }
Ejemplo n.º 3
0
        protected override Tuple<string, string> GetCollectionPathAndPropertyNameForOption(IOption key, string languageName)
        {
            if (key.Feature == EditorComponentOnOffOptions.OptionName)
            {
                return Tuple.Create(@"Roslyn\Internal\OnOff\Components", key.Name);
            }
            else if (key.Feature == InternalFeatureOnOffOptions.OptionName)
            {
                return Tuple.Create(@"Roslyn\Internal\OnOff\Features", key.Name);
            }
            else if (key.Feature == PerformanceFunctionIdOptionsProvider.Name)
            {
                return Tuple.Create(@"Roslyn\Internal\Performance\FunctionId", key.Name);
            }
            else if (key.Feature == LoggerOptions.FeatureName)
            {
                return Tuple.Create(@"Roslyn\Internal\Performance\Logger", key.Name);
            }
            else if (key.Feature == InternalDiagnosticsOptions.OptionName)
            {
                return Tuple.Create(@"Roslyn\Internal\Diagnostics", key.Name);
            }
            else if (key.Feature == InternalSolutionCrawlerOptions.OptionName)
            {
                return Tuple.Create(@"Roslyn\Internal\SolutionCrawler", key.Name);
            }
            else if (key.Feature == CacheOptions.FeatureName)
            {
                return Tuple.Create(@"Roslyn\Internal\Performance\Cache", key.Name);
            }

            throw ExceptionUtilities.Unreachable;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Returns the Greek object for a given Greek name
        /// </summary>
        /// <param name="greek">Greek name</param>
        /// <param name="option">Option object</param>
        /// <returns></returns>
        public static IGreek Create(GreekName greek, IOption option)
        {
            IGreek calculatedGreek = null;

            switch (greek)
            {
                case GreekName.Delta:
                    calculatedGreek = new Delta(option);
                    break;
                case GreekName.Gamma:
                    calculatedGreek = new Gamma(option);
                    break;
                case GreekName.Theta:
                    calculatedGreek = new Theta(option);
                    break;
                case GreekName.Vega:
                    calculatedGreek = new Vega(option);
                    break;
                case GreekName.Rho:
                    calculatedGreek = new Rho(option);
                    break;
                default:
                    break;
            }

            return calculatedGreek;
        }
Ejemplo n.º 5
0
 public static ITaggerEventSource OnOptionChanged(
     ITextBuffer subjectBuffer,
     IOption option,
     TaggerDelay delay)
 {
     return new OptionChangedEventSource(subjectBuffer, option, delay);
 }
Ejemplo n.º 6
0
 protected void AddOption(Panel panel, IOption option, string additional = null)
 {
     var uiElement = CreateControl(option, additional: additional);
     if (uiElement != null)
     {
         panel.Children.Add(uiElement);
     }
 }
 private void AddOption(StackPanel panel, IOption option)
 {
     var uiElement = CreateControl(option);
     if (uiElement != null)
     {
         panel.Children.Add(uiElement);
     }
 }
 private void AddPerLanguageOption(StackPanel panel, IOption option, string languageName)
 {
     var uiElement = CreateControl(option, languageName);
     if (uiElement != null)
     {
         panel.Children.Add(uiElement);
     }
 }
Ejemplo n.º 9
0
        public AlreadySelectedException(IOptionGroup group, IOption option, IOption selected)
            : this("The option '" + option.Key() + "' was specified but an option from this group "
				   + "has already been selected: '" + selected.Key() + "'")
        {
            OptionGroup = group;
            Option = option;
            SelectedOption = selected;
        }
Ejemplo n.º 10
0
        public IEnumerable<IOption> GetSubOptions(IOption selectedOption, string term)
        {
            var fileOption = selectedOption as FileOption;
            if(fileOption == null)
                return Enumerable.Empty<IOption>();

            return new IOption[] { new OpenContainingDirectoryOption(fileOption) };
        }
Ejemplo n.º 11
0
        public AbstractCheckBoxViewModel(IOption option, string description, string truePreview, string falsePreview, AbstractOptionPreviewViewModel info)
        {
            _truePreview = truePreview;
            _falsePreview = falsePreview;

            Info = info;
            Option = option;
            Description = description;
        }
Ejemplo n.º 12
0
 public CheckBoxOptionViewModel(IOption option, string description, string truePreview, string falsePreview, AbstractOptionPreviewViewModel info, OptionSet options)
 {
     this.Option = option;
     Description = description;
     _truePreview = truePreview;
     _falsePreview = falsePreview;
     _info = info;
     SetProperty(ref _isChecked, (bool)options.GetOption(new OptionKey(option, option.IsPerLanguage ? info.Language : null)));
 }
Ejemplo n.º 13
0
 public ActionButton(string _txt, string _assetName, Rectangle _rect, Game1.Actions _actionType, Game1 _game1, IOption<Animal> _animal)
 {
     this.txt = _txt;
     this.assetName = _assetName;
     this.rect = _rect;
     this.actionType = _actionType;
     this.animal = _animal;
     _game1.buttonList.Add(this);
     this.game1 = _game1;
 }
Ejemplo n.º 14
0
        public IEnumerable<IOption> GetSubOptions(IOption selectedOption, string term)
        {
            var option = selectedOption as ModuleOption;
            if(option == null) return Enumerable.Empty<IOption>();

            if(option.Module == this)
                return _modules.Value.Select(m => new ModuleOption(m)).FuzzySearch(term).Fetch();

            return option.Module.GetOptions(term);
        }
		public GeneralOptionView(IOption option)
		{
			if(option == null)
				throw new ArgumentNullException("option");

			_option = option;

			//初始化窗体组件
			InitializeComponent();
		}
Ejemplo n.º 16
0
        public void Describe(string reason, Action action)
        {
            var group = new ExampleGroup { Reason = reason };
            expression.Add(group);
            currentExampleGroupOption = group.SomeOrNone();

            action();
            
            currentExampleGroupOption = Option.None<ExampleGroup>();
        }
Ejemplo n.º 17
0
        public CheckBoxWithComboOptionViewModel(IOption option, string description, string truePreview, string falsePreview, AbstractOptionPreviewViewModel info, OptionSet options, IList<NotificationOptionViewModel> items)
            : base(option, description, truePreview, falsePreview, info)
        {
            NotificationOptions = items;

            var codeStyleOption = ((CodeStyleOption<bool>)options.GetOption(new OptionKey(option, option.IsPerLanguage ? info.Language : null)));
            SetProperty(ref _isChecked, codeStyleOption.Value);

            var notificationViewModel = items.Where(i => i.Notification.Value == codeStyleOption.Notification.Value).Single();
            SetProperty(ref _selectedNotificationOption, notificationViewModel);
        }
Ejemplo n.º 18
0
 internal static bool MatchesSearch(IOption opt, string searchText)
 {
     if (!string.IsNullOrEmpty(opt.DisplayName))
     {
         int dispIndex = opt.DisplayName.IndexOf(searchText, 0, StringComparison.InvariantCultureIgnoreCase);
         if (dispIndex != -1)
             return true;
     }
     int index = opt.Name.IndexOf(searchText, 0, StringComparison.InvariantCultureIgnoreCase);
     return (index > -1);
 }
Ejemplo n.º 19
0
        private TreeNode CreateOptionNode(TreeNode containerNode, IOption option)
        {
            TreeNode node = new TreeNode(option.VariableName) { Tag = option };
            containerNode.Nodes.Add(node);
            UpdateTreeNodeText(option, "VariableName", node);
            // On force une mise à jour pour mettre l'interface à jour
            string a = option.VariableName;
            option.VariableName = string.Empty;
            option.VariableName = a;

            return node;
        }
        private void SetChangedOption(IOptionService optionService, IOption option, string languageName)
        {
            OptionKey key = new OptionKey(option, languageName);

            object currentValue;
            if (this.TryFetch(key, out currentValue))
            {
                OptionSet optionSet = optionService.GetOptions();
                optionSet = optionSet.WithChangedOption(key, currentValue);

                optionService.SetOptions(optionSet);
            }
        }
        private string[] ExtractOptionArgs(Queue<string> argQueue, IOption option)
        {
            string[] arguments;
            if (option != null && option.ParameterCount > 0 && argQueue.Count > 0 && !argQueue.Peek().StartsWith("/"))
            {
                if (option.IsBoolean && !IsBoolValue(argQueue.Peek()))
                    arguments = new string[] {};
                else
                    arguments = option.ParameterCount == 1 ? new[] { argQueue.Dequeue() } : argQueue.Dequeue().Split(',');
            }
            else
                arguments = new string[] {};

            return arguments;
        }
Ejemplo n.º 22
0
        protected override String[] Flatten(Options options, string[] arguments, bool stopAtNonOption)
        {
            Init();

            int argc = arguments.Length;

            for (int i = 0; i < argc; i++) {
                // get the next command line token
                string token = arguments[i];

                // handle long option --foo or --foo=bar
                if (token.StartsWith("--")) {
                    int pos = token.IndexOf('=');
                    String opt = pos == -1 ? token : token.Substring(0, pos); // --foo

                    if (!options.HasOption(opt)) {
                        ProcessNonOptionToken(token, stopAtNonOption);
                    } else {
                        currentOption = options.GetOption(opt);

                        tokens.Add(opt);
                        if (pos != -1) {
                            tokens.Add(token.Substring(pos + 1));
                        }
                    }
                }

                // single hyphen
                else if ("-".Equals(token)) {
                    tokens.Add(token);
                } else if (token.StartsWith("-")) {
                    if (token.Length == 2 || options.HasOption(token)) {
                        ProcessOptionToken(options, token, stopAtNonOption);
                    }
                        // requires bursting
                    else {
                        BurstToken(options, token, stopAtNonOption);
                    }
                } else {
                    ProcessNonOptionToken(token, stopAtNonOption);
                }

                Gobble(arguments, ref i);
            }

            return (String[])tokens.ToArray(typeof(String));
        }
        public BooleanCodeStyleOptionViewModel(
            IOption option, 
            string description, 
            string truePreview, 
            string falsePreview, 
            AbstractOptionPreviewViewModel info, 
            OptionSet options, 
            string groupName, 
            List<CodeStylePreference> preferences = null, 
            List<NotificationOptionViewModel> notificationPreferences = null) 
            : base(option, description, truePreview, falsePreview, info, options, groupName, preferences, notificationPreferences)
        {
            var booleanOption = (bool)options.GetOption(new OptionKey(option, option.IsPerLanguage ? info.Language : null));
            _selectedPreference = Preferences.Single(c => c.IsChecked == booleanOption);

            NotifyPropertyChanged(nameof(SelectedPreference));
        }
Ejemplo n.º 24
0
        private static ExpandoObject GetExpandoObject(IOption<Member> firstMember, IEnumerable<Member> otherMembers)
        {
            var expandoObject = new ExpandoObject();
            var d = (IDictionary<string, object>)expandoObject;

            if (firstMember.IsDefined)
            {
                var member = firstMember.Get();
                d.Add(member.Name, member.Value);
            }

            foreach (var member in otherMembers)
            {
                d.Add(member.Name, member.Value);
            }

            return expandoObject;
        }
        private static bool TryGetKeyPathAndName(IOption option, out string path, out string key)
        {
            var serialization = option.StorageLocations.OfType<LocalUserProfileStorageLocation>().SingleOrDefault();

            if (serialization == null)
            {
                path = null;
                key = null;
                return false;
            }
            else
            {
                // We'll just use the filesystem APIs to decompose this
                path = Path.GetDirectoryName(serialization.KeyName);
                key = Path.GetFileName(serialization.KeyName);
                return true;
            }
        }
Ejemplo n.º 26
0
        private static ExpandoObject GetExpandoObject(
            IOption<Member> member,
            IEnumerable<Member> rest)
        {
            var expandoObject = new ExpandoObject();
            var dictionary = (IDictionary<string, object>)expandoObject;

            if (member.IsDefined)
            {
                dictionary.Add(member.Get().Name, member.Get().Value);

                foreach (var m in rest)
                {
                    dictionary.Add(m.Name, m.Value);
                }
            }

            return expandoObject;
        }
        private string[] ExtractOptionArgs(string input, Queue<string> argQueue, IOption option)
        {
            var colonPos = input.IndexOf(':');
            if (colonPos <= 0)
            {
                string[] arguments;
                if ((option == null || (option.ParameterCount > 0 && argQueue.Count > 0)) && (argQueue.Count > 0 && !argQueue.Peek().StartsWith("-")))
                    arguments = option == null || option.ParameterCount > 1 ? argQueue.Dequeue().Split(',') : new []{ argQueue.Dequeue() };
                else
                    arguments = new string[] {};

                return arguments;
            }

            var optionText = input.Substring(colonPos + 1);
            return option == null || option.ParameterCount > 1
                ? optionText.Split(',')
                : new [] { optionText };
        }
Ejemplo n.º 28
0
        private void UpdateOption(IOption opt)
        {
            if (opt is IOptionWithSubOptions)
            {
                foreach (IOption subOpt in (opt as IOptionWithSubOptions).SubOptions)
                    UpdateOption(subOpt);
            }

            RenderingOptionInfo roi = _options.Where(oi => oi.Name == opt.Name).FirstOrDefault();
            if (roi != null)
            {
                roi.Value = opt.StringValue;
            }
            else
            {
                if (!(opt is IOptionWithSubOptions))
                    throw new NotImplementedException();
            }

        }
Ejemplo n.º 29
0
        public TokenFloat(IOption<IEnumerable<char>> minus, string number1, string number2)
        {
            StringBuilder sb = new StringBuilder();
            if (minus.IsDefined && !minus.IsEmpty)
            {
                foreach (char c in minus.Get())
                {
                    sb.Append(c);
                }
            }

            sb.Append(number1).Append('.').Append(number2);

            double f;
            if (!Double.TryParse(sb.ToString(), out f))
            {
                throw new ArgumentException(string.Format("Bad float format: {0}", sb));
            }
            Value = f;
        }
Ejemplo n.º 30
0
        internal TokenInteger(IOption<IEnumerable<char>> minus, string number)
        {
            StringBuilder sb = new StringBuilder();
            if (minus.IsDefined && !minus.IsEmpty)
            {
                foreach (char c in minus.Get())
                {
                    sb.Append(c);
                }
            }

            sb.Append(number);

            Int64 v;
            if (!Int64.TryParse(sb.ToString(), out v))
            {
                throw new ArgumentException(string.Format("Bad Int64 format: {0}", sb));
            }
            Value = v;
        }
Ejemplo n.º 31
0
 public PingController(IExecutionContext executionContext, ITelemetryMemory telemetryMemory, IOption option)
 {
     _executionContext = executionContext;
     _telemetryMemory  = telemetryMemory;
     _option           = option;
 }
 /// <summary>
 /// Tests if a file or directory exists.
 /// </summary>
 /// <param name="filesystem"></param>
 /// <param name="path">path to a directory or to a single file, "" is root, separator is "/"</param>
 /// <param name="option">(optional) operation specific option; capability constraint, a session, security token or credential. Used for authenticating, authorizing or restricting the operation.</param>
 /// <returns>true if exists</returns>
 /// <exception cref="IOException">On unexpected IO error</exception>
 /// <exception cref="SecurityException">If caller did not have permission</exception>
 /// <exception cref="ArgumentNullException"><paramref name="path"/> is null</exception>
 /// <exception cref="ArgumentException"><paramref name="path"/> contains only white space, or contains one or more invalid characters</exception>
 /// <exception cref="NotSupportedException">The <see cref="IFileSystem"/> doesn't support exists</exception>
 /// <exception cref="UnauthorizedAccessException">The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.</exception>
 /// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters.</exception>
 /// <exception cref="InvalidOperationException">If <paramref name="path"/> refers to a non-file device, such as "con:", "com1:", "lpt1:", etc.</exception>
 /// <exception cref="ObjectDisposedException"/>
 public static Task <bool> ExistsAsync(this IFileSystem filesystem, string path, IOption option = null)
 {
     if (filesystem is IFileSystemBrowseAsync browserAsync)
     {
         return(browserAsync.GetEntryAsync(path, option).ContinueWith(t => t.Result != null));
     }
     if (filesystem is IFileSystemBrowse browser)
     {
         return(Task.Run(() => browser.GetEntry(path, option)).ContinueWith(t => t.Result != null));
     }
     else
     {
         throw new NotSupportedException(nameof(GetEntry));
     }
 }
Ejemplo n.º 33
0
 //add options from sub classes to the main library. used to generate the final list of
 //tsvariables
 public void AddOptionToLibary(IOption Option)
 {
     this._optionlibrary.Add(Option);
 }
Ejemplo n.º 34
0
 public PingController(IOption option)
 {
     _option = option;
 }
Ejemplo n.º 35
0
 public IGenerator SetSourceGenerator(string connectionString, IOption options)
 {
     SourceGenerator = new SQLServerGenerator(connectionString, options);
     return(SourceGenerator);
 }
Ejemplo n.º 36
0
 public FinancialComputation(IOption opt)
 {
     Option          = opt;
     Spots           = new List <double[]>();
     MarketDataDates = new List <DateTime>();
 }
 /// <summary>
 /// Test if <paramref name="filesystemOption"/> has Exists capability.
 /// </summary>
 /// <param name="filesystemOption"></param>
 /// <param name="defaultValue">Returned value if option is unspecified</param>
 /// <returns>true if has Exists capability</returns>
 public static bool CanGetEntry(this IOption filesystemOption, bool defaultValue = false)
 => filesystemOption.AsOption <IBrowseOption>() is IBrowseOption browser ? browser.CanGetEntry : defaultValue;
 public Stream Open(string path, FileMode fileMode, FileAccess fileAccess, FileShare fileShare, IOption option = null)
 {
     if (path != fileEntry.Path)
     {
         throw new FileNotFoundException(path);
     }
     if (fileMode != FileMode.Open)
     {
         throw new NotSupportedException();
     }
     if (fileAccess != FileAccess.Read)
     {
         throw new NotSupportedException();
     }
     byte[] data = UTF8Encoding.UTF8.GetBytes("Hello World");
     return(new MemoryStream(data));
 }
Ejemplo n.º 39
0
 public IOption <T> Alt(IOption <T> other)
 {
     return(other);
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Adapt <paramref name="fileProvider"/> to <see cref="IFileSystem"/>.
 ///
 /// WARNING: The Observe implementation browses the subtree of the watched directory path in order to create delta of changes.
 /// </summary>
 /// <param name="fileProvider"></param>
 /// <param name="option"></param>
 /// <returns><see cref="IFileSystem"/></returns>
 public static FileProviderSystem ToFileSystem(this IFileProvider fileProvider, IOption option)
 => new FileProviderSystem(fileProvider, option);
Ejemplo n.º 41
0
 public IList <int> Execute(IOption source)
 {
     MakeList(source.UnderlyingAsset.Bars.Count, source.GetStrikes().Count());
     return(this);
 }
Ejemplo n.º 42
0
 public ISecurity Execute(IOption opt)
 {
     return(opt.UnderlyingAsset);
 }
 /// <summary>
 /// Get entry of a single file or directory.
 /// </summary>
 /// <param name="filesystem"></param>
 /// <param name="path">path to a directory or to a single file, "" is root, separator is "/"</param>
 /// <param name="option">(optional) operation specific option; capability constraint, a session, security token or credential. Used for authenticating, authorizing or restricting the operation.</param>
 /// <returns>entry, or null if entry is not found</returns>
 /// <exception cref="IOException">On unexpected IO error</exception>
 /// <exception cref="SecurityException">If caller did not have permission</exception>
 /// <exception cref="ArgumentNullException"><paramref name="path"/> is null</exception>
 /// <exception cref="ArgumentException"><paramref name="path"/> contains only white space, or contains one or more invalid characters</exception>
 /// <exception cref="NotSupportedException">The <see cref="IFileSystem"/> doesn't support exists</exception>
 /// <exception cref="UnauthorizedAccessException">The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.</exception>
 /// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters.</exception>
 /// <exception cref="InvalidOperationException">If <paramref name="path"/> refers to a non-file device, such as "con:", "com1:", "lpt1:", etc.</exception>
 /// <exception cref="ObjectDisposedException"/>
 public static Task <IEntry> GetEntryAsync(this IFileSystem filesystem, string path, IOption option = null)
 {
     if (filesystem is IFileSystemBrowseAsync browserAsync)
     {
         return(browserAsync.GetEntryAsync(path, option));
     }
     if (filesystem is IFileSystemBrowse browser)
     {
         return(Task.Run(() => browser.GetEntry(path, option)));
     }
     throw new NotSupportedException(nameof(GetEntry));
 }
Ejemplo n.º 44
0
 public RangeExpressionSyntax(IOption <ExpressionSyntax> e1, IOption <ExpressionSyntax> e2)
 {
     this.S1 = e1.GetOrDefault();
     this.S2 = e2.GetOrDefault();
 }
 /// <summary>Flatten to simpler instance.</summary>
 public IOption Flatten(IOption o) => o is IBrowseOption b ? o is BrowseOption ? /*already flattened*/ o : /*new instance*/ new BrowseOption(b.CanBrowse, b.CanGetEntry) : throw new InvalidCastException($"{typeof(IBrowseOption)} expected.");
Ejemplo n.º 46
0
 /// <summary>
 /// Flatten <paramref name="option"/> as <paramref name="optionType"/>.
 /// </summary>
 /// <param name="option"></param>
 /// <param name="optionType">option interface type, a subtype of <see cref="IOption"/></param>
 /// <returns>Either <paramref name="option"/> or flattened version as <paramref name="optionType"/></returns>
 public static IOption OptionFlattenAs(this IOption option, Type optionType)
 => option.Operation <IOptionFlattenOperation>(optionType).Flatten(option);
Ejemplo n.º 47
0
 public DeployPackage(IOption option, IExecutionContext executionContext, ILogger <DeployPackage> logger)
 {
     _option           = option;
     _executionContext = executionContext;
     _logger           = logger;
 }
Ejemplo n.º 48
0
 /// <summary>
 ///     Determines if the given Option contains a value or not.
 /// </summary>
 /// <typeparam name="T">Type of the value potentially contained.</typeparam>
 /// <param name="option">Option instance to check for a value.</param>
 public static bool HasValue <T>(this IOption <T> option)
 {
     return(option is _Some <T>);
 }
Ejemplo n.º 49
0
 public OptionChangedEventSource(ITextBuffer subjectBuffer, IOption option, TaggerDelay delay) : base(subjectBuffer, delay)
 {
     _option = option;
 }
Ejemplo n.º 50
0
 public Synonym(IOption <T> main, string name)
 {
     _mainOption = main;
     _name       = name;
 }
Ejemplo n.º 51
0
 public void Init()
 {
     _pb            = new HoleFillingFilter();
     holeFillOption = _pb.Options[Option.HolesFill];
 }
Ejemplo n.º 52
0
 public void Add(IOption item)
 {
     base.Add(item as StringOption);
 }
Ejemplo n.º 53
0
        public override int Run(ExportConfigurationOptions exportOptions)
        {
            int result = FAILURE;

            try
            {
                PropertiesDictionary allOptions = new PropertiesDictionary();

                // The export command could be updated in the future to accept an arbitrary set
                // of analyzers for which to build an options XML file suitable for configuring them.
                ImmutableArray <IOptionsProvider> providers = DriverUtilities.GetExports <IOptionsProvider>(DefaultPlugInAssemblies);
                foreach (IOptionsProvider provider in providers)
                {
                    IOption sampleOption = null;

                    // Every analysis options provider has access to the following default configuration knobs
                    foreach (IOption option in provider.GetOptions())
                    {
                        sampleOption = sampleOption ?? option;
                        allOptions.SetProperty(option, option.DefaultValue, cacheDescription: true);
                    }
                }

                IEnumerable <IRule> rules;
                rules = DriverUtilities.GetExports <IRule>(DefaultPlugInAssemblies);

                // This code injects properties that are provided for every rule instance.
                foreach (IRule rule in rules)
                {
                    object objectResult;
                    PropertiesDictionary properties;

                    string ruleOptionsKey = rule.Id + "." + rule.Name.Text + ".Options";

                    if (!allOptions.TryGetValue(ruleOptionsKey, out objectResult))
                    {
                        objectResult = allOptions[ruleOptionsKey] = new PropertiesDictionary();
                    }
                    properties = (PropertiesDictionary)objectResult;

                    foreach (IOption option in DefaultDriverOptions.Instance.GetOptions())
                    {
                        properties.SetProperty(option, option.DefaultValue, cacheDescription: true, persistToSettingsContainer: false);
                    }
                }

                string extension = Path.GetExtension(exportOptions.OutputFilePath);

                if (extension.Equals(".xml", StringComparison.OrdinalIgnoreCase))
                {
                    allOptions.SaveToXml(exportOptions.OutputFilePath);
                }
                else if (extension.Equals(".json", StringComparison.OrdinalIgnoreCase))
                {
                    allOptions.SaveToJson(exportOptions.OutputFilePath);
                }
                else if (exportOptions.FileFormat == FileFormat.Xml)
                {
                    allOptions.SaveToXml(exportOptions.OutputFilePath);
                }
                else
                {
                    allOptions.SaveToJson(exportOptions.OutputFilePath);
                }

                Console.WriteLine("Configuration file saved to: " + Path.GetFullPath(exportOptions.OutputFilePath));

                result = SUCCESS;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
            }

            return(result);
        }
Ejemplo n.º 54
0
 public bool Contains(IOption item)
 {
     return(base.Contains(item as StringOption));
 }
Ejemplo n.º 55
0
 public static IEnumerable <T> ToEnumerable <T>(IOption <T> value)
 {
     return(value.ToList());
 }
 /// <summary>
 /// Browse a directory for child entries.
 ///
 /// <paramref name="path"/> should end with directory separator character '/', for example "mydir/".
 /// </summary>
 /// <param name="filesystem"></param>
 /// <param name="path">path to a directory, "" is root, separator is "/"</param>
 /// <param name="option">(optional) operation specific option; capability constraint, a session, security token or credential. Used for authenticating, authorizing or restricting the operation.</param>
 /// <returns>
 ///     Returns a snapshot of file and directory entries.
 ///     Note, that the returned array be internally cached by the implementation, and therefore the caller must not modify the array.
 /// </returns>
 /// <exception cref="IOException">On unexpected IO error</exception>
 /// <exception cref="SecurityException">If caller did not have permission</exception>
 /// <exception cref="ArgumentNullException"><paramref name="path"/> is null</exception>
 /// <exception cref="ArgumentException"><paramref name="path"/> contains only white space, or contains one or more invalid characters</exception>
 /// <exception cref="NotSupportedException">The <see cref="IFileSystem"/> doesn't support browse</exception>
 /// <exception cref="UnauthorizedAccessException">The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.</exception>
 /// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters.</exception>
 /// <exception cref="InvalidOperationException">If <paramref name="path"/> refers to a non-file device, such as "con:", "com1:", "lpt1:", etc.</exception>
 /// <exception cref="ObjectDisposedException"/>
 public static Task <IDirectoryContent> BrowseAsync(this IFileSystem filesystem, string path, IOption option = null)
 {
     if (filesystem is IFileSystemBrowseAsync browserAsync)
     {
         return(browserAsync.BrowseAsync(path, option));
     }
     if (filesystem is IFileSystemBrowse browser)
     {
         return(Task.Run(() => browser.Browse(path, option)));
     }
     throw new NotSupportedException(nameof(Browse));
 }
Ejemplo n.º 57
0
 public static bool IsCheckbox(this IOption opt)
 {
     return(opt.Max == 1.0f &&
            opt.Min == 0.0f &&
            opt.Step == 1.0f);
 }
Ejemplo n.º 58
0
    void DrawOption(Sensor sensor, IOption opt)
    {
        if (!cachedValue.ContainsKey(opt))
        {
            cachedValue[opt] = opt.Value;
        }

        string k = opt.Key.ToString();
        float  v = cachedValue[opt];

        if (opt.ReadOnly)
        {
            EditorGUILayout.BeginHorizontal();
            GUI.enabled = false;
            EditorGUILayout.LabelField(k, GUILayout.Width(EditorGUIUtility.labelWidth - 4));
            GUI.enabled = true;
            EditorGUILayout.SelectableLabel(v.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
            EditorGUILayout.EndHorizontal();
        }
        else if (opt.IsCheckbox())
        {
            bool isChecked = Convert.ToBoolean(v);
            if (isChecked != EditorGUILayout.Toggle(k, isChecked))
            {
                cachedValue[opt] = opt.Value = Convert.ToSingle(!isChecked);
            }
        }
        else if (opt.IsEnum(sensor.Options))
        {
            var valuesStrings = new List <string>();
            int selected      = 0;
            int counter       = 0;
            for (float i = opt.Min; i <= opt.Max; i += opt.Step, counter++)
            {
                if (Math.Abs(i - v) < 0.001)
                {
                    selected = counter;
                }
                valuesStrings.Add(sensor.Options.OptionValueDescription(opt.Key, i));
            }
            var newSelection = EditorGUILayout.Popup(k, selected, valuesStrings.ToArray());
            if (newSelection != selected)
            {
                cachedValue[opt] = opt.Value = Convert.ToSingle(newSelection);
            }
        }
        else if (opt.IsIntegersOnly())
        {
            var newVal = EditorGUILayout.IntSlider(k, (int)v, (int)opt.Min, (int)opt.Max);
            if (newVal != Convert.ToInt32(v))
            {
                cachedValue[opt] = opt.Value = Convert.ToSingle(newVal);
            }
        }
        else
        {
            float s = EditorGUILayout.Slider(k, v, opt.Min, opt.Max);
            if (!Mathf.Approximately(s, v))
            {
                cachedValue[opt] = opt.Value = s;
            }
        }
    }
Ejemplo n.º 59
0
 /// <summary>
 /// Take intersection of <paramref name="option"/> and <paramref name="anotherOption"/> as <paramref name="optionType"/>.
 /// </summary>
 /// <param name="option"></param>
 /// <param name="anotherOption"></param>
 /// <param name="optionType">option interface type, a subtype of <see cref="IOption"/></param>
 /// <returns>flattened instance of <paramref name="optionType"/></returns>
 public static IOption OptionIntersectionAs(this IOption option, IOption anotherOption, Type optionType)
 => option.Operation <IOptionIntersectionOperation>(optionType).Intersection(option, anotherOption);
Ejemplo n.º 60
0
 /// <summary>
 ///     Creates a new IOption(U) from an IOption(T) by converting the potentially contained
 ///     value, using a given conversion function.
 /// </summary>
 /// <typeparam name="T">Type of the value originally contained.</typeparam>
 /// <typeparam name="U">Type of the new value potentially contained.</typeparam>
 /// <param name="option">An option to Select over.</param>
 /// <param name="selector">A function used to convert the potential value.</param>
 public static IOption <U> Select <T, U>(this IOption <T> option, Func <T, U> selector)
 {
     return(option.Bind(x => Some(selector(x))));
 }