bool.TryParse(string, out bool)

Here are the examples of the csharp api bool.TryParse(string, out bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1317 Examples 7

19 View Source File : BooleanControlTemplate.cs
License : MIT License
Project Creator : Adoxio

private void AddSpecialBindingAndHiddenFieldsToPersistDisabledCheckBox(Control container, CheckBox checkBox)
		{
			checkBox.InputAttributes["clreplaced"] = "{0} readonly".FormatWith(CssClreplaced);
			checkBox.InputAttributes["disabled"] = "disabled";
			checkBox.InputAttributes["aria-disabled"] = "true";

			var hiddenValue = new HiddenField
			{
				ID = "{0}_Value".FormatWith(ControlID),
				Value = checkBox.Checked.ToString(CultureInfo.InvariantCulture)
			};
			container.Controls.Add(hiddenValue);

			RegisterClientSideDependencies(container);

			Bindings[Metadata.DataFieldName] = new CellBinding
			{
				Get = () =>
				{
					bool value;
					return bool.TryParse(hiddenValue.Value, out value) ? new bool?(value) : null;
				},
				Set = obj =>
				{
					var value = Convert.ToBoolean(obj);
					checkBox.Checked = value;
					hiddenValue.Value = value.ToString(CultureInfo.InvariantCulture);
				}
			};
		}

19 View Source File : SetupConfig.cs
License : MIT License
Project Creator : Adoxio

public static bool ProvisioningInProgress()
		{
			if (!PortalSettings.Instance.UseOnlineSetup) return false;

			bool inProgress;
			var setupInProgress = bool.TryParse(ConfigurationManager.AppSettings["PortalSetupInProgress"], out inProgress) && inProgress;

			if (!setupInProgress)
			{
				return false;
			}

			var websiteId = ConfigurationManager.AppSettings["PortalPackageName"];
			
			// Try to query the CRM for a PackageImportComplete setting to see if the package may have been installed already.
			try
			{
				var query = new QueryExpression("adx_setting") { ColumnSet = new ColumnSet("adx_name") };
				query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
				query.Criteria.AddCondition("adx_name", ConditionOperator.Equal, "PackageImportComplete");
				query.Criteria.AddCondition("adx_value", ConditionOperator.Equal, websiteId);

				var service = CrmConfigurationManager.CreateService();

				if (service.RetrieveMultiple(query).Enreplacedies.Count > 0)
				{
					return false;
				}
			}
			catch (Exception e)
			{
				// Ignore connection exceptions

				ADXTrace.Instance.TraceInfo(TraceCategory.Exception, string.Format("PackageImportComplete: Provisioning is in progress: {0}", e));
			}

			// If there is a website record & the plugins are enabled then we can create a website binding. 
			try
			{
				var adxWebsiteQuery = new QueryExpression("adx_website");
				adxWebsiteQuery.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
				adxWebsiteQuery.Criteria.AddCondition("adx_websiteid", ConditionOperator.Equal, websiteId);

				var service = CrmConfigurationManager.CreateService();

				if (service.RetrieveMultiple(adxWebsiteQuery).Enreplacedies.Count > 0)
				{
					// Now Check if the plugins are enabled. If they are enabled then we know that the data import is complete or if
					//  its not then the cache invalidation plugin is enabled so the webapp will be told of any new changes. 
					var webNotificationPluginQuery = new QueryExpression("pluginreplacedembly");
					webNotificationPluginQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "Adxstudio.Xrm.Plugins.WebNotification");
					webNotificationPluginQuery.Criteria.AddCondition("componentstate", ConditionOperator.Equal, 0);

					if (service.RetrieveMultiple(webNotificationPluginQuery).Enreplacedies.Count > 0)
					{
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Ending provisioning in progress. Creating the AdxSetting");
						SetSettingForPackageComplete(service, websiteId);
						return false;
					}
				}
			}
			catch (Exception e)
			{
				// Ignore connection exceptions

				ADXTrace.Instance.TraceInfo(TraceCategory.Exception, string.Format("Website: Provisioning is in progress: {0}", e));
			}

			return true;
		}

19 View Source File : FSDirectorySearchProvider.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().Name;
			}

			base.Initialize(name, config);

			var dataContextName = config["dataContextName"];

			SearchDataContextName = config["searchDataContextName"] ?? dataContextName;
			UpdateDataContextName = config["updateDataContextName"] ?? dataContextName;

			var indexPath = config["indexPath"];

			if (string.IsNullOrEmpty(indexPath))
			{
				throw new ProviderException("The search provider {0} requires the attribute indexPath to be set.".FormatWith(name));
			}

			IndexDirectory = new DirectoryInfo(
				(indexPath.StartsWith(@"~/", StringComparison.Ordinal) || indexPath.StartsWith(@"~\", StringComparison.Ordinal))
					? HostingEnvironment.MapPath(indexPath) ?? indexPath
					: indexPath);

			var useEncryptedDirectory = false;
			bool.TryParse(config["useEncryptedDirectory"], out useEncryptedDirectory);
			UseEncryptedDirectory = useEncryptedDirectory;

			var isOnlinePortal = false;
			bool.TryParse(config["isOnlinePortal"], out isOnlinePortal);
			IsOnlinePortal = isOnlinePortal;

			IndexQueryName = config["indexQueryName"] ?? _defaultIndexQueryName;
			Stemmer = CultureInfo.CurrentUICulture.Parent.EnglishName;

			var stopWords = config["stopWords"];

			StopWords = string.IsNullOrEmpty(stopWords)
				? new string[] { }
				: stopWords.Split(',').Select(word => word.Trim()).Where(word => !string.IsNullOrEmpty(word)).ToArray();

			var searcherCacheMode = config["indexSearcherCacheMode"];

			IndexSearcherCacheMode mode;

			_searcherPool = !string.IsNullOrEmpty(searcherCacheMode) && Enum.TryParse(searcherCacheMode, out mode) && mode == IndexSearcherCacheMode.SingleUse
				? new SingleUseIndexSearcherPool()
				: _sharedSearcherPool;

			var indexVersion = config["indexVersion"];

			Version version;

			Version = !string.IsNullOrEmpty(indexVersion) && Enum.TryParse(indexVersion, out version)
				? version
				: Version.LUCENE_23;

			Guid websiteId;
			WebsiteId = Guid.TryParse(config["websiteId"], out websiteId)
				? websiteId
				: (Guid?)null;

			var recognizedAttributes = new List<string>
			{
				"name",
				"description",
				"dataContextName",
				"indexPath",
				"indexQueryName",
				"indexSearcherCacheMode",
				"indexVersion",
				"searchDataContextName",
				"stemmer",
				"stopWords",
				"updateDataContextName",
				"isOnlinePortal",
				"useEncryptedDirectory",
				"websiteId",
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ProviderException("The search provider {0} does not currently recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}
		}

19 View Source File : EditableOptions.cs
License : MIT License
Project Creator : Adoxio

private static bool? GetBooleanAttributeValue(object value)
		{
			if (value == null)
			{
				return null;
			}

			if (value is bool)
			{
				return (bool)value;
			}

			bool parsed;

			return bool.TryParse(value.ToString(), out parsed)
				? parsed
				: (bool?)null;
		}

19 View Source File : ContentAccessProvider.cs
License : MIT License
Project Creator : Adoxio

protected bool IsSiteSettingEnabled(string siteSettingName)
        {
            string siteSettingEnabledString;
            if (this.siteSettingDictionary != null && this.siteSettingDictionary.ContainsKey(siteSettingName))
            {
                siteSettingEnabledString = this.siteSettingDictionary[siteSettingName];
            }
            else
            {
                var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
                siteSettingEnabledString = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, siteSettingName);
            }

            // By default, if the site setting isn't configured - don't enable it
            var siteSettingEnabled = false;

            bool.TryParse(siteSettingEnabledString, out siteSettingEnabled);

            return siteSettingEnabled;
        }

19 View Source File : ObjectCacheOutputCacheProvider.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			ObjectCacheName = config["objectCacheName"];
			CacheRegionName = config["cacheRegionName"];
			CacheKeyFormat = config["cacheKeyFormat"] ?? @"{0}:{{0}}".FormatWith(this);

			bool cacheItemDependenciesEnabled;
			if (!bool.TryParse(config["cacheItemDependenciesEnabled"], out cacheItemDependenciesEnabled))
			{
				cacheItemDependenciesEnabled = true;    // true by default
			}
			CacheItemDependenciesEnabled = cacheItemDependenciesEnabled;

			bool includeCacheItemDetails;
			IncludeCacheItemDetails = bool.TryParse(config["includeCacheItemDetails"], out includeCacheItemDetails) && includeCacheItemDetails;	// false by default

			base.Initialize(name, config);

			config.Remove("objectCacheName");
			config.Remove("cacheRegionName");
			config.Remove("cacheKeyFormat");
			config.Remove("cacheItemDependenciesEnabled");
			config.Remove("includeCacheItemDetails");

			if (config.Count > 0)
			{
				string unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ConfigurationErrorsException("The {0} doesn't recognize or support the attribute {1}.".FormatWith(this, unrecognizedAttribute));
				}
			}
		}

