当前位置: 首页>>代码示例>>C#>>正文


C# IDictionary.GetOrDefault方法代码示例

本文整理汇总了C#中IDictionary.GetOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# IDictionary.GetOrDefault方法的具体用法?C# IDictionary.GetOrDefault怎么用?C# IDictionary.GetOrDefault使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IDictionary的用法示例。


在下文中一共展示了IDictionary.GetOrDefault方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Init

        protected override void Init(IDictionary<string, string> arguments, CancellationToken cancellationToken)
        {
            _directory = CommandHelpers.GetLuceneDirectory(arguments);
            _source = arguments.GetOrThrow<string>(Arguments.Source);
            _verbose = arguments.GetOrDefault(Arguments.Verbose, false);

            _registration = arguments.GetOrDefault<string>(Arguments.Registration);
            if (_registration == null)
            {
                Logger.LogInformation("Lucene index will be created up to the end of the catalog (alternatively if you provide a registration it will not pass that)");
            }

            _catalogBaseAddress = arguments.GetOrDefault<string>(Arguments.CatalogBaseAddress);
            if (_catalogBaseAddress == null)
            {
                Logger.LogInformation("No catalogBaseAddress was specified so the Lucene index will NOT contain the storage paths");
            }

            _storageBaseAddress = arguments.GetOrDefault<string>(Arguments.StorageBaseAddress);

            Logger.LogInformation("CONFIG source: \"{ConfigSource}\" registration: \"{Registration}\"" +
                                   " catalogBaseAddress: \"{CatalogBaseAddress}\" storageBaseAddress: \"{StorageBaseAddress}\"",
                                   _source,
                                   _registration ?? "(null)",
                                   _catalogBaseAddress ?? "(null)",
                                   _storageBaseAddress ?? "(null)");

            _handlerFunc = CommandHelpers.GetHttpMessageHandlerFactory(_verbose, _catalogBaseAddress, _storageBaseAddress);
        }
开发者ID:NuGet,项目名称:NuGet.Services.Metadata,代码行数:29,代码来源:Catalog2LuceneJob.cs

示例2: Run

        public override async Task Run(IDictionary<string, string> arguments, CancellationToken cancellationToken)
        {
            var intervalSec = arguments.GetOrDefault(Arguments.Interval, Arguments.DefaultInterval);
            Logger.LogInformation("Looping job at interval {Interval} seconds.", intervalSec);

            // It can be expensive to initialize, so don't initialize on every run.
            // Remember the last time we initialized, and only reinitialize if a specified interval has passed since then.
            DateTime? timeLastInitialized = null;
            do
            {
                var timeMustReinitialize = DateTime.UtcNow.Subtract(new TimeSpan(0, 0, 0,
                    arguments.GetOrDefault(Arguments.ReinitializeIntervalSec, Arguments.DefaultReinitializeIntervalSec)));

                if (!timeLastInitialized.HasValue || timeLastInitialized.Value <= timeMustReinitialize)
                {
                    Logger.LogInformation("Initializing job.");
                    Init(arguments, cancellationToken);
                    timeLastInitialized = timeMustReinitialize;
                }

                Logger.LogInformation("Running job.");
                await RunInternal(cancellationToken);
                Logger.LogInformation("Job finished!");
                Logger.LogInformation("Waiting {Interval} seconds before starting job again.", intervalSec);
                await Task.Delay(intervalSec * 1000, cancellationToken);
            } while (true);
        }
开发者ID:NuGet,项目名称:NuGet.Services.Metadata,代码行数:27,代码来源:LoopingNgJob.cs

示例3: GetSecretInjector

        private static ISecretInjector GetSecretInjector(IDictionary<string, string> arguments)
        {
            ISecretReader secretReader;

            var vaultName = arguments.GetOrDefault<string>(Arguments.VaultName);
            if (string.IsNullOrEmpty(vaultName))
            {
                secretReader = new EmptySecretReader();
            }
            else
            {
                var clientId = arguments.GetOrThrow<string>(Arguments.ClientId);
                var certificateThumbprint = arguments.GetOrThrow<string>(Arguments.CertificateThumbprint);
                var storeName = arguments.GetOrDefault(Arguments.StoreName, StoreName.My);
                var storeLocation = arguments.GetOrDefault(Arguments.StoreLocation, StoreLocation.LocalMachine);
                var shouldValidateCert = arguments.GetOrDefault(Arguments.ValidateCertificate, false);

                var keyVaultConfig = new KeyVaultConfiguration(vaultName, clientId, certificateThumbprint, storeName, storeLocation, shouldValidateCert);

                secretReader = new CachingSecretReader(new KeyVaultReader(keyVaultConfig),
                    arguments.GetOrDefault(Arguments.RefreshIntervalSec, CachingSecretReader.DefaultRefreshIntervalSec));
            }

            return new SecretInjector(secretReader);
        }
