System.Collections.Generic.IEnumerable.SingleOrDefault()

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.SingleOrDefault() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

599 Examples 7

19 Source : GenericInterface.cs
with MIT License
from Accelerider

public static IGenericInterface AsGenericInterface(this object @this, Type type)
        {
            var interfaceType = (
                    from @interface in @this.GetType().GetInterfaces()
                    where @interface.IsGenericType
                    let definition = @interface.GetGenericTypeDefinition()
                    where definition == type
                    select @interface
                )
                .SingleOrDefault();

            return interfaceType != null
                ? new GenericInterfaceImpl(@this, interfaceType)
                : null;
        }

19 Source : OutOfProcessSettingValueProvider.cs
with GNU General Public License v3.0
from Acumatica

internal static bool IsOutOfProcessEnabled(this AreplacedinatorVSPackage package, Workspace workspace)
		{
			package.ThrowOnNull(nameof(package));
			package.VSVersion.ThrowOnNull($"{nameof(AreplacedinatorVSPackage)}.{nameof(AreplacedinatorVSPackage.VSVersion)}");

			if (!package.VSVersion.IsVS2019)
				return false;

			// Faster version gets setting OOP64Bit from the VS session store. If it is true then the OOP is enabled
			bool? outOfProcessFromSettingsStore = GetOutOfProcessSettingFromSessionStore(package);

			if (outOfProcessFromSettingsStore == true)
				return true;

			// If OOP is false or its retrieval failed then we need to resort to the internal Roslyn helper RemoteHostOptions.IsUsingServiceHubOutOfProcess
			if (workspace?.Services != null)
			{
				Type remoteHostOptionsType = (from replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()
											  where replacedembly.GetName().Name == "Microsoft.Codereplacedysis.Remote.Workspaces"
											  from type in replacedembly.GetTypes()
											  where type.IsClreplaced && type.IsAbstract && type.IsSealed && !type.IsPublic && type.Name == "RemoteHostOptions"
											  select type)
											.SingleOrDefault();
				MethodInfo isUsingServiceHubOutOfProcess = remoteHostOptionsType?.GetMethod("IsUsingServiceHubOutOfProcess",
																							BindingFlags.Static | BindingFlags.Public);

				object isOutOfProcessFromRoslynInternalsObj = isUsingServiceHubOutOfProcess?.Invoke(null, new object[] { workspace.Services });

				if (isOutOfProcessFromRoslynInternalsObj is bool isOutOfProcessFromRoslynInternals)
					return isOutOfProcessFromRoslynInternals;
			}

			return false;
		}

19 Source : SetVersionInfoTask.cs
with MIT License
from adamecr

private static void SetProjectPropertyNode(XContainer projectNode, string nodeName, string nodeValue)
        {
            var propertyNode = projectNode
                .Elements("PropertyGroup")
                .SelectMany(it => it.Elements(nodeName))
                .SingleOrDefault();
            // If no  node exists, create it.
            if (propertyNode == null)
            {
                var propertyGroupNode = GetOrCreateElement(projectNode, "PropertyGroup");
                propertyNode = GetOrCreateElement(propertyGroupNode, nodeName);
            }
            propertyNode.SetValue(nodeValue);
        }

19 Source : OrganizationServiceExtensions.cs
with MIT License
from Adoxio

public static Enreplacedy GetContactById(this IOrganizationService service, Guid contactid)
        {
            var fetchxml =
                $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' nolock='true'>
                      <enreplacedy name='contact'>
                        <all-attributes />
                        <filter type='and'>
                            <condition attribute='contactid' operator='eq' value='{contactid}' />
                        </filter>
                      </enreplacedy>
                    </fetch>";

            var contactResponse = service.RetrieveMultiple(new FetchExpression(fetchxml));

            return contactResponse.Enreplacedies.SingleOrDefault();
        }

19 Source : WebsiteManager.cs
with MIT License
from Adoxio

protected virtual TWebsite GetWebsiteByBinding(PortalHostingEnvironment environment, IEnumerable<TWebsite> websites)
		{
			return GetWebsitesByBinding(environment, websites).SingleOrDefault();
		}

19 Source : OrganizationServiceExtensions.cs
with MIT License
from Adoxio

public static Enreplacedy GetContactByExternalIdenreplacedyUsername(this IOrganizationService service, string username)
        {
            var fetchxml =
                $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' nolock='true'>
                      <enreplacedy name='contact'>
                        <all-attributes />
                        <link-enreplacedy name='adx_externalidenreplacedy' from='adx_contactid' to='contactid' alias='ab'>
                          <filter type='and'>
                            <condition attribute='adx_username' operator='eq' value='{username}' />
                          </filter>
                        </link-enreplacedy>
                      </enreplacedy>
                    </fetch>";

            var contactResponse = service.RetrieveMultiple(new FetchExpression(fetchxml));

            return contactResponse.Enreplacedies.SingleOrDefault();
        }

19 Source : OrganizationServiceExtensions.cs
with MIT License
from Adoxio

public static Enreplacedy RetrieveRelatedEnreplacedy(
			this IOrganizationService service,
			EnreplacedyReference target,
			string relationshipSchemaName,
			IEnumerable<string> columns = null,
			ICollection<Filter> filters = null,
			RequestFlag flag = RequestFlag.None,
			[CallerMemberName] string memberName = "",
			[CallerFilePath] string sourceFilePath = "",
			[CallerLineNumber] int sourceLineNumber = 0)
		{
			var enreplacedies = GetRelatedEnreplacedies(service, target, relationshipSchemaName, EnreplacedyRole.Referencing, columns, filters, flag, memberName, sourceFilePath, sourceLineNumber);
			return enreplacedies.Enreplacedies.SingleOrDefault();
		}

19 Source : OrganizationServiceExtensions.cs
with MIT License
from Adoxio