19 View Source File : EntityListODataFeedDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public virtual EdmEnreplacedyObjectCollection SelectMultiple(IEdmModel model, string enreplacedySetName, System.Web.Http.OData.Query.ODataQueryOptions queryOptions, System.Web.Http.OData.Query.ODataQuerySettings querySettings, HttpRequestMessage request)
		{
			var edmEnreplacedySchemaType = model.FindDeclaredType(string.Format("{0}.{1}", NamespaceName, enreplacedySetName));
			var edmEnreplacedyType = edmEnreplacedySchemaType as IEdmEnreplacedyType;
			var enreplacedyListIdProperty = edmEnreplacedyType.FindProperty("list-id") as IEdmStructuralProperty;
			var enreplacedyListIdString = enreplacedyListIdProperty.DefaultValueString;
			var viewIdProperty = edmEnreplacedyType.FindProperty("view-id") as IEdmStructuralProperty;
			var viewIdString = viewIdProperty.DefaultValueString;
			var enreplacedyPermissionEnabledProperty =
				edmEnreplacedyType.FindProperty("enreplacedy-permissions-enabled") as IEdmStructuralProperty;
			bool enreplacedyPermissionsEnabled;
			bool.TryParse(enreplacedyPermissionEnabledProperty.DefaultValueString, out enreplacedyPermissionsEnabled);

			Guid viewId;
			Guid.TryParse(viewIdString, out viewId);
			var view = GetView(viewId);
			var viewColumns = view.Columns.ToList();
			var fetch = Fetch.Parse(view.FetchXml);
			queryOptions.ApplyTo(querySettings, fetch);
			var serviceContext = this.Dependencies.GetServiceContext();

			// If Enreplacedy Permissions on the view was enabled then restrict add enreplacedy Permissions to Fetch
			if (enreplacedyPermissionsEnabled)
			{
				var crmEnreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
				var perm = crmEnreplacedyPermissionProvider.TryApplyRecordLevelFiltersToFetch(
					serviceContext,
					CrmEnreplacedyPermissionRight.Read,
					fetch);

				// Ensure the user has permissions to request read access to the enreplacedy.
				if (!perm.PermissionGranted && !perm.GlobalPermissionGranted)
				{
					ADXTrace.Instance.TraceWarning(
						TraceCategory.Exception,
						string.Format(
							"Access to oData, with the enreplacedy set name of '{0}', has been denied for the user with the following webroles: '{1}' due to enreplacedy permissions. Grant the webroles read access to the enreplacedyset if this was not an error.",
							enreplacedySetName,
							string.Join("', '", crmEnreplacedyPermissionProvider.CurrentUserRoleNames)));
					throw new SecurityAccessDeniedException();
				}
			}

			var dataSchemaType = model.FindDeclaredType(string.Format("{0}.{1}", NamespaceName, enreplacedySetName));
			var dataEnreplacedyType = dataSchemaType as IEdmEnreplacedyType;
			var dataEnreplacedyTypeReference = new EdmEnreplacedyTypeReference(dataEnreplacedyType, true);
			var collection = new EdmEnreplacedyObjectCollection(new EdmCollectionTypeReference(new EdmCollectionType(dataEnreplacedyTypeReference), true));
			var enreplacedyReferenceSchemaType = model.FindDeclaredType(string.Format("{0}.{1}", NamespaceName, "EnreplacedyReference"));
			var enreplacedyReferenceComplexType = enreplacedyReferenceSchemaType as IEdmComplexType;
			var enreplacedyReferenceComplexTypeReference = new EdmComplexTypeReference(enreplacedyReferenceComplexType, true);
			var optionSetSchemaType = model.FindDeclaredType(string.Format("{0}.{1}", NamespaceName, "OptionSet"));
			var optionSetComplexType = optionSetSchemaType as IEdmComplexType;
			var optionSetComplexTypeReference = new EdmComplexTypeReference(optionSetComplexType, true);
			var enreplacedyCollection = fetch.Execute(serviceContext as IOrganizationService);
			
			if (enreplacedyCollection == null)
			{
				return collection;
			}
			
			var records = enreplacedyCollection.Enreplacedies;

			foreach (var record in records)
			{
				var enreplacedyObject = BuildEdmEnreplacedyObject(record, view, viewColumns, dataEnreplacedyTypeReference, enreplacedyReferenceComplexTypeReference, optionSetComplexTypeReference, enreplacedyListIdString, viewIdString);
				collection.Add(enreplacedyObject);
			}

			if (enreplacedyCollection.MoreRecords && querySettings.PageSize.HasValue && querySettings.PageSize > 0)
			{
				var nextPageLink = ODataQueryOptionExtensions.GetNextPageLink(request, querySettings.PageSize.Value);
				request.SetNextPageLink(nextPageLink);
			}

			if (enreplacedyCollection.TotalRecordCount > 0)
			{
				request.SetInlineCount(enreplacedyCollection.TotalRecordCount);
			}

			return collection;
		}

19 View Source File : CommandSettings.cs
License : MIT License
Project Creator : actions