开发者ID:NuGet,项目名称:NuGet.Services.Metadata,代码行数:25,代码来源:CommandHelpers.cs

示例4: Init

 protected override void Init(IDictionary<string, string> arguments, CancellationToken cancellationToken)
 {
     _gallery = arguments.GetOrThrow<string>(Arguments.Gallery);
     _verbose = arguments.GetOrDefault(Arguments.Verbose, false);
     _id = arguments.GetOrThrow<string>(Arguments.Id);
     _version = arguments.GetOrDefault<string>(Arguments.Version);
     _storageFactory = CommandHelpers.CreateStorageFactory(arguments, _verbose);
 }
开发者ID:NuGet,项目名称:NuGet.Services.Metadata,代码行数:8,代码来源:Package2CatalogJob.cs

示例5: ExtractUrl

 private static Uri ExtractUrl(IDictionary<string, string> args)
 {
     Uri url = new UriBuilder()
     {
         Scheme = args.GetOrDefault("protocol", "https"),
         Host = args.GetOrDefault("host", "no-host.git"),
         Path = args.GetOrDefault("path", "/")
     }.Uri;
     return url;
 }
开发者ID:plurby,项目名称:git-credential-winstore,代码行数:10,代码来源:Program.cs

示例6: CreateFromDictionary

        public static Binding CreateFromDictionary(IDictionary<string, string> dict)
        {
            var binding = new Binding();

            // Parse the enums first
            BindingMode mode;
            if (Enum.TryParse(dict.GetOrDefault("Mode"), out mode)) binding.Mode = mode;

            RelativeSourceMode sourceMode;
            if (Enum.TryParse(dict.GetOrDefault("RelativeSource"), out sourceMode))
            {
                binding.RelativeSource = new RelativeSource
                {
                    Mode = sourceMode
                };
            }

            UpdateSourceTrigger trigger;
            if (Enum.TryParse(dict.GetOrDefault("UpdateSourceTrigger"), out trigger))
            {
                binding.UpdateSourceTrigger = trigger;
            }

            // Then the other stuff
            // var converter = SOMETHING;
            var converterLanguage = dict.GetOrDefault("ConverterLanguage");
            var converterParameter = dict.GetOrDefault("ConverterParameter");
            var elementName = dict.GetOrDefault("ElementName");
            var fallbackValue = dict.GetOrDefault("FallbackValue");
            var path = dict.GetOrDefault("Path");
            var source = dict.GetOrDefault("Source");
            var targetNullValue = dict.GetOrDefault("TargetNullValue");

            // And now for the null checks...
            if (converterLanguage != null)
                binding.ConverterLanguage = converterLanguage;
            if (converterParameter != null)
                binding.ConverterParameter = converterParameter;
            if (elementName != null)
                binding.ElementName = elementName;
            if (fallbackValue != null)
                binding.FallbackValue = fallbackValue;
            if (path != null)
                binding.Path = new PropertyPath(path);
            if (source != null)
                binding.Source = source;
            if (targetNullValue != null)
                binding.TargetNullValue = targetNullValue;

            // Done!
            return binding;
        }
开发者ID:jamesqo,项目名称:Sirloin,代码行数:52,代码来源:BindingHelpers.cs