public static Enreplacedy RetrieveRelatedEnreplacedy(
			this IOrganizationService service,
			EnreplacedyReference target,
			Relationship relationship,
			ICollection<FetchAttribute> attributes = null,
			ICollection<Filter> filters = null,
			RequestFlag flag = RequestFlag.None,
			[CallerMemberName] string memberName = "",
			[CallerFilePath] string sourceFilePath = "",
			[CallerLineNumber] int sourceLineNumber = 0)
		{
			var enreplacedies = GetRelatedEnreplacedies(service, target, relationship, attributes, filters, flag, memberName, sourceFilePath, sourceLineNumber);
			return enreplacedies.Enreplacedies.SingleOrDefault();
		}

19 Source : EnumUtils.cs
with MIT License
from akaskela

private static BidirectionalDictionary<string, string> InitializeEnumType(Type type)
        {
            BidirectionalDictionary<string, string> map = new BidirectionalDictionary<string, string>(
                StringComparer.OrdinalIgnoreCase,
                StringComparer.OrdinalIgnoreCase);

            foreach (FieldInfo f in type.GetFields())
            {
                string n1 = f.Name;
                string n2;

#if !NET20
                n2 = f.GetCustomAttributes(typeof(EnumMemberAttribute), true)
                    .Cast<EnumMemberAttribute>()
                    .Select(a => a.Value)
                    .SingleOrDefault() ?? f.Name;
#else
                n2 = f.Name;
#endif

                string s;
                if (map.TryGetBySecond(n2, out s))
                {
                    throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, n2, type.Name));
                }

                map.Set(n1, n2);
            }

            return map;
        }

19 Source : ReflectionUtils.cs
with MIT License
from akaskela

public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo)
        {
            const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

            switch (memberInfo.MemberType())
            {
                case MemberTypes.Property:
                    PropertyInfo propertyInfo = (PropertyInfo)memberInfo;

                    Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray();

                    return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null);
                default:
                    return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault();
            }
        }

19 Source : StringUtils.cs
with MIT License
from akaskela

public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (valueSelector == null)
            {
                throw new ArgumentNullException(nameof(valueSelector));
            }

            var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase));
            if (caseInsensitiveResults.Count() <= 1)
            {
                return caseInsensitiveResults.SingleOrDefault();
            }
            else
            {
                // multiple results returned. now filter using case sensitivity
                var caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal));
                return caseSensitiveResults.SingleOrDefault();
            }
        }

19 Source : EnumExtensions.cs
with MIT License
from AlexanderPro

internal static TAttribute GetSingleAttributeOrNull<TAttribute>(this Enum value) where TAttribute : Attribute
        {
            var attribute = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(TAttribute), false).SingleOrDefault() as TAttribute;
            return attribute;
        }

19 Source : Int16EnumTypeVisitor.cs
with MIT License
from aliencube