private bool TestFlag(string name)
        {
            bool result = _parser.Flags.Contains(name);
            if (!result)
            {
                string envStr = GetEnvArg(name);
                if (!bool.TryParse(envStr, out result))
                {
                    result = false;
                }
            }

            _trace.Info($"Flag '{name}': '{result}'");
            return result;
        }

19 View Source File : ConfigFile.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public bool GetBool(string key)
        {
            bool result;
            if (booleans.TryGetValue(key, out result))
            {
                return result;
            }
            string val;
            if (allValues.TryGetValue(key, out val))
            {
                if (bool.TryParse(val, out result))
                {
                    booleans.Add(key, result);
                }
            }
            return result;
        }

19 View Source File : ActionCommandManager.cs
License : MIT License
Project Creator : actions

public void ProcessCommand(IExecutionContext context, string line, ActionCommand command, ContainerInfo container)
        {
            var allowUnsecureCommands = false;
            bool.TryParse(Environment.GetEnvironmentVariable(Constants.Variables.Actions.AllowUnsupportedCommands), out allowUnsecureCommands);

            // Apply environment from env context, env context contains job level env and action's env block
#if OS_WINDOWS
            var envContext = context.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = context.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            if (!allowUnsecureCommands && envContext.ContainsKey(Constants.Variables.Actions.AllowUnsupportedCommands))
            {
                bool.TryParse(envContext[Constants.Variables.Actions.AllowUnsupportedCommands].ToString(), out allowUnsecureCommands);
            }

            if (!allowUnsecureCommands)
            {
                throw new Exception(String.Format(Constants.Runner.UnsupportedCommandMessageDisabled, this.Command));
            }

            if (!command.Properties.TryGetValue(SetEnvCommandProperties.Name, out string envName) || string.IsNullOrEmpty(envName))
            {
                throw new Exception("Required field 'name' is missing in ##[set-env] command.");
            }


            foreach (var blocked in _setEnvBlockList)
            {
                if (string.Equals(blocked, envName, StringComparison.OrdinalIgnoreCase))
                {
                    // Log Telemetry and let user know they shouldn't do this
                    var issue = new Issue()
                    {
                        Type = IssueType.Error,
                        Message = $"Can't update {blocked} environment variable using ::set-env:: command."
                    };
                    issue.Data[Constants.Runner.InternalTelemetryIssueDataKey] = $"{Constants.Runner.UnsupportedCommand}_{envName}";
                    context.AddIssue(issue);

                    return;
                }
            }

            context.Global.EnvironmentVariables[envName] = command.Data;
            context.SetEnvContext(envName, command.Data);
            context.Debug($"{envName}='{command.Data}'");
        }

19 View Source File : DirectoryContentHash.cs
License : MIT License
Project Creator : Adoxio

public static bool TryParse(string value, out DirectoryContentHash hash)
		{
			hash = null;

			try
			{
				if (string.IsNullOrEmpty(value))
				{
					return false;
				}

				var decoded = Base64Decode(value);

				var match = Regex.Match(decoded, "^(?<LogicalName>[^:]+):(?<Id>.+):(?<IsDirectory>.*)$", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture);

				if (!match.Success)
				{
					return false;
				}

				var logicalName = match.Groups["LogicalName"].Value;

				Guid id;

				if (!Guid.TryParse(match.Groups["Id"].Value, out id))
				{
					return false;
				}

				bool isDirectoryValue;

				var isDirectory = bool.TryParse(match.Groups["IsDirectory"].Value, out isDirectoryValue) && isDirectoryValue;

				hash = new DirectoryContentHash(new EnreplacedyReference(logicalName, id), isDirectory);

				return true;
			}
			catch
			{
				return false;
			}
		}

19 View Source File : DebugOrganizationService.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			Formatting formatting;

			if (Enum.TryParse(config["formatting"], out formatting))
			{
				Formatting = formatting;
			}

			bool includeResponse;

			if (bool.TryParse(config["includeResponse"], out includeResponse))
			{
				IncludeResponse = includeResponse;
			}

			base.Initialize(name, config);
		}

19 View Source File : ExpanderStyleSelector.cs
License : MIT License
Project Creator : Actipro

public override Style SelectStyle(object item, DependencyObject container) {
			Expander expander = container as Expander;
			if (null == expander)
				return null;

			string styleKey = "ExpanderGroupStyle";
			XmlElement element = item as XmlElement;
			if (null != element) {
				if (null != element.Attributes["UseAlternateStyle"]) {
					bool useAlternateStyle;
					if (bool.TryParse(element.Attributes["UseAlternateStyle"].Value, out useAlternateStyle)) {
						if (useAlternateStyle)
							styleKey = "ExpanderGroupAlternateStyle";
					}
				}
			}

			return expander.FindResource(styleKey) as Style;
		}