示例7: Init

        protected override void Init(IDictionary<string, string> arguments, CancellationToken cancellationToken)
        {
            var source = arguments.GetOrThrow<string>(Arguments.Source);
            var unlistShouldDelete = arguments.GetOrDefault(Arguments.UnlistShouldDelete, false);
            var verbose = arguments.GetOrDefault(Arguments.Verbose, false);

            var contentBaseAddress = arguments.GetOrDefault<string>(Arguments.ContentBaseAddress);

            StorageFactory storageFactoryToUse;

            var storageFactory = CommandHelpers.CreateStorageFactory(arguments, verbose);
            var compressedStorageFactory = CommandHelpers.CreateCompressedStorageFactory(arguments, verbose);

            Logger.LogInformation("CONFIG source: \"{ConfigSource}\" storage: \"{Storage}\"", source, storageFactory);

            RegistrationMakerCatalogItem.PackagePathProvider = new PackagesFolderPackagePathProvider();

            if (compressedStorageFactory != null)
            {
                var secondaryStorageBaseUrlRewriter = new SecondaryStorageBaseUrlRewriter(new List<KeyValuePair<string, string>>
                {
                    // always rewrite storage root url in seconary
                    new KeyValuePair<string, string>(storageFactory.BaseAddress.ToString(), compressedStorageFactory.BaseAddress.ToString())
                });

                var aggregateStorageFactory = new AggregateStorageFactory(
                    storageFactory,
                    new[] { compressedStorageFactory },
                    secondaryStorageBaseUrlRewriter.Rewrite);

                storageFactoryToUse = aggregateStorageFactory;
            }
            else
            {
                storageFactoryToUse = storageFactory;
            }

            _collector = new RegistrationCollector(new Uri(source), storageFactoryToUse, CommandHelpers.GetHttpMessageHandlerFactory(verbose))
            {
                ContentBaseAddress = contentBaseAddress == null
                    ? null
                    : new Uri(contentBaseAddress)
            };

            var storage = storageFactoryToUse.Create();
            _front = new DurableCursor(storage.ResolveUri("cursor.json"), storage, MemoryCursor.MinValue);
            _back = MemoryCursor.CreateMax();
        }
开发者ID:NuGet,项目名称:NuGet.Services.Metadata,代码行数:48,代码来源:Catalog2RegistrationJob.cs

示例8: ExtractUrl

        private static Uri ExtractUrl(IDictionary<string, string> args)
        {
            // Manually build a string (tried a UriBuilder, but Git gives us credentials and port numbers so it's difficult)
            string scheme = args.GetOrDefault("protocol", "https");
            string host = args.GetOrDefault("host", "no-host.git");
            string path = args.GetOrDefault("path", "/");

            string candidateUrl = String.Format("{0}://{1}{2}", scheme, host, path);
            Uri url;
            if (!Uri.TryCreate(candidateUrl, UriKind.Absolute, out url))
            {
                Console.Error.WriteLine("Failed to parse url: {0}", candidateUrl);
                return null;
            }
            return url;
        }
开发者ID:erezak,项目名称:git-credential-winstore,代码行数:16,代码来源:Program.cs

示例9: Init

        protected override void Init(IDictionary<string, string> arguments, CancellationToken cancellationToken)
        {
            Gallery = arguments.GetOrThrow<string>(Arguments.Gallery);
            Verbose = arguments.GetOrDefault(Arguments.Verbose, false);
            StartDate = arguments.GetOrDefault(Arguments.StartDate, DateTimeMinValueUtc);

            var catalogStorageFactory = CommandHelpers.CreateStorageFactory(arguments, Verbose);
            var auditingStorageFactory = CommandHelpers.CreateSuffixedStorageFactory("Auditing", arguments, Verbose);

            Logger.LogInformation("CONFIG source: \"{ConfigSource}\" storage: \"{Storage}\"", Gallery, catalogStorageFactory);

            CatalogStorage = catalogStorageFactory.Create();
            AuditingStorage = auditingStorageFactory.Create();

            Top = 20;
            Timeout = TimeSpan.FromSeconds(300);
        }
开发者ID:NuGet,项目名称:NuGet.Services.Metadata,代码行数:17,代码来源:Feed2CatalogJob.cs