public override void Visit(IAcceptor acceptor, KeyValuePair<string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var name = type.Key;

            var instance = acceptor as OpenApiSchemaAcceptor;
            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Adds enum values to the schema.
            var enums = type.Value.ToOpenApiInt16Collection();

            var schema = new OpenApiSchema()
            {
                Type = "integer",
                Format = "int32",
                Enum = enums,
                Default = enums.First()
            };

            // Adds the visibility property.
            if (attributes.Any())
            {
                var visibilityAttribute = attributes.OfType<OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!visibilityAttribute.IsNullOrDefault())
                {
                    var extension = new OpenApiString(visibilityAttribute.Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
            }

            instance.Schemas.Add(name, schema);
        }

19 Source : StringEnumTypeVisitor.cs
with MIT License
from aliencube

public override void Visit(IAcceptor acceptor, KeyValuePair<string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var name = type.Key;

            var instance = acceptor as OpenApiSchemaAcceptor;
            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Adds enum values to the schema.
            var enums = type.Value.ToOpenApiStringCollection(namingStrategy);

            var schema = new OpenApiSchema()
            {
                Type = "string",
                Format = null,
                Enum = enums,
                Default = enums.First()
            };

            // Adds the visibility property.
            if (attributes.Any())
            {
                var visibilityAttribute = attributes.OfType<OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!visibilityAttribute.IsNullOrDefault())
                {
                    var extension = new OpenApiString(visibilityAttribute.Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
            }

            instance.Schemas.Add(name, schema);
        }

19 Source : ProjectInfo.cs
with MIT License
from aliencube

private void SetProjectPath(string path)
        {
            if (path.IsNullOrWhiteSpace() || path == ".")
            {
                this._projectPath = Environment.CurrentDirectory.TrimEnd(directorySeparator);

                var filepath = Directory.GetFiles(this._projectPath, "*.csproj").SingleOrDefault();
                if (filepath.IsNullOrWhiteSpace())
                {
                    throw new FileNotFoundException();
                }

                var csproj = new FileInfo(filepath);
                this._filename = csproj.Name;

                return;
            }

            var fqpath =
#if NETFRAMEWORK
                System.IO.Path.IsPathRooted(path)
#else
                System.IO.Path.IsPathFullyQualified(path)
#endif
                ? path
                : $"{Environment.CurrentDirectory.TrimEnd(directorySeparator)}{directorySeparator}{path}";

            if (fqpath.EndsWith(".csproj"))
            {
                var csproj = new FileInfo(fqpath);

                this._projectPath = csproj.DirectoryName.TrimEnd(directorySeparator);
                this._filename = csproj.Name;

                return;
            }

            var di = new DirectoryInfo(fqpath);
            this._projectPath = di.FullName.TrimEnd(directorySeparator);

            var segments = di.FullName.Split(new[] { directorySeparator }, StringSplitOptions.RemoveEmptyEntries);
            this._filename = $"{segments.Last()}.csproj";
        }

19 Source : Int64EnumTypeVisitor.cs
with MIT License
from aliencube

public override void Visit(IAcceptor acceptor, KeyValuePair<string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var name = type.Key;

            var instance = acceptor as OpenApiSchemaAcceptor;
            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Adds enum values to the schema.
            var enums = type.Value.ToOpenApiInt64Collection();

            var schema = new OpenApiSchema()
            {
                Type = "integer",
                Format = "int64",
                Enum = enums,
                Default = enums.First()
            };

            // Adds the visibility property.
            if (attributes.Any())
            {
                var visibilityAttribute = attributes.OfType<OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!visibilityAttribute.IsNullOrDefault())
                {
                    var extension = new OpenApiString(visibilityAttribute.Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
            }

            instance.Schemas.Add(name, schema);
        }

19 Source : TypeVisitor.cs
with MIT License
from aliencube

protected string Visit(IAcceptor acceptor, string name, string replacedle, string dataType, string dataFormat, params Attribute[] attributes)
        {
            var instance = acceptor as OpenApiSchemaAcceptor;
            if (instance.IsNullOrDefault())
            {
                return null;
            }

            if (instance.Schemas.ContainsKey(name))
            {
                return null;
            }

            var schema = new OpenApiSchema()
            {
                replacedle = replacedle,
                Type = dataType,
                Format = dataFormat
            };

            // Adds the visibility property.
            if (attributes.Any())
            {
                var visibilityAttribute = attributes.OfType<OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!visibilityAttribute.IsNullOrDefault())
                {
                    var extension = new OpenApiString(visibilityAttribute.Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
            }

            instance.Schemas.Add(name, schema);

            return name;
        }

19 Source : Int32EnumTypeVisitor.cs
with MIT License
from aliencube

public override void Visit(IAcceptor acceptor, KeyValuePair<string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var name = type.Key;

            var instance = acceptor as OpenApiSchemaAcceptor;
            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Adds enum values to the schema.
            var enums = type.Value.ToOpenApiInt32Collection();

            var schema = new OpenApiSchema()
            {
                Type = "integer",
                Format = "int32",
                Enum = enums,
                Default = enums.First()
            };

            // Adds the visibility property.
            if (attributes.Any())
            {
                var visibilityAttribute = attributes.OfType<OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!visibilityAttribute.IsNullOrDefault())
                {
                    var extension = new OpenApiString(visibilityAttribute.Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
            }

            instance.Schemas.Add(name, schema);
        }

19 Source : NullableObjectTypeVisitor.cs
with MIT License
from aliencube

public override void Visit(IAcceptor acceptor, KeyValuePair<string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var instance = acceptor as OpenApiSchemaAcceptor;
            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Gets the schema for the underlying type.
            var underlyingType = type.Value.GetUnderlyingType();
            var types = new Dictionary<string, Type>()
            {
                { type.Key, underlyingType }
            };
            var schemas = new Dictionary<string, OpenApiSchema>();

            var subAcceptor = new OpenApiSchemaAcceptor()
            {
                Types = types,
                Schemas = schemas,
            };

            subAcceptor.Accept(this.VisitorCollection, namingStrategy);

            // Adds the schema for the underlying type.
            var name = subAcceptor.Schemas.First().Key;
            var schema = subAcceptor.Schemas.First().Value;
            schema.Nullable = true;

            // Adds the visibility property.
            if (attributes.Any())
            {
                var visibilityAttribute = attributes.OfType<OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!visibilityAttribute.IsNullOrDefault())
                {
                    var extension = new OpenApiString(visibilityAttribute.Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
            }

            instance.Schemas.Add(name, schema);
        }

19 Source : ConfigurationStore.cs
with MIT License
from alonsoalon

public async Task<TenantInfo> TryGetByIdAsync(string id)
        {
            if (id is null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            return await Task.FromResult(tenantMap.Where(x => x.Id.ToLower() == id.ToLower()).SingleOrDefault());
        }

19 Source : ConfigurationStore.cs
with MIT License
from alonsoalon

public async Task<TenantInfo> TryGetByCodeAsync(string code)
        {
            if (code is null)
            {
                throw new ArgumentNullException(nameof(code));
            }

            return await Task.FromResult(tenantMap.Where(x => x.Code.ToLower() == code.ToLower()).SingleOrDefault());
        }

19 Source : OpenVPNSession.cs
with GNU General Public License v3.0
from Amebis

protected override void DoRun()
        {
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
            try
            {
                try
                {
                    // Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
                    var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
                    mgmtServer.Start();
                    try
                    {
                        try
                        {
                            // Purge stale log files.
                            var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
                            foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
                            {
                                SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
                                if (File.GetLastWriteTimeUtc(f) <= timestamp)
                                {
                                    try { File.Delete(LogPath); }
                                    catch { }
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception) { /* Failure to remove stale log files is not fatal. */ }

                        try
                        {
                            // Save OpenVPN configuration file.
                            using (var fs = new FileStream(
                                ConfigurationPath,
                                FileMode.Create,
                                FileAccess.Write,
                                FileShare.Read,
                                1048576,
                                FileOptions.SequentialScan))
                            using (var sw = new StreamWriter(fs))
                            {
                                // Save profile's configuration to file.

                                if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
                                {
                                    // Remove options on the OpenVPNRemoveOptions list on the fly.
                                    using (var sr = new StringReader(ProfileConfig))
                                    {
                                        string inlineTerm = null;
                                        bool inlineRemove = false;
                                        for (; ; )
                                        {
                                            var line = sr.ReadLine();
                                            if (line == null)
                                                break;

                                            var trimmedLine = line.Trim();
                                            if (!string.IsNullOrEmpty(trimmedLine))
                                            {
                                                // Not an empty line.
                                                if (inlineTerm == null)
                                                {
                                                    // Not inside an inline option block = Regular parsing mode.
                                                    if (!trimmedLine.StartsWith("#") &&
                                                        !trimmedLine.StartsWith(";"))
                                                    {
                                                        // Not a comment.
                                                        var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
                                                        if (option.Count > 0)
                                                        {
                                                            if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
                                                            {
                                                                // Start of an inline option.
                                                                var o = option[0].Substring(1, option[0].Length - 2);
                                                                inlineTerm = "</" + o + ">";
                                                                inlineRemove = openVPNRemoveOptions.Contains(o);
                                                                if (inlineRemove)
                                                                {
                                                                    sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                    line = "# " + line;
                                                                }
                                                            }
                                                            else if (openVPNRemoveOptions.Contains(option[0]))
                                                            {
                                                                sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                line = "# " + line;
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    // Inside an inline option block.
                                                    if (inlineRemove)
                                                    {
                                                        // Remove the inline option content.
                                                        line = "# " + line;
                                                    }

                                                    if (trimmedLine == inlineTerm)
                                                    {
                                                        // Inline option terminator found. Returning to regular parsing mode.
                                                        inlineTerm = null;
                                                    }
                                                }
                                            }

                                            sw.WriteLine(line);
                                        }
                                    }
                                }
                                else
                                    sw.Write(ProfileConfig);

                                // Append eduVPN Client specific configuration directives.
                                sw.WriteLine();
                                sw.WriteLine();
                                sw.WriteLine("# eduVPN Client for Windows");

                                // Introduce ourself (to OpenVPN server).
                                var replacedembly = replacedembly.GetExecutingreplacedembly();
                                var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
                                var replacedemblyVersion = replacedembly?.GetName()?.Version;
                                sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));

                                // Configure log file (relative to WorkingFolder).
                                sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));

                                // Configure interaction between us and openvpn.exe.
                                sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
                                sw.WriteLine("management-client");
                                sw.WriteLine("management-hold");
                                sw.WriteLine("management-query-preplacedwords");
                                sw.WriteLine("management-query-remote");

                                // Configure client certificate.
                                sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
                                sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));

                                // Ask when username/preplacedword is denied.
                                sw.WriteLine("auth-retry interact");
                                sw.WriteLine("auth-nocache");

                                // Set Wintun interface to be used.
                                sw.Write("windows-driver wintun\n");
                                sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");

#if DEBUG
                                // Renegotiate data channel every 5 minutes in debug versions.
                                sw.WriteLine("reneg-sec 300");
#endif

                                if (Environment.OSVersion.Version < new Version(6, 2))
                                {
                                    // Windows 7 is using tiny 8kB send/receive socket buffers by default.
                                    // Increase to 64kB which is default from Windows 8 on.
                                    sw.WriteLine("sndbuf 65536");
                                    sw.WriteLine("rcvbuf 65536");
                                }

                                var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
                                if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
                                {
                                    sw.WriteLine();
                                    sw.WriteLine();
                                    sw.WriteLine("# Added by OpenVPNAddOptions setting:");
                                    sw.WriteLine(openVPNAddOptions);
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }

                        bool retry;
                        do
                        {
                            retry = false;

                            // Connect to OpenVPN Interactive Service to launch the openvpn.exe.
                            using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
                            {
                                var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
                                try
                                {
                                    openvpnInteractiveServiceConnection.Connect(
                                        string.Format("openvpn{0}\\service", InstanceName),
                                        WorkingFolder,
                                        new string[] { "--config", ConnectionId + ".conf", },
                                        mgmtPreplacedword + "\n",
                                        3000,
                                        SessionAndWindowInProgress.Token);
                                }
                                catch (OperationCanceledException) { throw; }
                                catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }

                                try
                                {
                                    // Wait and accept the openvpn.exe on our management interface (--management-client parameter).
                                    var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
                                    try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
                                    catch (AggregateException ex) { throw ex.InnerException; }
                                    var mgmtClient = mgmtClientTask.Result;
                                    try
                                    {
                                        // Start the management session.
                                        ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);

                                        // Initialize session and release openvpn.exe to get started.
                                        ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
                                        ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);

                                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
                                        try
                                        {
                                            // Wait for the session to end gracefully.
                                            ManagementSession.Monitor.Join();
                                            if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
                                            {
                                                // Session reported an error. Retry.
                                                retry = true;
                                            }
                                        }
                                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
                                    }
                                    finally { mgmtClient.Close(); }
                                }
                                finally
                                {
                                    Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                                        () =>
                                        {
                                            // Cleanup status properties.
                                            State = SessionStatusType.Disconnecting;
                                            StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
                                            TunnelAddress = null;
                                            IPv6TunnelAddress = null;
                                            ConnectedAt = null;
                                            BytesIn = null;
                                            BytesOut = null;
                                        }));

                                    // Wait for openvpn.exe to finish. Maximum 30s.
                                    try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
                                    catch (ArgumentException) { }
                                }
                            }
                        } while (retry);
                    }
                    finally
                    {
                        mgmtServer.Stop();
                    }
                }
                finally
                {
                    // Delete profile configuration file. If possible.
                    try { File.Delete(ConfigurationPath); }
                    catch { }
                }
            }
            finally
            {
                Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                    () =>
                    {
                        // Cleanup status properties.
                        State = SessionStatusType.Disconnected;
                        StateDescription = "";

                        Wizard.TaskCount--;
                    }));
                PropertyUpdater.Stop();
            }
        }

19 Source : App.cs
with GNU General Public License v3.0
from Amebis

protected override void OnStartup(StartupEventArgs e)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;

            // Client is using parallelism in web data retrieval.
            // The default maximum concurrent connections set to 2 is a bottleneck.
            ServicePointManager.DefaultConnectionLimit = 5;

            //// Set language preference.
            //var culture = new System.Globalization.CultureInfo("sl-SI");
            //var culture = new System.Globalization.CultureInfo("ar-MA");
            //var culture = new System.Globalization.CultureInfo("tr-TR");
            //var culture = new System.Globalization.CultureInfo("es-CL");
            //System.Globalization.CultureInfo.DefaultThreadCurrentCulture = culture;
            //System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = culture;
            //System.Threading.Thread.CurrentThread.CurrentCulture = culture;
            //System.Threading.Thread.CurrentThread.CurrentUICulture = culture;

            try
            {
                // Test load the user settings.
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            }
            catch (ConfigurationErrorsException ex)
            {
                // Ups, something is wrong with the user settings.
                var replacedemblyreplacedle = (Attribute.GetCustomAttributes(replacedembly.GetExecutingreplacedembly(), typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute)?.replacedle;
                var filename = ex.Filename;
                if (MessageBox.Show(
                    string.Format(Views.Resources.Strings.SettingsCorruptErrorMessage, replacedemblyreplacedle, filename),
                    Views.Resources.Strings.SettingsCorruptErrorreplacedle,
                    MessageBoxButton.OKCancel,
                    MessageBoxImage.Error) == MessageBoxResult.OK)
                {
                    // Delete user settings file and continue.
                    File.Delete(filename);
                }
                else
                {
                    // User cancelled. Quit.
                    Shutdown(1);
                    return;
                }
            }

            eduVPN.Properties.Settings.Initialize();
            Views.Properties.Settings.Initialize();

            eduVPN.Properties.Settings.Default.IsSignon = e.Args.Any(param => param.Equals("/signon", StringComparison.OrdinalIgnoreCase));
            if (eduVPN.Properties.Settings.Default.IsSignon && !Views.Properties.Settings.Default.StartOnSignon)
                Shutdown(0);

            RenderOptions.ProcessRenderMode = Views.Properties.SettingsEx.Default.ProcessRenderMode;

            base.OnStartup(e);
        }

19 Source : IEnumerableExtensions.cs
with Apache License 2.0
from AndcultureCode

public static T PickRandom<T>(this IEnumerable<T> source) => source.PickRandom(1).SingleOrDefault();

19 Source : ShoppingCart.cs
with GNU General Public License v3.0
from andysal

public void AddProduct(int productId, int quanreplacedy, decimal unitPrice)
        {
            if (quanreplacedy <= 0)
            {
                throw new ArgumentException("Product quanreplacedy must be higher than zero.", nameof(quanreplacedy));
            }
            var item = Items.Where(i => i.ProductId == productId)
                            .SingleOrDefault();
            if(item!=null)
            {
                UpdateProductQuanreplacedy(productId, item.Quanreplacedy += quanreplacedy);
            }
            else
            {
                item = new Carreplacedem()
                                {
                                    ProductId = productId,
                                    Quanreplacedy = quanreplacedy,
                                    UnitPrice = unitPrice
                                };
                (Items as List<Carreplacedem>).Add(item);
            }
        }

19 Source : ShoppingCart.cs
with GNU General Public License v3.0
from andysal

public void RemoveProduct(int productId)
        {
            var item = Items.Where(i => i.ProductId == productId)
                            .SingleOrDefault();
            if (item == null)
            {
                throw new ArgumentException("The cart does not cointain the specified product.", nameof(productId));
            }
            else
            {
                (Items as List<Carreplacedem>).Remove(item);
            }
        }

19 Source : ShoppingCart.cs
with GNU General Public License v3.0
from andysal

public void UpdateProductQuanreplacedy(int productId, int quanreplacedy)
        {
            if(quanreplacedy<=0)
            {
                throw new ArgumentException("Product quantoty must be higher than zero.", nameof(quanreplacedy));
            }
            var item = Items.Where(i => i.ProductId == productId)
                            .SingleOrDefault();
            if (item == null)
            {
                throw new ArgumentException("The cart does not cointain the specified product.", nameof(productId));
            }
            else
            {
                item.Quanreplacedy = quanreplacedy;
            }
        }

19 Source : ShoppingCart.cs
with GNU General Public License v3.0
from andysal

public void AddProduct(int productId, int quanreplacedy, decimal unitPrice)
        {
            if (quanreplacedy <= 0)
            {
                throw new ArgumentException("Product quantoty must be higher than zero.", "quanreplacedy");
            }
            var item = Items.Where(i => i.ProductId == productId)
                            .SingleOrDefault();
            if(item!=null)
            {
                UpdateProductQuanreplacedy(productId, item.Quanreplacedy += quanreplacedy);
            }
            else
            {
                item = new Carreplacedem()
                                {
                                    ProductId = productId,
                                    Quanreplacedy = quanreplacedy,
                                    UnitPrice = unitPrice
                                };
                (Items as List<Carreplacedem>).Add(item);
            }
        }

19 Source : ShoppingCart.cs
with GNU General Public License v3.0
from andysal

public void RemoveProduct(int productId)
        {
            var item = Items.Where(i => i.ProductId == productId)
                            .SingleOrDefault();
            if (item == null)
            {
                throw new ArgumentException("The cart does not cointain the specified product.", "productId");
            }
            else
            {
                (Items as List<Carreplacedem>).Remove(item);
            }
        }

19 Source : ShoppingCart.cs
with GNU General Public License v3.0
from andysal

public void UpdateProductQuanreplacedy(int productId, int quanreplacedy)
        {
            if(quanreplacedy<=0)
            {
                throw new ArgumentException("Product quantoty must be higher than zero.", "quanreplacedy");
            }
            var item = Items.Where(i => i.ProductId == productId)
                            .SingleOrDefault();
            if (item == null)
            {
                throw new ArgumentException("The cart does not cointain the specified product.", "productId");
            }
            else
            {
                item.Quanreplacedy = quanreplacedy;
            }
        }

19 Source : Order.cs
with MIT License
from anjoy8

public void AddOrderItem(int productId, string productName, decimal unitPrice, decimal discount, string pictureUrl, int units = 1)
        {
            // 是否存在某一个产品的订单
            var existingOrderForProduct = _orderItems.Where(o => o.ProductId == productId)
                .SingleOrDefault();

            if (existingOrderForProduct != null)
            {
                //如果discount大于当前的折扣,用更高的折扣和单位修改它。

                if (discount > existingOrderForProduct.GetCurrentDiscount())
                {
                    existingOrderForProduct.SetNewDiscount(discount);
                }

                existingOrderForProduct.AddUnits(units);
            }
            else
            {
                //添加经过验证的新订单项

                var orderItem = new OrderItem(productId, productName, unitPrice, discount, pictureUrl, units);
                _orderItems.Add(orderItem);
            }
        }

19 Source : SObjectDescribeFull.cs
with MIT License
from anthonyreilly

public List<PickListValue> GetPicklistValues(string fieldName)
        {
            List<PickListValue> values = new List<PickListValue>();

            if(Fields != null && Fields.Count > 0)
            {
                values =  Fields.Where(f => f.Name == fieldName).Select(f => f.PicklistValues).SingleOrDefault();
            }

            return values;
        }

19 Source : EpubAsArchive.cs
with MIT License
from AntonyCorbett

private string GetSingleChapterPath(string path)
        {
            string result = null;

            var x = GetXmlFile(path);

            var attr = x?.Root?.Attribute("xmlns");
            if (attr != null)
            {
                XNamespace ns = attr.Value;

                var body = x.Root.Descendants(ns + "body").SingleOrDefault();

                const string chapterToken = "#chapter1_verse";
                var verseElem = body?.Descendants(ns + "a").FirstOrDefault(n =>
                {
                    var href = n.Attribute("href");
                    return href != null && href.Value.Contains(chapterToken);
                });

                if (verseElem != null)
                {
                    var href = verseElem.Attribute("href");
                    if (href != null)
                    {
                        var docRef = href.Value;

                        var index = docRef.IndexOf("#", StringComparison.OrdinalIgnoreCase);
                        if (index > -1)
                        {
                            result = docRef.Substring(0, index);
                        }
                    }
                }
            }

            return result;
        }

19 Source : EpubAsArchive.cs
with MIT License
from AntonyCorbett

private VerseRange GetVerseNumbersNewStyle(string fullPath)
        {
            VerseRange result = null;

            var x = GetXmlFile(fullPath);

            var attr = x?.Root?.Attribute("xmlns");
            if (attr != null)
            {
                XNamespace ns = attr.Value;

                var body = x.Root.Descendants(ns + "body").SingleOrDefault();
                var verseRange = body?.Descendants(ns + "a").FirstOrDefault(n =>
                {
                    var xAttribute = n.Attribute("href");
                    return xAttribute != null && xAttribute.Value.StartsWith("bibleversenav");
                });

                if (verseRange != null)
                {
                    result = GetVerseNumbers(verseRange);
                }
            }

            return result;
        }

19 Source : EpubAsArchive.cs
with MIT License
from AntonyCorbett

private VerseRange GetVerseNumbersOldStyle(string fullPath)
        {
            VerseRange result = null;

            var x = GetXmlFile(fullPath);

            var attr = x?.Root?.Attribute("xmlns");
            if (attr != null)
            {
                XNamespace ns = attr.Value;

                var body = x.Root.Descendants(ns + "body").SingleOrDefault();

                const string chapterToken = "chapter";
                var verseElems = body?.Descendants(ns + "a").Where(n =>
                {
                    var idAttr = n.Attribute("id");
                    return idAttr != null && idAttr.Value.StartsWith(chapterToken);
                });

                if (verseElems != null)
                { 
                    int chapterNumber = 0;
                    foreach (var verseElem in verseElems)
                    {
                        var idElem = verseElem.Attribute("id");
                        if (idElem != null)
                        {
                            if (chapterNumber == 0)
                            {
                                var chapterNumberString = idElem.Value.Substring(chapterToken.Length);
                                int.TryParse(chapterNumberString, out chapterNumber);
                            }
                            else
                            {
                                var token = $"{chapterToken}{chapterNumber}_verse";
                                if (idElem.Value.StartsWith(token))
                                {
                                    var verseNumberString = idElem.Value.Substring(token.Length);

                                    if (int.TryParse(verseNumberString, out var verseNum))
                                    {
                                        if (result == null)
                                        {
                                            result = new VerseRange { FirstVerse = int.MaxValue };
                                        }

                                        result.FirstVerse = Math.Min(result.FirstVerse, verseNum);
                                        result.LastVerse = Math.Max(result.LastVerse, verseNum);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }

19 Source : EpubAsArchive.cs
with MIT License
from AntonyCorbett

public IReadOnlyList<BookChapter> GenerateBibleChaptersList(IReadOnlyList<BibleBook> bibleBooks)
        {
            var cachedResult = BibleChaptersCache.Get(_epubPath, _epubCreationStampUtc);
            if (cachedResult != null)
            {
                return cachedResult;
            }

            Log.Logger.Information("Initialising chapters");

            var result = new List<BookChapter>();

            foreach (var book in bibleBooks)
            {
                Log.Logger.Debug($"Book = {book.BookNumber}, {book.BookAbbreviatedName}, {book.FullPath}");

                if (book.HreplacedingleChapter)
                {
                    var bc = new BookChapter
                    {
                        FullPath = book.FullPath,
                        Book = book,
                        Chapter = 1,
                        VerseRange = GetVerseNumbers(book.FullPath)
                    };

                    Log.Logger.Debug($"Chapter = {bc.Chapter}, {bc.FullPath}");
                    result.Add(bc);
                }
                else
                {
                    var x = GetXmlFile(book.FullPath, true);

                    var attr = x?.Root?.Attribute("xmlns");
                    if (attr != null)
                    {
                        XNamespace ns = attr.Value;

                        var body = x.Root.Descendants(ns + "body").SingleOrDefault();
                        if (body != null)
                        {
                            result.AddRange(GetBookChapters(ns, book, body));
                        }
                    }
                }
            }

            ElideRogueVerses(result);

            BibleChaptersCache.Add(_epubPath, _epubCreationStampUtc, result);

            return result;
        }

19 Source : EpubAsArchive.cs
with MIT License
from AntonyCorbett

public IReadOnlyList<BibleBook> GenerateBibleBooksList()
        {
            var cachedResult = BibleBooksCache.Get(_epubPath, _epubCreationStampUtc);
            if (cachedResult != null)
            {
                return cachedResult;
            }

            Log.Logger.Information("Initialising books");

            var nav = _navigationDoreplacedent.Value;

            var result = new List<BibleBook>();

            var attr = nav.Root?.Attribute("xmlns");
            if (attr != null)
            {
                XNamespace ns = attr.Value;

                var body = nav.Root.Descendants(ns + "body").SingleOrDefault();
                if (body != null)
                {
                    var books = body.Descendants(ns + "a").Where(n => n.Attribute("href") != null);
                    int bookNum = 1;

                    foreach (var book in books)
                    {
                        string href = book.Attribute("href")?.Value;
                        if (href != null && href.EndsWith(".xhtml"))
                        {
                            var fullPath = GetFullPathInArchive(href);

                            var bb = new BibleBook
                            {
                                FullPath = fullPath,
                                BookAbbreviatedName = book.Value.Trim(),
                                BookFullName = GetFullNameOfBook(fullPath),
                                BookNumber = bookNum++
                            };

                            if (bb.HreplacedingleChapter)
                            {
                                var scp = GetSingleChapterPath(bb.FullPath);
                                if (!string.IsNullOrEmpty(scp))
                                {
                                    // older formats...
                                    bb.FullPath = GetFullPathInArchive(GetSingleChapterPath(bb.FullPath));
                                }
                            }

                            Log.Logger.Debug($"Book = {bb.BookNumber}, {bb.BookAbbreviatedName}, {bb.FullPath}");

                            result.Add(bb);
                        }
                    }

                    if (result.Count == BibleBooksMetaData.NumBibleBooksGreek)
                    {
                        // renumber...
                        foreach (var book in result)
                        {
                            book.BookNumber = book.BookNumber + BibleBooksMetaData.NumBibleBooksHebrew;
                        }
                    }
                }
            }

            BibleBooksCache.Add(_epubPath, _epubCreationStampUtc, result);

            return result;
        }

19 Source : EpubAsArchive.cs
with MIT License
from AntonyCorbett

public string GetBibleText(
            IReadOnlyList<BookChapter> chapters, 
            int bibleBook, 
            int chapter, 
            int verse,
            FormattingOptions formattingOptions)
        {
            var verseText = OverrideVerseFetch(bibleBook, chapter, verse);
            if (!string.IsNullOrEmpty(verseText))
            {
                return verseText;
            }

            var x = GetChapter(chapters, bibleBook, chapter);
            
            var attr = x?.Root?.Attribute("xmlns");
            if (attr == null)
            {
                return null;
            }

            XNamespace ns = attr.Value;
            var body = x.Root.Descendants(ns + "body").SingleOrDefault();
            if (body == null)
            {
                return null;
            }
            
            var idThisVerse = $"chapter{chapter}_verse{verse}";
            var idNextVerse = $"chapter{chapter}_verse{verse + 1}";

            var elem = body.Descendants().SingleOrDefault(n =>
            {
                var xAttribute = n.Attribute("id");
                return xAttribute != null && xAttribute.Value.Equals(idThisVerse);
            });

            var parentPara = elem?.Parent;
            if (parentPara == null)
            {
                return null;
            }
            
            var sb = new StringBuilder();

            var paras = new List<XElement> { parentPara };
            paras.AddRange(parentPara.ElementsAfterSelf());

            bool started = false;
            
            foreach (var para in paras)
            {
                var result = GetParagraph(
                    para, 
                    parentPara, 
                    ns, 
                    idThisVerse, 
                    idNextVerse, 
                    formattingOptions,
                    started);

                sb.Append(result.Text);

                if (result.Finished)
                {
                    break;
                }

                started = result.Started;
            }

            return sb.ToString().Trim().Trim('~');
        }

19 Source : EpubAsArchive.cs
with MIT License
from AntonyCorbett

private string GetFullNameOfBook(string fullPath)
        {
            var x = GetXmlFile(fullPath, true);

            var attr = x?.Root?.Attribute("xmlns");
            if (attr != null)
            {
                XNamespace ns = attr.Value;

                var replacedle = x.Root.Descendants(ns + "replacedle").SingleOrDefault();
                var result = replacedle?.Value;

                if (result != null && _epubStyle == EpubStyle.Old && result.Trim().EndsWith(")", StringComparison.Ordinal))
                {
                    var trimPos = result.LastIndexOf("(", StringComparison.OrdinalIgnoreCase);
                    if (trimPos > -1)
                    {
                        result = result.Substring(0, trimPos).Trim();
                    }
                }

                return result?.Trim();
            }

            return null;
        }

19 Source : AggregateHelper.cs
with MIT License
from ARKlab

private static string _getName() 
                => typeof(TEvent)
                .GetTypeInfo()
                .GetCustomAttributes<EventNameAttribute>().SingleOrDefault()?.Name 
                ?? typeof(TEvent).Name;

19 Source : AggregateHelper.cs
with MIT License
from ARKlab

private static string _getName()
        {
            return typeof(TAggregate)
                .GetTypeInfo()
                .GetCustomAttributes<AggregateNameAttribute>().SingleOrDefault()?.Name
                ?? typeof(TAggregate).Name;
        }

19 Source : ResourceWatcher.cs
with MIT License
from ARKlab

private List<ProcessContext> _createEvalueteList(List<IResourceMetadata> list, IEnumerable<ResourceState> states)
        {
            var ev = list.GroupJoin(states, i => i.ResourceId, s => s.ResourceId, (i, s) =>
             {
                 var x = new ProcessContext { CurrentInfo = i, LastState = s.SingleOrDefault() };
                 if (x.LastState == null)
                 {
                     x.ProcessType = ProcessType.New;
                 }
                 else if (x.LastState.RetryCount == 0 && x.IsResourceUpdated(out _))
                 {
                     x.ProcessType = ProcessType.Updated;
                 }
                 else if (x.LastState.RetryCount > 0 && x.LastState.RetryCount <= _config.MaxRetries)
                 {
                     x.ProcessType = ProcessType.Retry;
                 }
                 else if (x.LastState.RetryCount > _config.MaxRetries
                     && x.IsResourceUpdated(out _)
                     && x.LastState.LastEvent + _config.BanDuration < SystemClock.Instance.GetCurrentInstant()
                     // BAN expired and new version                
                     )
                 {
                     x.ProcessType = ProcessType.RetryAfterBan;
                 }
                 else if (x.LastState.RetryCount > _config.MaxRetries
                     && x.IsResourceUpdated(out _)
                     && !(x.LastState.LastEvent + _config.BanDuration < SystemClock.Instance.GetCurrentInstant())
                     // BAN               
                     )
                 {
                     x.ProcessType = ProcessType.Banned;
                 }
                 else
                     x.ProcessType = ProcessType.NothingToDo;

                 if (x.ProcessType == ProcessType.NothingToDo || x.ProcessType == ProcessType.Banned)
                 {
                     x.ResultType = ResultType.Skipped;
                 }

                 return x;
             }).ToList();

            return ev;
        }

19 Source : AuthenticationManager.cs
with Apache License 2.0
from aspnet

public async Task<AuthenticateResult> AuthenticateAsync(string authenticationType)
        {
            return (await AuthenticateAsync(new[] { authenticationType })).SingleOrDefault();
        }

19 Source : Descriptor.cs
with GNU General Public License v3.0
from audiamus

private static T getAttribute<T> (PropertyDescriptor propdesc) where T : Attribute {
      var attr = propdesc.Attributes
        .Cast<Attribute> ()
        .Where (a => a.GetType ().Equals (typeof (T)))
        .SingleOrDefault () as T;
      return attr;
    }

19 Source : EnumDescriptionConverter.cs
with MIT License
from AvaloniaCommunity

private string GetEnumDescription(Enum enumObj)
        {
            FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());
            var descriptionAttr = fieldInfo
                                          .GetCustomAttributes(false)
                                          .OfType<DescriptionAttribute>()
                                          .Cast<DescriptionAttribute>()
                                          .SingleOrDefault();
            if (descriptionAttr == null)
            {
                return enumObj.ToString();
            }
            else
            {
                return descriptionAttr.Description;
            }
        }

19 Source : CosmosDbValueQuery.cs
with MIT License
from Avanade

public T? SelectSingleOrDefault()
        {
            return _container.GetValue(ExecuteQuery(q =>
            {
                q = q.Paging(0, 2);
                return q.AsEnumerable().SingleOrDefault();
            }));
        }

19 Source : CosmosDbQueryExtensions.cs
with MIT License
from Avanade

public static T SelectSingleOrDefault<T>(this IQueryable<T> query)
        {
            return query.Paging(0, 2).AsEnumerable().SingleOrDefault();
        }

19 Source : Extention.Enum.cs
with MIT License
from awesomedotnetcore

public static string GetDescription(this Enum value)
        {
            DescriptionAttribute attribute = value.GetType()
                .GetField(value.ToString())
                .GetCustomAttributes(typeof(DescriptionAttribute), false)
                .SingleOrDefault() as DescriptionAttribute;
            return attribute == null ? value.ToString() : attribute.Description;
        }

19 Source : XmlOverridesMerger.cs
with Apache License 2.0
from aws

private static bool Merge(XmlElement serviceConfiguration, XmlElement serviceOverride)
        {
            foreach (var overrideElementsByName in serviceOverride.ChildNodes.OfType<XmlElement>().GroupBy(element => element.Name))
            {
                switch (overrideElementsByName.Key)
                {
                    case nameof(ConfigModel.FileVersion):
                        {
                            var currentFileVersion =  int.Parse(GetChildElementsByTagName(serviceConfiguration, nameof(ConfigModel.FileVersion)).SingleOrDefault()?.InnerXml ?? "0");
                            var overridesFileVersion = int.Parse(overrideElementsByName.Single().InnerXml);
                            if (currentFileVersion != overridesFileVersion)
                            {
                                return false;
                            }
                        }
                        break;
                    case nameof(ConfigModel.C2jFilename):
                        break;
                    case nameof(ConfigModel.SkipCmdletGeneration):
                    case nameof(ConfigModel.replacedemblyName):
                    case nameof(ConfigModel.ServiceNounPrefix):
                    case nameof(ConfigModel.ServiceName):
                    case nameof(ConfigModel.ServiceClientInterface):
                    case nameof(ConfigModel.ServiceClient):
                    case nameof(ConfigModel.ServiceModuleGuid):
                        throw new NotSupportedException($"The {overrideElementsByName.Key} configuration cannot be changed through overrides");
                    case nameof(ConfigModel.ServiceOperations):
                        MergeOperations(GetChildElementsByTagName(serviceConfiguration, nameof(ConfigModel.ServiceOperations)).Single(),
                                        overrideElementsByName.SelectMany(overrideOperations => overrideOperations.ChildNodes.OfType<XmlElement>()));
                        break;
                    default:
                        foreach(var elementsToBeReplaced in GetChildElementsByTagName(serviceConfiguration, overrideElementsByName.Key).ToArray())
                        {
                            serviceConfiguration.RemoveChild(elementsToBeReplaced);
                        }
                        foreach(var overrideElement in overrideElementsByName)
                        {
                            serviceConfiguration.AppendChild(serviceConfiguration.OwnerDoreplacedent.ImportNode(overrideElement, true));
                        }
                        break;
                }
            }

            return true;
        }

19 Source : Utils.cs
with Apache License 2.0
from aws

public static string FindResourceName(string partialName)
        {
            return FindResourceName(s => s.IndexOf(partialName, StringComparison.OrdinalIgnoreCase) >= 0).SingleOrDefault();
        }

See More Examples