19 View Source File : CrmContactRoleProvider.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (_initialized)
			{
				return;
			}

			config.ThrowOnNull("config");

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().FullName;
			}

			if (string.IsNullOrEmpty(config["description"]))
			{
				config["description"] = "XRM Role Provider";
			}

			base.Initialize(name, config);

			replacedertRequiredCustomAttributes(config);

			ApplicationName = config["applicationName"] ?? Utility.GetDefaultApplicationName();

			_attributeMapIsAuthenticatedUsersRole = config["attributeMapIsAuthenticatedUsersRole"];

			bool authenticatedUsersRolesEnabledConfigurationValue;

			// Whether "Authenticated Users" role is supported is determine by a config switch, and whether
			// or not an attribute map for that boolean has been supplied. The feature is enabled by default,
			// provided that an attribute map has been supplied.
			_authenticatedUsersRolesEnabled = !string.IsNullOrWhiteSpace(_attributeMapIsAuthenticatedUsersRole)
				&& bool.TryParse(config["authenticatedUsersRolesEnabled"], out authenticatedUsersRolesEnabledConfigurationValue)
					? authenticatedUsersRolesEnabledConfigurationValue
					: true;

			_attributeMapStateCode = config["attributeMapStateCode"];

			_attributeMapIsDisabled = config["attributeMapIsDisabled"];

			_attributeMapRoleName = config["attributeMapRoleName"];

			_attributeMapRoleWebsiteId = config["attributeMapRoleWebsiteId"];

			_attributeMapUsername = config["attributeMapUsername"];

			PortalName = config["portalName"];

			_roleEnreplacedyName = config["roleEnreplacedyName"];

			_roleToUserRelationshipName = config["roleToUserRelationshipName"];

			_userEnreplacedyName = config["userEnreplacedyName"];

			_roleEnreplacedyId = config["roleEnreplacedyId"];

			_userEnreplacedyId = config["userEnreplacedyId"];

			var recognizedAttributes = new List<string>
			{
				"name",
				"applicationName",
				"attributeMapStateCode",
				"attributeMapIsDisabled",
				"attributeMapIsAuthenticatedUsersRole",
				"attributeMapRoleName",
				"attributeMapRoleWebsiteId",
				"attributeMapUsername",
				"portalName",
				"roleEnreplacedyName",
				"roleToUserRelationshipName",
				"userEnreplacedyName",
				"roleEnreplacedyId",
				"userEnreplacedyId"
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ConfigurationErrorsException("The {0} doesn't recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}

			_initialized = true;
		}

private void AddDefaultWorksets()
        {
            var newWorksets = ModelSetupWizardSettings.Default.DefaultWorksets;
            foreach (var newWorksetDef in newWorksets)
            {
                var segs = newWorksetDef.Split(';');
                var b = false;
                bool.TryParse(segs[1].Trim(), out b);
                if (!string.IsNullOrEmpty(segs[0]))
                {
                    if (segs.Length > 2 && !string.IsNullOrEmpty(segs[2]))
                    {
                        WorksetParameter wp = new WorksetParameter(segs[0], b, segs[2]);
                        Worksets.Add(wp);
                    }
                    else
                    {
                        WorksetParameter wp = new WorksetParameter(segs[0], b, -1);
                        Worksets.Add(wp);
                    }
                }
            }
        }

19 View Source File : XNodeExtensions.cs
License : MIT License
Project Creator : Adoxio

public static bool TryGetBooleanElementValue(this XNode startingNode, string elementXPath, out bool elementValue)
		{
			elementValue = false;

			string textValue;

			return startingNode.TryGetElementValue(elementXPath, out textValue) && bool.TryParse(textValue, out elementValue);
		}

19 View Source File : SettingDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public bool? GetBooleanValue(string settingName)
		{
			return SelectValue(settingName, value =>
			{
				if (value == null)
				{
					return null;
				}

				bool b;

				if (_booleanValueMappings.TryGetValue(value, out b))
				{
					return b;
				}

				return bool.TryParse(value, out b) ? new bool?(b) : null;
			});
		}

19 View Source File : CrmRoleProvider.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (_initialized)
			{
				return;
			}

			config.ThrowOnNull("config");

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().FullName;
			}

			if (string.IsNullOrEmpty(config["description"]))
			{
				config["description"] = "XRM Role Provider";
			}

			base.Initialize(name, config);

			replacedertRequiredCustomAttributes(config);

			ApplicationName = config["applicationName"] ?? Utility.GetDefaultApplicationName();

			_attributeMapIsAuthenticatedUsersRole = config["attributeMapIsAuthenticatedUsersRole"];

			bool authenticatedUsersRolesEnabledConfigurationValue;

			// Whether "Authenticated Users" role is supported is determine by a config switch, and whether
			// or not an attribute map for that boolean has been supplied. The feature is enabled by default,
			// provided that an attribute map has been supplied.
			_authenticatedUsersRolesEnabled = !string.IsNullOrWhiteSpace(_attributeMapIsAuthenticatedUsersRole)
				&& bool.TryParse(config["authenticatedUsersRolesEnabled"], out authenticatedUsersRolesEnabledConfigurationValue)
					? authenticatedUsersRolesEnabledConfigurationValue
					: true;

			_attributeMapRoleName = config["attributeMapRoleName"];

			_attributeMapRoleWebsiteId = config["attributeMapRoleWebsiteId"];

			_attributeMapUsername = config["attributeMapUsername"];

			PortalName = config["portalName"];

			_roleEnreplacedyName = config["roleEnreplacedyName"];

			_roleToUserRelationshipName = config["roleToUserRelationshipName"];

			_userEnreplacedyName = config["userEnreplacedyName"];

			var recognizedAttributes = new List<string>
			{
				"name",
				"applicationName",
				"attributeMapIsAuthenticatedUsersRole",
				"attributeMapRoleName",
				"attributeMapRoleWebsiteId",
				"attributeMapUsername",
				"portalName",
				"roleEnreplacedyName",
				"roleToUserRelationshipName",
				"userEnreplacedyName"
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ConfigurationErrorsException("The {0} does not currently recognize or support the attribute '{1}'".FormatWith(name, unrecognizedAttribute));
				}
			}

			_initialized = true;
		}

19 View Source File : UraganoBuilderExtensions.cs
License : MIT License
Project Creator : 1100100

private static void ReadFromConfiguration(this ExceptionlessConfiguration config, IConfiguration settings)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));

            if (settings == null)
                throw new ArgumentNullException(nameof(settings));

            var apiKey = settings["ApiKey"];
            if (!string.IsNullOrEmpty(apiKey) && apiKey != "API_KEY_HERE")
                config.ApiKey = apiKey;

            foreach (var data in settings.GetSection("DefaultData").GetChildren())
                if (data.Value != null)
                    config.DefaultData[data.Key] = data.Value;

            foreach (var tag in settings.GetSection("DefaultTags").GetChildren())
                config.DefaultTags.Add(tag.Value);

            if (bool.TryParse(settings["Enabled"], out var enabled) && !enabled)
                config.Enabled = false;

            if (bool.TryParse(settings["IncludePrivateInformation"], out var includePrivateInformation) && !includePrivateInformation)
                config.IncludePrivateInformation = false;

            var serverUrl = settings["ServerUrl"];
            if (!string.IsNullOrEmpty(serverUrl))
                config.ServerUrl = serverUrl;

            var storagePath = settings["StoragePath"];
            if (!string.IsNullOrEmpty(storagePath))
                config.Resolver.Register(typeof(IObjectStorage), () => new FolderObjectStorage(config.Resolver, storagePath));

            foreach (var setting in settings.GetSection("Settings").GetChildren())
                if (setting.Value != null)
                    config.Settings[setting.Key] = setting.Value;
        }

19 View Source File : AnarchyStorage.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public bool GetBool(string key, bool def)
        {
            bool result;
            if (booleans.TryGetValue(key, out result))
            {
                return result;
            }
            string val;
            if (allValues.TryGetValue(key, out val))
            {
                if (bool.TryParse(val, out result))
                {
                    booleans.Add(key, result);
                    return result;
                }
                return def;
            }
            else
            {
                SetBool(key, def);
                return def;
            }
        }

19 View Source File : PortalBusOrganizationServiceCache.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			_name = name;

			if (config != null)
			{
				_connectionStringName = GetConnectionStringName(name, config);

				bool syncRemoveEnabled;

				if (bool.TryParse(config["syncRemoveEnabled"], out syncRemoveEnabled))
				{
					this._syncRemoveEnabled = syncRemoveEnabled;
				}
			}

			base.Initialize(name, config);
		}

19 View Source File : CrmEntityIndexSearcher.cs
License : MIT License
Project Creator : Adoxio

private bool IsAnnotationSearchEnabled()
        {
            var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
            var displayNotesEnabledString = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "KnowledgeManagement/DisplayNotes");

            bool displayNotesEnabled;
            bool.TryParse(displayNotesEnabledString, out displayNotesEnabled);

            return displayNotesEnabled;
        }

19 View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH

public static bool ToBool(this object s)
    {
        if (s == null) 
            return false;

        s = s.ToString().ToLower();
        if (s.Equals(1) || s.Equals("1") || s.Equals("true") || s.Equals("是") || s.Equals("yes"))
            return true;
        if (s.Equals(0) || s.Equals("0") || s.Equals("false") || s.Equals("否") || s.Equals("no"))
            return false;

        Boolean.TryParse(s.ToString(), out bool result);
        return result;
    }

19 View Source File : Order.cs
License : MIT License
Project Creator : Adoxio