示例10: Extract

        /// <summary>
        /// Creates a <see cref="ExtensionMetadata"/> instance from the given metadata dictionary.
        /// </summary>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public static IEnumerable<IExtensionMetadata> Extract(IDictionary<string, object> metadata)
        {
            var objectTypes = (ExtensionObjectType[])metadata.GetOrDefault("ObjectType");
            var localNames = (string[])metadata.GetOrDefault("LocalName");
            var namespaceNames = (string[])metadata.GetOrDefault("NamespaceName");
            var predicateTypes = (Type[])metadata.GetOrDefault("PredicateType");

            // find shortest array
            int length = objectTypes.Length;
            length = Math.Min(length, localNames.Length);
            length = Math.Min(length, namespaceNames.Length);
            length = Math.Min(length, predicateTypes.Length);

            // extract metadata
            for (int i = 0; i < length; i++)
                yield return new ExtensionMetadata(objectTypes[i], localNames[i], namespaceNames[i], predicateTypes[i]);
        }
开发者ID:nxkit,项目名称:nxkit,代码行数:22,代码来源:ExtensionMetadata.cs

示例11: Init

        protected override void Init(IDictionary<string, string> arguments, CancellationToken cancellationToken)
        {
            var source = arguments.GetOrThrow<string>(Arguments.Source);
            var verbose = arguments.GetOrDefault(Arguments.Verbose, false);
            var contentBaseAddress = arguments.GetOrDefault<string>(Arguments.ContentBaseAddress);
            var storageFactory = CommandHelpers.CreateStorageFactory(arguments, verbose);

            Logger.LogInformation("CONFIG source: \"{ConfigSource}\" storage: \"{Storage}\"", source, storageFactory);

            _collector = new DnxCatalogCollector(new Uri(source), storageFactory, CommandHelpers.GetHttpMessageHandlerFactory(verbose))
            {
                ContentBaseAddress = contentBaseAddress == null ? null : new Uri(contentBaseAddress)
            };

            var storage = storageFactory.Create();
            _front = new DurableCursor(storage.ResolveUri("cursor.json"), storage, MemoryCursor.MinValue);
            _back = MemoryCursor.CreateMax();
        }
开发者ID:NuGet,项目名称:NuGet.Services.Metadata,代码行数:18,代码来源:Catalog2DnxJob.cs

示例12: StoreCommand

        static IEnumerable<Tuple<string, string>> StoreCommand(IDictionary<string, string> args)
        {
            // Build the URL
            Uri url = ExtractUrl(args);
            string userName = args.GetOrDefault("username", String.Empty);
            string password = args.GetOrDefault("password", String.Empty);

            bool abort = false;
            if(abort |= String.IsNullOrEmpty(userName)) {
                Console.Error.WriteLine("username parameter must be provided");
            }
            if(abort |= String.IsNullOrEmpty(password)) {
                Console.Error.WriteLine("password parameter must be provided");
            }
            if (!abort)
            {
                string target = GetTargetName(url);
                IntPtr passwordPtr = Marshal.StringToBSTR(password);
                NativeMethods.CREDENTIAL cred = new NativeMethods.CREDENTIAL()
                {
                    type = 0x01, // Generic
                    targetName = target,
                    credentialBlob = Marshal.StringToCoTaskMemUni(password),
                    persist = 0x03, // Enterprise (roaming)
                    attributeCount = 0,
                    userName = userName
                };
                cred.credentialBlobSize = Encoding.Unicode.GetByteCount(password);
                if (!NativeMethods.CredWrite(ref cred, 0))
                {
                    Console.Error.WriteLine(
                        "Failed to write credential: " +
                        GetLastErrorMessage());
                }
            }
            return Enumerable.Empty<Tuple<string, string>>();
        }
开发者ID:erezak,项目名称:git-credential-winstore,代码行数:37,代码来源:Program.cs