public static Order Parse(XElement element)
		{
			if (element == null) return null;

			var attribute = element.Attribute("descending");

			bool descending;

			var direction = attribute != null && bool.TryParse(attribute.Value, out descending)
				? descending ? OrderType.Descending : OrderType.Ascending as OrderType?
				: null;

			return new Order
			{
				Attribute = element.GetAttribute("attribute"),
				Alias = element.GetAttribute("alias"),
				Direction = direction,

				Extensions = element.GetExtensions(),
			};
		}

19 View Source File : ActionCommandManager.cs
License : MIT License
Project Creator : actions

public void ProcessCommand(IExecutionContext context, string line, ActionCommand command, ContainerInfo container)
        {
            var allowUnsecureCommands = false;
            bool.TryParse(Environment.GetEnvironmentVariable(Constants.Variables.Actions.AllowUnsupportedCommands), out allowUnsecureCommands);

            // Apply environment from env context, env context contains job level env and action's env block
#if OS_WINDOWS
            var envContext = context.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = context.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            if (!allowUnsecureCommands && envContext.ContainsKey(Constants.Variables.Actions.AllowUnsupportedCommands))
            {
                bool.TryParse(envContext[Constants.Variables.Actions.AllowUnsupportedCommands].ToString(), out allowUnsecureCommands);
            }

            if (!allowUnsecureCommands)
            {
                throw new Exception(String.Format(Constants.Runner.UnsupportedCommandMessageDisabled, this.Command));
            }

            if (!command.Properties.TryGetValue(SetEnvCommandProperties.Name, out string envName) || string.IsNullOrEmpty(envName))
            {
                throw new Exception("Required field 'name' is missing in ##[set-env] command.");
            }


            foreach (var blocked in _setEnvBlockList)
            {
                if (string.Equals(blocked, envName, StringComparison.OrdinalIgnoreCase))
                {
                    // Log Telemetry and let user know they shouldn't do this
                    var issue = new Issue()
                    {
                        Type = IssueType.Error,
                        Message = $"Can't update {blocked} environment variable using ::set-env:: command."
                    };
                    issue.Data[Constants.Runner.InternalTelemetryIssueDataKey] = $"{Constants.Runner.UnsupportedCommand}_{envName}";
                    context.AddIssue(issue);

                    return;
                }
            }

            context.Global.EnvironmentVariables[envName] = command.Data;
            context.SetEnvContext(envName, command.Data);
            context.Debug($"{envName}='{command.Data}'");
        }

19 View Source File : Order.cs
License : MIT License
Project Creator : Adoxio

public static Order Parse(JToken element, IEnumerable<XAttribute> xmlns = null)
		{
			if (element == null) return null;

			var namespaces = element.ToNamespaces(xmlns);
			var attribute = element["descending"];

			bool descending;

			var direction = attribute != null && bool.TryParse(attribute.Value<string>(), out descending)
				? descending ? OrderType.Descending : OrderType.Ascending as OrderType?
				: null;

			return new Order
			{
				Attribute = element.GetAttribute("attribute"),
				Alias = element.GetAttribute("alias"),
				Direction = direction,

				Extensions = element.GetExtensions(namespaces),
			};
		}

19 View Source File : OpenCommand.cs
License : MIT License
Project Creator : Adoxio

private static CommandResponse GetResponse(ICommandContext commandContext, IFileSystemContext fileSystemContext, OpenCommandResponse response, bool forceTree = false)
		{
			response.cwd = fileSystemContext.Current.Info;
			response.cdc = fileSystemContext.Current.Children;

			bool treeRequested;

			if (forceTree || (bool.TryParse(commandContext.Parameters["tree"] ?? string.Empty, out treeRequested) && treeRequested))
			{
				response.tree = fileSystemContext.Tree;
			}

			return response;
		}

19 View Source File : ActionCommandManager.cs
License : MIT License
Project Creator : actions

public void ProcessCommand(IExecutionContext context, string line, ActionCommand command, ContainerInfo container)
        {
            var allowUnsecureCommands = false;
            bool.TryParse(Environment.GetEnvironmentVariable(Constants.Variables.Actions.AllowUnsupportedCommands), out allowUnsecureCommands);

            // Apply environment from env context, env context contains job level env and action's env block
#if OS_WINDOWS
            var envContext = context.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = context.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            if (!allowUnsecureCommands && envContext.ContainsKey(Constants.Variables.Actions.AllowUnsupportedCommands))
            {
                bool.TryParse(envContext[Constants.Variables.Actions.AllowUnsupportedCommands].ToString(), out allowUnsecureCommands);
            }

            if (!allowUnsecureCommands)
            {
                throw new Exception(String.Format(Constants.Runner.UnsupportedCommandMessageDisabled, this.Command));
            }

            ArgUtil.NotNullOrEmpty(command.Data, "path");
            context.Global.PrependPath.RemoveAll(x => string.Equals(x, command.Data, StringComparison.CurrentCulture));
            context.Global.PrependPath.Add(command.Data);
        }

19 View Source File : Rating.cs
License : MIT License
Project Creator : Adoxio

public override void Render(Context context, TextWriter result)
		{
			IPortalLiquidContext portalLiquidContext;

			if (!context.TryGetPortalLiquidContext(out portalLiquidContext))
			{
				return;
			}

			string id;
			Guid parsedId;

			if (!this.TryGetAttributeValue(context, "id", out id) || !Guid.TryParse(id, out parsedId))
			{
				throw new SyntaxException("Syntax Error in 'rating' tag. Missing required attribute 'id:[string]'");
			}

			string enreplacedy;

			if (!this.TryGetAttributeValue(context, "enreplacedy", out enreplacedy) || string.IsNullOrWhiteSpace(enreplacedy))
			{
				enreplacedy = "adx_webpage";
			}

			string readonlyString;
			var parsedReadonly = false;

			if (this.TryGetAttributeValue(context, "readonly", out readonlyString))
			{
				bool.TryParse(readonlyString, out parsedReadonly);
			}

			string panel;
			var parsedPanel = false;

			if (this.TryGetAttributeValue(context, "panel", out panel))
			{
				bool.TryParse(panel, out parsedPanel);
			}

			string panelSnippet;

			this.TryGetAttributeValue(context, "snippet", out panelSnippet);

			string step;

			this.TryGetAttributeValue(context, "step", out step);

			string min;

			this.TryGetAttributeValue(context, "min", out min);

			string max;

			this.TryGetAttributeValue(context, "max", out max);

			string round;
			var parsedRound = true;

			if (this.TryGetAttributeValue(context, "round", out round))
			{
				bool.TryParse(round, out parsedRound);
			}

			var enreplacedyReference = new EnreplacedyReference(enreplacedy, parsedId);

			var html = portalLiquidContext.Html.Rating(enreplacedyReference, panel: parsedPanel, panelreplacedleSnippetName: panelSnippet, isReadonly: parsedReadonly, step: step, min: min, max: max, roundNearestHalf: parsedRound);

			result.Write(html);
		}

19 View Source File : NegatableBooleanToVisibilityConverter.cs
License : Microsoft Public License
Project Creator : achimismaili

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool bVal;
            bool result = bool.TryParse(value.ToString(), out bVal);
            if (!result) return value;
            if (bVal && !Negate) return Visibility.Visible;
            if (bVal && Negate) return FalseVisibility;
            if (!bVal && Negate) return Visibility.Visible;
            if (!bVal && !Negate) return FalseVisibility;
            else return Visibility.Visible;
        }

19 View Source File : CrmProfileProvider.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (_initialized) return;

			if (config == null) throw new ArgumentNullException("config");

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().FullName;
			}

			if (string.IsNullOrEmpty(config["description"]))
			{
				config["description"] = "Adxstudio CRM Profile Provider";
			}

			base.Initialize(name, config);

			replacedertRequiredCustomAttributes(config);

			ApplicationName = config["applicationName"] ?? "/";

			_attributeMapStateCode = config["attributeMapStateCode"];

			_attributeMapIsDisabled = config["attributeMapIsDisabled"];

			_attributeMapIsAnonymous = config["attributeMapIsAnonymous"];

			_attributeMapLastActivityDate = config["attributeMapLastActivityDate"];

			_attributeMapLastUpdatedDate = config["attributeMapLastUpdatedDate"];

			_attributeMapUsername = config["attributeMapUsername"];

			ContextName = config["contextName"];

			var enableActivityTrackingConfig = config["enableActivityTracking"];
			bool enableActivityTrackingValue;

			// Profile activity tracking is disabled by default, for performance reasons. Updating the profile
			// activity timestamp on each request generally adds over 100ms--too much.
			_enableActivityTracking = bool.TryParse(enableActivityTrackingConfig, out enableActivityTrackingValue)
				? enableActivityTrackingValue
				: false;

			_profileEnreplacedyName = config["profileEnreplacedyName"];

			var recognizedAttributes = new List<string>
			{
				"name",
				"applicationName",
				"attributeMapStateCode",
				"attributeMapIsDisabled",
				"attributeMapIsAnonymous",
				"attributeMapLastActivityDate",
				"attributeMapLastUpdatedDate",
				"attributeMapUsername",
				"crmDataContextName",
				"enableActivityTracking",
				"profileEnreplacedyName"
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ConfigurationErrorsException("The {0} doesn't recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}

			_initialized = true;
		}

19 View Source File : CrmWebsite.cs
License : MIT License
Project Creator : Adoxio

protected virtual T GetValue<T>(string value)
		{
			var type = typeof(T);

			if (type.IsA(typeof(string)))
			{
				return (T)(object)value;
			}

			if (type.IsA(typeof(bool)) || type.IsA(typeof(bool?)))
			{
				bool result;

				if (bool.TryParse(value, out result))
				{
					return (T)(object)result;
				}
			}

			if (type.IsA(typeof(int)) || type.IsA(typeof(int?)))
			{
				int result;

				if (int.TryParse(value, out result))
				{
					return (T)(object)result;
				}
			}

			if (type.IsA(typeof(TimeSpan)) || type.IsA(typeof(TimeSpan?)))
			{
				TimeSpan result;

				if (TimeSpan.TryParse(value, out result))
				{
					return (T)(object)result;
				}
			}

			if (type.IsA(typeof(PathString)) || type.IsA(typeof(PathString?)))
			{
				return (T)(object)new PathString(value);
			}

			return default(T);
		}

19 View Source File : PreviewPermission.cs
License : MIT License
Project Creator : Adoxio

private bool TryGetCookieValue(out bool cookieValue)
		{
			cookieValue = false;

			var cookie = Cookie;

			return cookie != null && bool.TryParse(cookie.Value, out cookieValue);
		}

19 View Source File : HeifEncoder.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054

private static bool TryConvertStringToBoolean(string value, out bool result)
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                if (bool.TryParse(value, out result))
                {
                    return true;
                }
                else if (value.Equals("1", StringComparison.Ordinal))
                {
                    result = true;
                    return true;
                }
                else if (value.Equals("0", StringComparison.Ordinal))
                {
                    result = false;
                    return true;
                }
            }

            result = false;
            return false;
        }

19 View Source File : XNodeExtensions.cs
License : MIT License
Project Creator : Adoxio

public static bool TryGetBooleanAttributeValue(this XNode startingNode, string elementXPath, string attributeName, out bool attributeValue)
		{
			attributeValue = false;

			string textValue;

			return TryGetAttributeValue(startingNode, elementXPath, attributeName, out textValue) && bool.TryParse(textValue, out attributeValue);
		}

19 View Source File : CmsCrmEntitySecurityProvider.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			base.Initialize(name, config);

			var portalName = config["portalName"];

			var contentMapProvider = AdxstudioCrmConfigurationManager.CreateContentMapProvider(portalName);

			_underlyingProvider = contentMapProvider != null
				? new ContentMapUncachedProvider(contentMapProvider)
				: new UncachedProvider(portalName);

			var cacheInfoFactory = new CrmEnreplacedySecurityCacheInfoFactory(GetType().FullName);

			bool cachingEnabled;
			if (!bool.TryParse(config["cachingEnabled"], out cachingEnabled)) { cachingEnabled = true; }

			if (cachingEnabled)
			{
				_underlyingProvider = new ApplicationCachingCrmEnreplacedySecurityProvider(_underlyingProvider, cacheInfoFactory);
			}

			bool requestCachingEnabled;
			if (!bool.TryParse(config["requestCachingEnabled"], out requestCachingEnabled)) { requestCachingEnabled = true; }

			if (requestCachingEnabled && HttpContext.Current != null)
			{
				_underlyingProvider = new RequestCachingCrmEnreplacedySecurityProvider(_underlyingProvider, cacheInfoFactory);
			}
		}

19 View Source File : TableLayoutSectionTemplate.cs
License : MIT License
Project Creator : Adoxio