示例13: ProcessBatch

		private int ProcessBatch(AbstractViewGenerator viewGenerator, List<object> currentDocumentResults, string currentKey, HashSet<ReduceKeyAndBucket> changes,
			IStorageActionsAccessor actions,
			IDictionary<string, int> statsPerKey)
		{
			if (currentKey == null || currentDocumentResults.Count == 0)
				return 0;
			var old = CurrentIndexingScope.Current;
			try
			{
				CurrentIndexingScope.Current = null;

				if (logIndexing.IsDebugEnabled)
				{
					var sb = new StringBuilder()
						.AppendFormat("Index {0} for document {1} resulted in:", PublicName, currentKey)
						.AppendLine();
					foreach (var currentDocumentResult in currentDocumentResults)
					{
						sb.AppendLine(JsonConvert.SerializeObject(currentDocumentResult));
					}
					logIndexing.Debug(sb.ToString());
				}

				int count = 0;
				var results = RobustEnumerationReduceDuringMapPhase(currentDocumentResults.GetEnumerator(), viewGenerator.ReduceDefinition);
				foreach (var doc in results)
				{
					count++;

					var reduceValue = viewGenerator.GroupByExtraction(doc);
					if (reduceValue == null)
					{
						logIndexing.Debug("Field {0} is used as the reduce key and cannot be null, skipping document {1}",
										  viewGenerator.GroupByExtraction, currentKey);
						continue;
					}
					string reduceKey = ReduceKeyToString(reduceValue);

					var data = GetMappedData(doc);

					logIndexing.Debug("Index {0} for document {1} resulted in ({2}): {3}", PublicName, currentKey, reduceKey, data);
					actions.MapReduce.PutMappedResult(indexId, currentKey, reduceKey, data);
					statsPerKey[reduceKey] = statsPerKey.GetOrDefault(reduceKey) + 1;
					actions.General.MaybePulseTransaction();
					changes.Add(new ReduceKeyAndBucket(IndexingUtil.MapBucket(currentKey), reduceKey));
				}
				return count;
			}
			finally
			{
				CurrentIndexingScope.Current = old;
			}
		}
开发者ID:bbqchickenrobot,项目名称:ravendb,代码行数:53,代码来源:MapReduceIndex.cs

示例14: ProcessBatch

		private int ProcessBatch(AbstractViewGenerator viewGenerator, List<object> currentDocumentResults, string currentKey, HashSet<ReduceKeyAndBucket> changes,
			IStorageActionsAccessor actions,
			IDictionary<string, int> statsPerKey)
		{
			if (currentKey == null || currentDocumentResults.Count == 0)
				return 0;

			int count = 0;
			var results = RobustEnumerationReduceDuringMapPhase(currentDocumentResults.GetEnumerator(), viewGenerator.ReduceDefinition);
			foreach (var doc in results)
			{
				count++;

				var reduceValue = viewGenerator.GroupByExtraction(doc);
				if (reduceValue == null)
				{
					logIndexing.Debug("Field {0} is used as the reduce key and cannot be null, skipping document {1}",
									  viewGenerator.GroupByExtraction, currentKey);
					continue;
				}
				string reduceKey = ReduceKeyToString(reduceValue);

				var data = GetMappedData(doc);

				actions.MapReduce.PutMappedResult(name, currentKey, reduceKey, data);
				statsPerKey[reduceKey] = statsPerKey.GetOrDefault(reduceKey) + 1;
				actions.General.MaybePulseTransaction();
				changes.Add(new ReduceKeyAndBucket(IndexingUtil.MapBucket(currentKey), reduceKey));
			}
			return count;
		}
开发者ID:nzaugg,项目名称:ravendb,代码行数:31,代码来源:MapReduceIndex.cs

示例15: Init

        protected override void Init(IDictionary<string, string> arguments, CancellationToken cancellationToken)
        {
            PrintLightning();

            _command = arguments.GetOrThrow<string>(Arguments.Command);
            _verbose = arguments.GetOrDefault(Arguments.Verbose, false);

            _log = _verbose ? Console.Out : new StringWriter();

            switch (_command.ToLowerInvariant())
            {
                case "charge":
                case "prepare":
                    InitPrepare(arguments);
                    break;
                case "strike":
                    InitStrike(arguments);
                    break;
                default:
                    throw new ArgumentNullException();
            }

            _contentBaseAddress = arguments.GetOrThrow<string>(Arguments.ContentBaseAddress);
            _storageAccount = arguments.GetOrThrow<string>(Arguments.StorageAccount);
            _storageContainer = arguments.GetOrThrow<string>(Arguments.StorageContainer);
            _storageBaseAddress = arguments.GetOrThrow<string>(Arguments.StorageBaseAddress);
            _compress = arguments.GetOrDefault(Arguments.Compress, false);
        }
开发者ID:NuGet,项目名称:NuGet.Services.Metadata,代码行数:28,代码来源:LightningJob.cs


注:本文中的IDictionary.GetOrDefault方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。