public override void InstantiateIn(Control container)
		{
			var wrapper = new HtmlGenericControl("fieldset");
			container.Controls.Add(wrapper);

			var sectionTable = new HtmlGenericControl("table");
			
			sectionTable.Attributes.Add("role", "presentation");

			string sectionName;
			var sectionLabel = string.Empty;
			var sectionCssClreplacedName = string.Empty;
			string visibleProperty;
			var visible = true;

			Node.TryGetAttributeValue(".", "visible", out visibleProperty);

			if (!string.IsNullOrWhiteSpace(visibleProperty))
			{
				bool.TryParse(visibleProperty, out visible);
			}

			if (!visible)
			{
				return;
			}

			if (Node.TryGetAttributeValue(".", "name", out sectionName))
			{
				sectionTable.Attributes.Add("data-name", sectionName);

				if (_webformMetadata != null)
				{
					var sectionWebFormMetadata = _webformMetadata.FirstOrDefault(wfm => wfm.GetAttributeValue<string>("adx_sectionname") == sectionName);

					if (sectionWebFormMetadata != null)
					{
						var label = sectionWebFormMetadata.GetAttributeValue<string>("adx_label");

						if (!string.IsNullOrWhiteSpace(label))
						{
							sectionLabel = Localization.GetLocalizedString(label, LanguageCode);
						}

						sectionCssClreplacedName = sectionWebFormMetadata.GetAttributeValue<string>("adx_cssclreplaced") ?? string.Empty;
					}
				}
			}

			sectionTable.Attributes.Add("clreplaced", !string.IsNullOrWhiteSpace(sectionCssClreplacedName) ? string.Join(" ", "section", sectionCssClreplacedName) : "section");

			if (ShowLabel)
			{
				var caption = new HtmlGenericControl("legend") { InnerHtml = string.IsNullOrWhiteSpace(sectionLabel) ? Label : sectionLabel };

				var cssClreplaced = "section-replacedle";
				if (ShowBar)
				{
					cssClreplaced += " show-bar";
				}

				caption.Attributes.Add("clreplaced", cssClreplaced);

				wrapper.Controls.Add(caption);
			}

			var colgroup = new HtmlGenericControl("colgroup");
			sectionTable.Controls.Add(colgroup);

			if (PortalSettings.Instance.BingMapsSupported && !string.IsNullOrWhiteSpace(sectionName) && sectionName.EndsWith("section_map"))
			{
				var bingmap = new BingMap { ClientIDMode = ClientIDMode.Static, MappingFieldCollection = MappingFieldCollection };

				sectionTable.Controls.Add(bingmap);
			}
			
			string columns;

			if (Node.TryGetAttributeValue(".", "columns", out columns))
			{
				// For every column there is a "1" in the columns attribute... 1=1, 11=2, 111=3, etc.)
				foreach (var column in columns)
				{
					var width = 1 / (double)columns.Length * 100;
					var col = new SelfClosingHtmlGenericControl("col");
					col.Style.Add(HtmlTextWriterStyle.Width, "{0}%".FormatWith(width));
					colgroup.Controls.Add(col);
				}
				colgroup.Controls.Add(new SelfClosingHtmlGenericControl("col"));
			}

			wrapper.Controls.Add(sectionTable);

			var rowTemplates = Node.XPathSelectElements("rows/row").Select(row => RowTemplateFactory.CreateTemplate(row, EnreplacedyMetadata, CellTemplateFactory));

			foreach (var template in rowTemplates)
			{
				template.InstantiateIn(sectionTable);
			}
		}

19 View Source File : TabularModelSerializer.cs
License : MIT License
Project Creator : action-bi-toolkit

public static JObject ConvertMeasureXml(XDoreplacedent xml)
        {
            if (xml == null) return default(JObject);

            var measure = new JObject {
                { "name", xml.Root.Attribute("Name")?.Value }
            };

            string ToCamelCase(string s)
            {
                var sb = new StringBuilder(s);
                if (sb.Length > 0) sb[0] = Char.ToLower(s[0]);
                return sb.ToString();
            };

            foreach (var element in xml.Root.Elements())
            {
                if (element.Name == "Annotation")
                {
                    var sb = new StringBuilder();

                    using (var writer = XmlWriter.Create(new StringWriter(sb), new XmlWriterSettings { Indent = false, OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment }))
                    {
                        element.FirstNode.WriteTo(writer);
                    }

                    var annotation = new JObject {
                        { "name", element.Attribute("Name")?.Value },
                        { "value", sb.ToString() }
                    };

                    JArray GetOrInsertAnnotations()
                    {
                        if (measure["annotations"] is JArray array)
                            return array;
                        var newArray = new JArray();
                        measure.Add("annotations", newArray);
                        return newArray;
                    };

                    GetOrInsertAnnotations().Add(annotation);
                }
                else if (element.Name == "Expression")
                {
                    var expressionsArray = element.Value.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
                    var token = expressionsArray.Length == 1 ? (JToken)expressionsArray[0] : new JArray(expressionsArray);
                    measure.Add("expression", token);
                }
                else if (element.Name == "IsHidden" && Boolean.TryParse(element.Value, out var boolValue))
                {
                    measure.Add(ToCamelCase(element.Name.LocalName), boolValue);
                }
                //		else if (Int64.TryParse(element.Value, out var intValue))
                //		{
                //			measure.Add(ToCamelCase(element.Name.LocalName), intValue);
                //		}
                //		else if (Double.TryParse(element.Value, out var doubleValue))
                //		{
                //			measure.Add(ToCamelCase(element.Name.LocalName), doubleValue);
                //		}
                else
                {
                    measure.Add(ToCamelCase(element.Name.LocalName), element.Value);
                }
            }

            return measure;
        }

19 View Source File : Expression.cs
License : MIT License
Project Creator : Adoxio

private static object ParseValue(string attributeName, string text)
		{
			// try convert from string to value type

			object value;
			DateTime dateTimeValue;
			double doubleValue;
			bool boolValue;
			Guid guidValue;

			if (double.TryParse(
					text,
					NumberStyles.Any,
					CultureInfo.InvariantCulture,
					out doubleValue))
			{
				value = doubleValue;
			}
			else if (DateTime.TryParse(
					text,
					CultureInfo.InvariantCulture,
					DateTimeStyles.replacedumeLocal,
					out dateTimeValue))
			{
				value = dateTimeValue;
			}
			else if (bool.TryParse(
					text,
					out boolValue))
			{
				value = boolValue;
			}
			else if (Guid.TryParse(
					text,
					out guidValue))
			{
				value = guidValue;
			}
			else if (string.Compare(text, "null", StringComparison.InvariantCultureIgnoreCase) == 0)
			{
				value = null;
			}
			else
			{
				value = text;
			}

			return value;
		}

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio

public static bool? ToBoolean(this string text)
		{
			bool result;

			return bool.TryParse(text, out result) ? result : (bool?)null;
		}

19 View Source File : XNodeUtility.cs
License : MIT License
Project Creator : Adoxio

public static bool TryGetBooleanAttributeValue(XNode startingNode, string elementXPath, string attributeName, out bool attributeValue)
		{
			attributeValue = false;

			string textValue;

			return TryGetAttributeValue(startingNode, elementXPath, attributeName, out textValue) && bool.TryParse(textValue, out attributeValue);
		}

19 View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000

public override ExprLiteral FromString(string? value) =>
            value == null
                ? throw new SqExpressException($"Value cannot be null for '{this.ColumnName.Name}' non nullable column")
                : bool.TryParse(value, out var result)
                    ? SqQueryBuilder.Literal(result)
                    : throw new SqExpressException($"Could not parse '{value}' as boolean for column '{this.ColumnName.Name}'.");

19 View Source File : Home.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs args)
		{
			var setting = ServiceContext.CreateQuery("adx_sitesetting").FirstOrDefault(s => s.GetAttributeValue<string>("adx_name") == "twitter_feed_enabled");

			var twitterEnabled = false;

			if (setting != null)
			{
				bool.TryParse(setting.GetAttributeValue<string>("adx_value"), out twitterEnabled);
			}

			TwitterFeedPanel.Visible = twitterEnabled;

			ServiceRequestsListView.DataSource = GetServiceRequests();
			ServiceRequestsListView.DataBind();
		}

19 View Source File : PortalSearchProvider.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}

			bool displayNotes;

			PortalName = config["portalName"];
			NotesFilter = config["notesFilter"];
			ArticlesLanguageCode = config["articlesLanguageCode"];
			DisplayNotes = bool.TryParse(config["displayNotes"], out displayNotes) && displayNotes;

			var recognizedAttributes = new List<string>
			{
				"portalName",
				"notesFilter",
				"displayNotes",
				"articlesLanguageCode"
			};

			recognizedAttributes.ForEach(config.Remove);

			base.Initialize(name, config);
		}

19 View Source File : Variables.cs
License : MIT License
Project Creator : actions

public bool? GetBoolean(string name)
        {
            bool val;
            if (bool.TryParse(Get(name), out val))
            {
                return val;
            }

            return null;
        }

19 View Source File : RCEPControl.cs
License : MIT License
Project Creator : 0x0ade

[RCEndpoint(false, "/chatlog", "?count={count}&detailed={true|false}", "?count=20&detailed=false", "Chat Log", "Basic chat log.")]
        public static void ChatLog(Frontend f, HttpRequestEventArgs c) {
            bool auth = f.IsAuthorized(c);
            NameValueCollection args = f.ParseQueryString(c.Request.RawUrl);

            if (!int.TryParse(args["count"], out int count) || count <= 0)
                count = 20;
            if (!auth && count > 100)
                count = 100;

            if (!bool.TryParse(args["detailed"], out bool detailed))
                detailed = false;

            ChatModule chat = f.Server.Get<ChatModule>();
            List<object> log = new();
            RingBuffer<DataChat?> buffer = chat.ChatBuffer;
            lock (buffer) {
                for (int i = Math.Max(-buffer.Moved, -count); i < 0; i++) {
                    DataChat? msg = buffer[i];
                    if (msg != null && (msg.Target == null || auth))
                        log.Add(detailed ? msg.ToDetailedFrontendChat() : msg.ToFrontendChat());
                }
            }

            f.RespondJSON(c, log);
        }

19 View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000

public override ExprLiteral FromString(string? value) =>
            value == null
                ? SqQueryBuilder.Literal((bool?)null)
                : bool.TryParse(value, out var result)
                    ? SqQueryBuilder.Literal(result)
                    : throw new SqExpressException($"Could not parse '{value}' as boolean.");

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<bool> ParseChanceTable_Bool(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<bool>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"\(\s+([^,]+),\s+([\d.]+)");

                if (!match.Success || !bool.TryParse(match.Groups[1].Value, out var val) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((val, chance));
            }

            return chanceTable;
        }

19 View Source File : ActionCommandManager.cs
License : MIT License
Project Creator : actions

public void ProcessCommand(IExecutionContext context, string line, ActionCommand command, ContainerInfo container)
        {
            var allowUnsecureCommands = false;
            bool.TryParse(Environment.GetEnvironmentVariable(Constants.Variables.Actions.AllowUnsupportedCommands), out allowUnsecureCommands);

            // Apply environment from env context, env context contains job level env and action's env block
#if OS_WINDOWS
            var envContext = context.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = context.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            if (!allowUnsecureCommands && envContext.ContainsKey(Constants.Variables.Actions.AllowUnsupportedCommands))
            {
                bool.TryParse(envContext[Constants.Variables.Actions.AllowUnsupportedCommands].ToString(), out allowUnsecureCommands);
            }

            if (!allowUnsecureCommands)
            {
                throw new Exception(String.Format(Constants.Runner.UnsupportedCommandMessageDisabled, this.Command));
            }

            ArgUtil.NotNullOrEmpty(command.Data, "path");
            context.Global.PrependPath.RemoveAll(x => string.Equals(x, command.Data, StringComparison.CurrentCulture));
            context.Global.PrependPath.Add(command.Data);
        }

19 View Source File : CacheFeedHandler.cs
License : MIT License
Project Creator : Adoxio

public void ProcessRequest(HttpContext context)
		{
			var section = AdxstudioCrmConfigurationManager.GetCrmSection();
			var config = section.CacheFeed;

			if (!config.Enabled)
			{
				throw new HttpException("Feed isn't enabled.");
			}

			if (config.LocalOnly && !IsLocal(context.Request))
			{
				throw new HttpException("Feed is local only.");
			}

			// Get the output content type, let the querystring override web.config value. Default value is JSON.
			ContentType outputType = ContentType.Json;
			bool queryStringOverrideContentType = false;
			if (!string.IsNullOrEmpty(context.Request[QueryKeys.ContentType]))
			{
				if (context.Request[QueryKeys.ContentType].ToLower().Contains("xml"))
				{
					queryStringOverrideContentType = true;
					outputType = ContentType.Xml;
				}
				else if (context.Request[QueryKeys.ContentType].ToLower().Contains("json"))
				{
					// Keep output type as JSON
					queryStringOverrideContentType = true;
				}
			}
			if (!queryStringOverrideContentType && !string.IsNullOrEmpty(config.ContentType) && config.ContentType.ToLower().Contains("xml"))
			{
				// web.config override to XML
				outputType = ContentType.Xml;
			}

			switch (outputType)
			{
				case ContentType.Xml:
					context.Response.ContentType = "text/xml";
					break;
				case ContentType.Json:
				default:
					context.Response.ContentType = "text/json";
					break;
			}

			context.Trace.IsEnabled = config.Traced;
			var showValues = config.ShowValues;

			bool showAll;
			bool.TryParse(context.Request["showAll"], out showAll);

			bool expanded;
			bool.TryParse(context.Request[QueryKeys.Expanded], out expanded);

			var regionName = context.Request["regionName"];

			bool cacheFootprint;
			bool.TryParse(context.Request[QueryKeys.CacheFootprint], out cacheFootprint);

			var url = context.Request.Url;
			var alternateLink = new Uri(url.GetLeftPart(UriPartial.Path));

			bool clear;
			var key = context.Request["key"];
			var remove = context.Request["remove"];

			var objectCacheName = context.Request["objectCacheName"] ?? config.ObjectCacheName;

			if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(objectCacheName))
			{
				var cache = GetCache(objectCacheName);

				if (cache != null)
				{
					switch (outputType)
					{
						case ContentType.Xml:
							var feed = cache.GetFeed(key, null, null, alternateLink, alternateLink, showAll, regionName, showValues);
							Render(feed, context.Response.OutputStream, config.Stylesheet);
							break;
						case ContentType.Json:
						default:
							var json = cache.GetJson(key, null, null, alternateLink, alternateLink, showAll, regionName, showValues);
							Render(json, context.Response.OutputStream);
							break;
					}
				}
			}
			else if (!string.IsNullOrWhiteSpace(remove) && !string.IsNullOrWhiteSpace(objectCacheName))
			{
				var cache = GetCache(objectCacheName);

				if (cache != null)
				{
					Remove(cache, remove, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet);
				}
			}
			else if (bool.TryParse(context.Request["clear"], out clear))
			{
				if (string.IsNullOrWhiteSpace(objectCacheName))
				{
					var caches = GetCaches(objectCacheName);
					foreach (var cache in caches) Clear(cache, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet);
				}
				else
				{
					var cache = GetCache(objectCacheName);

					if (cache != null)
					{
						Clear(cache, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet);
					}
				}
			}
			else if (cacheFootprint)
			{
				var caches = GetCaches(objectCacheName);
				RenderCacheFootprint(caches, context, outputType, expanded);
			}
			else
			{
				var caches = GetCaches(objectCacheName);
				RenderList(caches, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet);
			}
		}

See More Examples