System.Collections.Generic.IEnumerable.Any(System.Func)

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

12647 Examples 7

19 Source : SqliteSyncConfigurationBuilder.cs
with MIT License
from adospace

public SqliteSyncConfigurationBuilder Table<T>(
            string name = null, 
            SyncDirection syncDirection = SyncDirection.UploadAndDownload, 
            bool skipInitialSnapshot = false, 
            string selectIncrementalQuery = null,
            string customSnapshotQuery = null)
        {
            if (name == null)
            {
                var tableAttribute = (TableAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TableAttribute));
                if (tableAttribute != null)
                    name = tableAttribute.Name;
            }

            if (name == null)
            {
                name = typeof(T).Name;
            }

            if (_tables.Any(_ => string.CompareOrdinal(_.Name, name) == 0))
                throw new InvalidOperationException($"Table with name '{name}' already added");

            return Table(name, typeof(T), syncDirection, skipInitialSnapshot, selectIncrementalQuery, customSnapshotQuery);
        }

19 Source : VisualNode.cs
with MIT License
from adospace

protected virtual void CommitAnimations()
        {
            if (_animatables.Any(_ => _.Value.IsEnabled.GetValueOrDefault() && !_.Value.Animation.IsCompleted()))
            {
                RequestAnimationFrame();
            }
        }

19 Source : Validate.cs
with MIT License
from adospace

public static void Any(bool[] arrayOfValidations, [NotNull] string parameterName, [CanBeNull] string field = null)
        {
            if (!arrayOfValidations.Any(_ => _)) throw new ArgumentException("Parameter is not valid", parameterName + (field == null ? string.Empty : "." + field));
        }

19 Source : SqlSyncTable.cs
with MIT License
from adospace

internal void SetupCommand(SqlCommand cmd, ChangeType itemChangeType, Dictionary<string, SyncItemValue> syncItemValues)
        {
            var allColumnsExceptSkipColumns = Columns.Keys.Except(SkipColumns).ToArray();

            //take values only for existing columns (server table schema could be not in sync with local table schema)
            var allSyncItems = syncItemValues
                .Where(value => allColumnsExceptSkipColumns.Any(_ => StringComparer.OrdinalIgnoreCase.Compare(_, value.Key) == 0))
                .ToList();

            var allSyncItemsExceptPrimaryKey = allSyncItems.Where(_ => !PrimaryKeyColumns.Any(kc => kc == _.Key)).ToArray();

            switch (itemChangeType)
            {
                case ChangeType.Insert:
                    {
                        cmd.CommandText = $@"{(HasTableIdenreplacedyColumn ? $"SET IDENreplacedY_INSERT {NameWithSchema} ON" : string.Empty)}
BEGIN TRY 
INSERT INTO {NameWithSchema} ({string.Join(", ", allSyncItems.Select(_ => "[" + _.Key + "]"))}) 
VALUES ({string.Join(", ", allSyncItems.Select((_, index) => $"@p{index}"))});
END TRY  
BEGIN CATCH  
PRINT ERROR_MESSAGE()
END CATCH
{(HasTableIdenreplacedyColumn ? $"SET IDENreplacedY_INSERT {NameWithSchema} OFF" : string.Empty)}";


                        int pIndex = 0;
                        foreach (var valueItem in allSyncItems)
                        {
                            cmd.Parameters.Add(new SqlParameter($"@p{pIndex}", Columns[valueItem.Key].DbType)
                            {
                                Value = Utils.ConvertToSqlType(valueItem.Value, Columns[valueItem.Key].DbType)
                            });
                            //cmd.Parameters.AddWithValue("@" + valueItem.Key.Replace(" ", "_"), valueItem.Value.Value ?? DBNull.Value);
                            pIndex++;
                        }
                    }
                    break;

                case ChangeType.Update:
                    {
                        cmd.CommandText = $@"BEGIN TRY 
UPDATE {NameWithSchema}
SET {string.Join(", ", allSyncItemsExceptPrimaryKey.Select((_, index) => $"[{_.Key}] = @p{index}"))}
WHERE {NameWithSchema}.[{PrimaryColumnName}] = @PrimaryColumnParameter
AND (@sync_force_write = 1 OR (SELECT MAX(ID) FROM __CORE_SYNC_CT WHERE PK_{PrimaryColumnType} = @PrimaryColumnParameter AND TBL = '{NameWithSchema}') <= @last_sync_version)
END TRY  
BEGIN CATCH  
PRINT ERROR_MESSAGE()
END CATCH";
                        cmd.Parameters.Add(new SqlParameter("@PrimaryColumnParameter", Columns[PrimaryColumnName].DbType)
                        {
                            Value = Utils.ConvertToSqlType(syncItemValues[PrimaryColumnName], Columns[PrimaryColumnName].DbType)
                        });

                        int pIndex = 0;
                        foreach (var valueItem in allSyncItemsExceptPrimaryKey)
                        {
                            cmd.Parameters.Add(new SqlParameter($"@p{pIndex}", Columns[valueItem.Key].DbType)
                            {
                                Value = Utils.ConvertToSqlType(valueItem.Value, Columns[valueItem.Key].DbType)
                            });
                            //cmd.Parameters.AddWithValue("@" + valueItem.Key.Replace(" ", "_"), valueItem.Value.Value ?? DBNull.Value);
                            pIndex++;
                        }

                    }
                    break;

                case ChangeType.Delete:
                    {
                        cmd.CommandText = $@"BEGIN TRY 
DELETE FROM {NameWithSchema}
WHERE {NameWithSchema}.[{PrimaryColumnName}] = @PrimaryColumnParameter
AND (@sync_force_write = 1 OR (SELECT MAX(ID) FROM __CORE_SYNC_CT WHERE PK_{PrimaryColumnType} = @PrimaryColumnParameter AND TBL = '{NameWithSchema}') <= @last_sync_version)
END TRY  
BEGIN CATCH  
PRINT ERROR_MESSAGE()
END CATCH";

                        cmd.Parameters.Add(new SqlParameter("@PrimaryColumnParameter", Columns[PrimaryColumnName].DbType)
                        {
                            Value = Utils.ConvertToSqlType(syncItemValues[PrimaryColumnName], Columns[PrimaryColumnName].DbType)
                        });

                    }
                    break;
            }


        }

19 Source : Validate.cs
with MIT License
from adospace

public static void NotNullOrEmptyArray<T>([CanBeNull] T[] values, [NotNull] string parameterName, [CanBeNull] string field = null)
        {
            if (values == null) throw new ArgumentNullException(parameterName + (field == null ? string.Empty : "." + field));
            if (values.Length == 0) throw new ArgumentException($"Parameter can't be an empty array", parameterName + (field == null ? string.Empty : "." + field));
            if (values.Any(_ => _ == null)) throw new ArgumentException($"Parameter cannot contain Null values", parameterName + (field == null ? string.Empty : "." + field));
        }

19 Source : SqliteSyncTable.cs
with MIT License
from adospace

internal void SetupCommand(SqliteCommand cmd, ChangeType itemChangeType, Dictionary<string, SyncItemValue> syncItemValues)
        {
            //take values only for existing columns (server table schema could be not in sync with local table schema)
            var valuesForValidColumns = syncItemValues
                .Where(value => Columns.Any(_ => StringComparer.OrdinalIgnoreCase.Compare(_.Key, value.Key) == 0))
                .ToList();

            switch (itemChangeType)
            {
                case ChangeType.Insert:
                    {
                        cmd.CommandText = $@"INSERT OR IGNORE INTO [{Name}] ({string.Join(", ", valuesForValidColumns.Select(_ => "[" + _.Key + "]"))}) 
VALUES ({string.Join(", ", valuesForValidColumns.Select((_, index) => $"@p{index}"))});";

                        int pIndex = 0;
                        foreach (var valueItem in valuesForValidColumns)
                        {
                            cmd.Parameters.Add(new SqliteParameter($"@p{pIndex}", valueItem.Value.Value ?? DBNull.Value));
                            pIndex++;
                        }
                    }
                    break;

                case ChangeType.Update:
                    {
                        cmd.CommandText = $@"UPDATE [{Name}]
SET {string.Join(", ", valuesForValidColumns.Select((_, index) => $"[{_.Key}] = @p{index}"))}
WHERE [{Name}].[{PrimaryColumnName}] = @PrimaryColumnParameter
AND (@sync_force_write = 1 OR (SELECT MAX(ID) FROM __CORE_SYNC_CT WHERE PK_{PrimaryColumnType} = @PrimaryColumnParameter AND TBL = '{Name}') <= @last_sync_version)";

                        cmd.Parameters.Add(new SqliteParameter("@PrimaryColumnParameter", syncItemValues[PrimaryColumnName].Value ?? DBNull.Value));

                        int pIndex = 0;
                        foreach (var valueItem in valuesForValidColumns)
                        {
                            cmd.Parameters.Add(new SqliteParameter($"@p{pIndex}", valueItem.Value.Value ?? DBNull.Value));
                            pIndex++;
                        }
                    }
                    break;

                case ChangeType.Delete:
                    {
                        cmd.CommandText = $@"DELETE FROM [{Name}]
WHERE [{Name}].[{PrimaryColumnName}] = @PrimaryColumnParameter
AND (@sync_force_write = 1 OR (SELECT MAX(ID) FROM __CORE_SYNC_CT WHERE PK_{PrimaryColumnType} = @PrimaryColumnParameter AND TBL = '{Name}') <= @last_sync_version)";

                        cmd.Parameters.Add(new SqliteParameter("@PrimaryColumnParameter", syncItemValues[PrimaryColumnName].Value ?? DBNull.Value));
                    }
                    break;
            }
        }

19 Source : SqlSyncConfigurationBuilder.cs
with MIT License
from adospace

public SqlSyncConfigurationBuilder Table(
            [NotNull] string name, 
            SyncDirection syncDirection = SyncDirection.UploadAndDownload, 
            string schema = null, 
            bool skipInitialSnapshot = false,
            string selectIncrementalQuery = null,
            string customSnapshotQuery = null)
        {
            Validate.NotNullOrEmptyOrWhiteSpace(name, nameof(name));

            name = name.Trim();

            var nameWithSchema = $"{(schema == null ? string.Empty : "[" + schema + "].")}[{name}]";

            if (_tables.Any(_ => string.CompareOrdinal(_.NameWithSchema, nameWithSchema) == 0))
                throw new InvalidOperationException($"Table with name '{nameWithSchema}' already added");

            _tables.Add(new SqlSyncTable(name, syncDirection, schema ?? _schema, skipInitialSnapshot, selectIncrementalQuery, customSnapshotQuery));
            return this;
        }

19 Source : SqlSyncConfigurationBuilder.cs
with MIT License
from adospace

public SqlSyncConfigurationBuilder Table<T>(
            SyncDirection syncDirection = SyncDirection.UploadAndDownload, 
            string schema = null, 
            bool skipInitialSnapshot = false,
            string selectIncrementalQuery = null,
            string customSnapshotQuery = null)
        {
            var name = typeof(T).Name;
            var tableAttribute = (TableAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TableAttribute));
            if (tableAttribute != null)
            {
                name = tableAttribute.Name;
                schema = tableAttribute.Schema;
            }

            var nameWithSchema = $"{(schema == null ? string.Empty : "[" + schema + "].")}[{name}]";

            if (_tables.Any(_ => string.CompareOrdinal(_.NameWithSchema, nameWithSchema) == 0))
                throw new InvalidOperationException($"Table with name '{nameWithSchema}' already added");

            return Table(name, syncDirection, schema ?? _schema, skipInitialSnapshot, selectIncrementalQuery, customSnapshotQuery);
        }

19 Source : ApplicationRestartPortalBusMessage.cs
with MIT License
from Adoxio

public virtual bool Validate(PluginMessage message)
		{
			IEnumerable<string> patterns;

			if (message.Target == null
				|| string.IsNullOrWhiteSpace(message.Target.LogicalName)
				|| !_enreplacediesToRestart.TryGetValue(message.Target.LogicalName, out patterns))
			{
				return false;
			}

			return patterns.Contains(".*")
				|| (!string.IsNullOrWhiteSpace(message.Target.Name)
				&& patterns.Any(pattern => Regex.IsMatch(message.Target.Name, pattern)));
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static void AddTagToWebPageAndSave(this OrganizationServiceContext context, Guid pageId, string tagName)
		{
			if (context.MergeOption == MergeOption.NoTracking)
			{
				throw new ArgumentException("The OrganizationServiceContext.MergeOption cannot be MergeOption.NoTracking.", "context");
			}

			if (string.IsNullOrEmpty(tagName))
			{
				throw new ArgumentException("Can't be null or empty.", "tagName");
			}

			if (pageId == Guid.Empty)
			{
				throw new ArgumentException("Argument must be a non-empty GUID.", "pageId");
			}

			var page = context.CreateQuery("adx_webpage").Single(p => p.GetAttributeValue<Guid>("adx_webpageid") == pageId);

			var tag = context.GetPageTagByName(tagName);

			// If the tag doesn't exist, create it
			if (tag == null)
			{
				tag = new Enreplacedy("adx_pagetag");
				tag["adx_name"] = tagName;

				context.AddObject(tag);
				context.SaveChanges();
				context.ReAttach(page);
				context.ReAttach(tag);
			}

			if (!page.GetRelatedEnreplacedies(context, "adx_pagetag_webpage").Any(t => t.GetAttributeValue<Guid>("adx_pagetagid") == tag.Id))
			{
				context.AddLink(page, new Relationship("adx_pagetag_webpage"), tag);

				context.SaveChanges();
			}
		}

19 Source : WebPageAccessControlSecurityProvider.cs
with MIT License
from Adoxio

public virtual bool Tryreplacedert(WebPageNode page, CrmEnreplacedyRight right, bool useScope)
		{
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on web page '{1}' ({2}).", right, page.Name, page.Id));

			if (!Roles.Enabled)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, "Roles are not enabled for this application. Allowing Read, but not Change.");

				// If roles are not enabled on the site, grant Read, deny Change.
				return right == CrmEnreplacedyRight.Read;
			}

			// Ignore access control rules for service pages like not found or access denied
			if (right == CrmEnreplacedyRight.Read && IsServicePage(page))
			{
				return true;
			}

			// If the chain of pages from the current page up to the root page contains an inactive page, deny the replacedertion
			if (IsInactivePath(page))
			{
				return false;
			}

			var userRoles = this.GetUserRoles();

			// when we use rule scope we're checking permissions for parent page of web file
			//	and we need to check permissions only for one level
			var useInheritance = !useScope || right == CrmEnreplacedyRight.Change;

			// Get all rules applicable to the page and its parent path, grouping equivalent rules. (Rules that
			// target the same web page and confer the same right are equivalent.)
			var ruleGroupings =
				from rule in this.GetRulesApplicableToWebPage(page, useInheritance)
				where rule.WebPage != null && rule.Right != null
				group rule by new { WebPageId = rule.WebPage.Id, Right = ParseRightOption(rule.Right.Value) } into ruleGrouping
				select ruleGrouping;

			// Order the rule groupings so that all GrantChange rules will be evaluated first.
			ruleGroupings = ruleGroupings.OrderByDescending(grouping => grouping.Key.Right, new RightOptionComparer());

			foreach (var ruleGrouping in ruleGroupings)
			{
				// Collect the names of all the roles that apply to this rule grouping
				var ruleGroupingRoles = ruleGrouping.SelectMany(
					rule => rule.WebRoles.Where(role => BelongsToWebsite(page.Website, role))
					.Select(role => role.Name));

				// Determine if the user belongs to any of the roles that apply to this rule grouping
				var userIsInAnyRoleForThisRule = ruleGroupingRoles.Any(role => userRoles.Any(userRole => userRole == role));

				// If the user belongs to one of the roles...
				if (userIsInAnyRoleForThisRule)
				{
					// ...and the rule is GrantChange...
					if (ruleGrouping.Key.Right == RightOption.GrantChange)
					{
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on web page ({0}). Permission granted.", ruleGrouping.Key.WebPageId));

						// ...the user has all rights.
						return true;
					}
				}

				// If the user does not belong to any of the roles, the rule restricts read, and the desired right
				// is read...
				else if (ruleGrouping.Key.Right == RightOption.RestrictRead && right == CrmEnreplacedyRight.Read)
				{
					if (useScope && ruleGrouping.Any(rule => rule.Scope.HasValue && (ScopeOption)rule.Scope.Value == ScopeOption.ExcludeDirectChildWebFiles))
					{
						// Ignore read restriction for web files where scope is ExcludeDirectChildWebFiles
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Ignoring web page ({0}) read restriction due to ExcludeDirectChildWebFiles", ruleGrouping.Key.WebPageId));
					}
					else
					{
						if (page.Parent == null && page.PartialUrl == "/")
						{
							ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("\"Restrict Read\" right on web page({0}) ({1}).", ruleGrouping.Key.WebPageId, page.Name));
						}
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on web page ({0}). Permission denied.", ruleGrouping.Key.WebPageId));

						// ...the user has no right.
						return false;
					}
				}
			}

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and page. Allowing Read, but not Change.");

			// If none of the above rules apply, grant Read by default, and deny Change by default.
			return right == CrmEnreplacedyRight.Read;
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static bool IsOptionSelected(this OrganizationServiceContext context, Enreplacedy option, Enreplacedy registration)
		{
			option.replacedertEnreplacedyName("adx_conferenceoption");
			registration.replacedertEnreplacedyName("adx_conferenceregistration");

			if (registration == null) return false;

			var options = registration.GetRelatedEnreplacedies(context, "adx_conferenceregistration_option");

			return options.Any(co => co.GetAttributeValue<Guid>("adx_conferenceoptionid") == option.GetAttributeValue<Guid>("adx_conferenceoptionid"));
		}

19 Source : TelemetryState.cs
with MIT License
from Adoxio

public static bool IsTelemetryEnabledUserAgent()
		{
			// invalid validation if the useragent is null
			string userAgent;
			if (!TelemetryState.HasRequestContext || (userAgent = HttpContext.Current.Request.UserAgent) == null)
			{
				return false;
			}

			var ignoredAgentsString = ConfigurationManager.AppSettings["IgnoreUserAgent"];
			if (string.IsNullOrWhiteSpace(ignoredAgentsString))
			{

				// don't ignore any
				return true;
			}

			var ignoredList = ignoredAgentsString.Split(',');
			return !ignoredList.Any(userAgent.Contains);
		}

19 Source : TelemetryState.cs
with MIT License
from Adoxio

public static bool IsTelemetryEnabledRequestExtension()
		{
			string requestExtension;
			if (!TelemetryState.HasRequestContext
				|| (requestExtension = HttpContext.Current.Request.CurrentExecutionFilePathExtension) == null)
			{
				return false;
			}

			var allowedString = ConfigurationManager.AppSettings["TelemetryFileTypes"];
			if (allowedString == null)
			{

				// don't ignore any
				return true;
			}

			var allowed = allowedString.Split(',');
			return allowed.Any(requestExtension.Equals);
		}

19 Source : TelemetryState.cs
with MIT License
from Adoxio

private static bool IsPathMatch(string path)
		{
			var ignoredString = ConfigurationManager.AppSettings["IgnorePath"];
			if (ignoredString == null)
			{
				return false;
			}

			var ignoredList = ignoredString.Split(',');
			return ignoredList.Any(path.StartsWith);
		}

19 Source : OutputObjectCache.cs
with MIT License
from Adoxio

private bool AddKey(string key)
		{
			if (_excludeKeys.Any(key.StartsWith))
			{
				return false;
			}

			return HttpSingleton<OutputCacheKeyCollection>.Enabled
				? HttpSingleton<OutputCacheKeyCollection>.GetInstance(OutputObjectCacheName, () => new OutputCacheKeyCollection()).Add(key)
				: false;
		}

19 Source : DiscountCodeValidationResult.cs
with MIT License
from Adoxio

public static DiscountCodeValidationResult ValidateDiscountCode(OrganizationServiceContext context, Guid quoteId, string code)
		{
			var errorCode = DiscountErrorCode.Unknown;
			var isValid = false;
			var discountableQuoteProductIds = new List<Guid>();
			if (string.IsNullOrWhiteSpace(code))
			{
				var result = new DiscountCodeValidationResult
								{
									ErrorCode = DiscountErrorCode.CodeNotSpecified
								};
				return result;
			}

			var quote = context.CreateQuery("quote").FirstOrDefault(q => q.GetAttributeValue<Guid>("quoteid") == quoteId);

			if (quote == null)
			{
				var result = new DiscountCodeValidationResult
								{
									ErrorCode = DiscountErrorCode.QuoteNotFound,
								};
				return result;
			}

			var existingDiscountCodes = quote.GetAttributeValue<string>("adx_discountcodes") ?? string.Empty;

			if (existingDiscountCodes.Contains(code))
			{
				var result = new DiscountCodeValidationResult
								{
									ErrorCode = DiscountErrorCode.AlreadyApplied,
								};
				return result;
			}

			var prefreightAmount = GetDecimalFromMoney(quote, "totalamountlessfreight");

			if (prefreightAmount <= 0)
			{
				var result = new DiscountCodeValidationResult
								{
									ErrorCode = DiscountErrorCode.ZeroAmount,
								};
				return result;
			}

			var discountErrors = new List<DiscountError>();

			var orderScopedDiscounts =
				context.CreateQuery("adx_discount")
					.Where(
						d =>
							d.GetAttributeValue<OptionSetValue>("statecode").Value == 0 &&
							(d.GetAttributeValue<OptionSetValue>("adx_scope") != null &&
							 d.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)DiscountScope.Order) &&
							((d.GetAttributeValue<DateTime?>("adx_startdate") == null ||
							  d.GetAttributeValue<DateTime?>("adx_startdate") <= DateTime.UtcNow) &&
							 (d.GetAttributeValue<DateTime?>("adx_enddate") == null ||
							  d.GetAttributeValue<DateTime?>("adx_enddate") >= DateTime.UtcNow)) &&
							d.GetAttributeValue<string>("adx_code") == code)
					.ToList();

			if (orderScopedDiscounts.Any())
			{
				var discountPercentage = quote.GetAttributeValue<decimal?>("discountpercentage") ?? 0;
				var discountAmount = GetDecimalFromMoney(quote, "discountamount");
				var newDiscountPercentage = discountPercentage;
				var newDiscountAmount = discountAmount;
				var appliedDiscounts = (from d in context.CreateQuery("adx_discount")
										join dq in context.CreateQuery("adx_discount_quote") on
											d.GetAttributeValue<Guid>("adx_discountid") equals dq.GetAttributeValue<Guid>("adx_discountid")
										where dq.GetAttributeValue<Guid>("quoteid") == quote.Id
										select d).ToList();
				var newDiscounts = new List<Enreplacedy>();

				foreach (var discount in orderScopedDiscounts)
				{
					var applied = appliedDiscounts.Any(d => d.GetAttributeValue<Guid>("adx_discountid") == discount.Id);

					if (applied)
					{
						discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.AlreadyApplied });
						continue;
					}

					var minimumPurchaseAmount = GetDecimalFromMoney(discount, "adx_minimumpurchaseamount");
					var maximumRedemptions = discount.GetAttributeValue<int?>("adx_maximumredemptions").GetValueOrDefault(0);
					var redemptions = discount.GetAttributeValue<int?>("adx_redemptions").GetValueOrDefault(0);
					var typeOption = discount.GetAttributeValue<OptionSetValue>("adx_type");
					decimal percentage = 0;
					decimal amount = 0;

					if (typeOption == null)
					{
						discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
						continue;
					}

					switch (typeOption.Value)
					{
						case (int)DiscountType.Percentage:
							percentage = discount.GetAttributeValue<decimal?>("adx_percentage") ?? 0;
							break;
						case (int)DiscountType.Amount:
							amount = GetDecimalFromMoney(discount, "adx_amount");
							break;
						default:
							discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
							continue;
					}

					if (minimumPurchaseAmount > 0 && prefreightAmount < minimumPurchaseAmount)
					{
						discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MinimumAmountNotMet });
					}
					else if (maximumRedemptions > 0 && redemptions >= maximumRedemptions)
					{
						discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MaximumRedemptions });
					}
					else
					{
						newDiscountPercentage += percentage;
						newDiscountAmount += amount;
						appliedDiscounts.Add(discount);
						newDiscounts.Add(discount);
					}
				}

				if (newDiscountPercentage != discountPercentage || newDiscountAmount != discountAmount)
				{
					isValid = true;
				}
			}

			if (!isValid)
			{
				// Check for valid quotedetail items

				var quoteDetails =
					context.CreateQuery("quotedetail")
							.Where(q => q.GetAttributeValue<EnreplacedyReference>("quoteid").Equals(quote.ToEnreplacedyReference()))
							.ToList();

				if (quoteDetails.Any())
				{
					var priceList = quote.GetAttributeValue<EnreplacedyReference>("pricelevelid");

					var productScopeDiscounts =
						context.CreateQuery("adx_discount")
							.Where(
								d =>
									d.GetAttributeValue<OptionSetValue>("statecode").Value == 0 &&
									(d.GetAttributeValue<OptionSetValue>("adx_scope") != null &&
									 d.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)DiscountScope.Product) &&
									((d.GetAttributeValue<DateTime?>("adx_startdate") == null ||
									  d.GetAttributeValue<DateTime?>("adx_startdate") <= DateTime.UtcNow) &&
									 (d.GetAttributeValue<DateTime?>("adx_enddate") == null ||
									  d.GetAttributeValue<DateTime?>("adx_enddate") >= DateTime.UtcNow)) &&
									d.GetAttributeValue<string>("adx_code") == code)
							.ToList();

					if (!productScopeDiscounts.Any())
					{
						var result = new DiscountCodeValidationResult
										{
											ErrorCode = DiscountErrorCode.DoesNotExist,
											DiscountErrors = discountErrors
										};
						return result;
					}

					foreach (var quotedetail in quoteDetails)
					{
						var baseAmount = GetDecimalFromMoney(quotedetail, "baseamount");

						if (baseAmount <= 0)
						{
							discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.ZeroAmount });
							continue;
						}

						var appliedDiscounts = (from d in context.CreateQuery("adx_discount")
												join i in context.CreateQuery("adx_discount_quotedetail") on
													d.GetAttributeValue<Guid>("adx_discountid") equals i.GetAttributeValue<Guid>("adx_discountid")
												where i.GetAttributeValue<Guid>("quotedetailid") == quotedetail.Id
												select d).ToList();
						var newDiscounts = new List<Enreplacedy>();
						var discountAmount = GetDecimalFromMoney(quotedetail, "manualdiscountamount");
						var newDiscountAmount = discountAmount;

						foreach (var discount in productScopeDiscounts)
						{
							var applied = appliedDiscounts.Any(d => d.GetAttributeValue<Guid>("adx_discountid") == discount.Id);

							if (applied)
							{
								discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.AlreadyApplied });
								continue;
							}

							var discountProductPriceLevel = (from pl in context.CreateQuery("productpricelevel")
															join dp in context.CreateQuery("adx_discount_productpricelevel") on
																pl.GetAttributeValue<Guid>("productpricelevelid") equals dp.GetAttributeValue<Guid>("productpricelevelid")
															where dp.GetAttributeValue<Guid>("adx_discountid") == discount.Id
															where pl.GetAttributeValue<EnreplacedyReference>("pricelevelid").Equals(priceList)
															select pl).ToList();

							if (!discountProductPriceLevel.Any())
							{
								continue;
							}

							var quotedetailid = quotedetail.Id;
							var quoteProductDiscounts = (from d in discountProductPriceLevel
														join q in
															context.CreateQuery("quotedetail")
																	.Where(q => q.GetAttributeValue<Guid>("quotedetailid") == quotedetailid)
															on
															new
																{
																	productid = d.GetAttributeValue<EnreplacedyReference>("productid"),
																	uomid = d.GetAttributeValue<EnreplacedyReference>("uomid")
																} equals
															new
																{
																	productid = q.GetAttributeValue<EnreplacedyReference>("productid"),
																	uomid = q.GetAttributeValue<EnreplacedyReference>("uomid")
																}
														select q).ToList();

							if (!quoteProductDiscounts.Any())
							{
								continue;
							}

							var maximumRedemptions = discount.GetAttributeValue<int?>("adx_maximumredemptions").GetValueOrDefault(0);
							var redemptions = discount.GetAttributeValue<int?>("adx_redemptions").GetValueOrDefault(0);
							var typeOption = discount.GetAttributeValue<OptionSetValue>("adx_type");
							decimal amount = 0;

							if (typeOption == null)
							{
								discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
								continue;
							}

							switch (typeOption.Value)
							{
								case (int)DiscountType.Percentage:
									var percentage = discount.GetAttributeValue<decimal?>("adx_percentage") ?? 0;
									if (percentage > 0 && baseAmount > 0)
									{
										amount = baseAmount * percentage / 100;
									}
									break;
								case (int)DiscountType.Amount:
									amount = GetDecimalFromMoney(discount, "adx_amount");
									break;
								default:
									discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
									continue;
							}

							if (maximumRedemptions > 0 && redemptions >= maximumRedemptions)
							{
								discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MaximumRedemptions });
								continue;
							}

							newDiscountAmount += amount;
							appliedDiscounts.Add(discount);
							newDiscounts.Add(discount);
							discountableQuoteProductIds.Add(quotedetail.Id);
						}

						if (newDiscountAmount == discountAmount)
						{
							continue;
						}

						isValid = true;

						break;
					}
				}
			}

			if (!isValid && !discountErrors.Any())
			{
				discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.NotApplicable });
				errorCode = DiscountErrorCode.NotApplicable;
			}

			return new DiscountCodeValidationResult(isValid)
						{
							ErrorCode = errorCode,
							ExistingDiscountCodes = existingDiscountCodes,
							DiscountableQuoteProductIds = discountableQuoteProductIds.Distinct(),
							DiscountErrors = discountErrors
						};
		}

19 Source : EntityListPackageRepositoryDataAdapter.cs
with MIT License
from Adoxio

public PackageRepository SelectRepository(string category = null, string filter = null, string search = null)
		{
			replacedertEnreplacedyListAccess();

			var serviceContext = Dependencies.GetServiceContext();

			Enreplacedy packageRepository;

			if (!TryGetPackageRepository(serviceContext, PackageRepository, out packageRepository))
			{
                throw new InvalidOperationException("Unable to retrieve the package repository ({0}:{1}).".FormatWith(PackageRepository.LogicalName, PackageRepository.Id));
			}

			Enreplacedy enreplacedyList;

			if (!TryGetEnreplacedyList(serviceContext, EnreplacedyList, out enreplacedyList))
			{
				throw new InvalidOperationException("Unable to retrieve the enreplacedy list ({0}:{1}).".FormatWith(EnreplacedyList.LogicalName, EnreplacedyList.Id));
			}

			Enreplacedy view;

			if (!TryGetView(serviceContext, enreplacedyList, View, out view))
			{
				throw new InvalidOperationException("Unable to retrieve view ({0}:{1}).".FormatWith(View.LogicalName, View.Id));
			}

			var fetchXml = view.GetAttributeValue<string>("fetchxml");

			if (string.IsNullOrEmpty(fetchXml))
			{
				throw new InvalidOperationException("Unable to retrieve the view FetchXML ({0}:{1}).".FormatWith(View.LogicalName, View.Id));
			}

			var fetch = Fetch.Parse(fetchXml);

			var searchableAttributes = fetch.Enreplacedy.Attributes.Select(a => a.Name).ToArray();

			fetch.Enreplacedy.Attributes = FetchAttribute.All;

			var settings = new EnreplacedyListSettings(enreplacedyList);

			AddPackageCategoryJoin(fetch.Enreplacedy);
			AddPackageComponentJoin(fetch.Enreplacedy);
			AddPackageDependencyJoin(fetch.Enreplacedy);
			AddPackageImageJoin(fetch.Enreplacedy);
			AddPackagePublisherJoin(fetch.Enreplacedy);
			AddPackageVersionJoin(fetch.Enreplacedy);

			// Refactor the query to reduce links, but just do an in-memory category filter for now.
			//AddPackageCategoryFilter(fetch.Enreplacedy, category);

			AddSelectableFilterToFetchEnreplacedy(fetch.Enreplacedy, settings, filter);
			AddWebsiteFilterToFetchEnreplacedy(fetch.Enreplacedy, settings);
			AddSearchFilterToFetchEnreplacedy(fetch.Enreplacedy, settings, search, searchableAttributes);

			var enreplacedyGroupings = FetchEnreplacedies(serviceContext, fetch).GroupBy(e => e.Id);

			var packages = GetPackages(enreplacedyGroupings, GetPackageUrl(settings)).ToArray();

			var categoryComparer = new PackageCategoryComparer();

			var repositoryCategories = packages.SelectMany(e => e.Categories).Distinct(categoryComparer).OrderBy(e => e.Name);

			// Do in-memory category filter.
			if (!string.IsNullOrWhiteSpace(category))
			{
				var filterCategory = new PackageCategory(category);

				packages = packages
					.Where(e => e.Categories.Any(c => categoryComparer.Equals(c, filterCategory)))
					.ToArray();
			}

			return new PackageRepository
			{
				replacedle = packageRepository.GetAttributeValue<string>("adx_name"),
				Categories = repositoryCategories,
				Packages = packages,
				Description = packageRepository.GetAttributeValue<string>("adx_description"),
				RequiredInstallerVersion = packageRepository.GetAttributeValue<string>("adx_requiredinstallerversion")
			};
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static void AddTagToEventAndSave(this OrganizationServiceContext context, Guid taggableEventId, string tagName)
		{
			if (context.MergeOption == MergeOption.NoTracking)
			{
				throw new ArgumentException("The OrganizationServiceContext.MergeOption cannot be MergeOption.NoTracking.", "context");
			}

			if (string.IsNullOrEmpty(tagName))
			{
				throw new ArgumentException("Can't be null or empty.", "tagName");
			}

			if (taggableEventId == Guid.Empty)
			{
				throw new ArgumentException("Argument must be a non-empty GUID.", "taggableEventId");
			}

			var taggableEvent = context.CreateQuery("adx_event").Single(e => e.GetAttributeValue<Guid>("adx_eventid") == taggableEventId);

			var tag = GetEventTagByName(context, tagName);

			// If the tag doesn't exist, create it
			if (tag == null)
			{
				tag = new Enreplacedy("adx_eventtag");
				tag["adx_name"] = tagName;

				context.AddObject(tag);
				context.SaveChanges();
				context.ReAttach(taggableEvent);
				context.ReAttach(tag);
			}

			if (!taggableEvent.GetRelatedEnreplacedies(context, "adx_eventtag_event").Any(t => t.GetAttributeValue<Guid>("adx_eventtagid") == tag.Id))
			{
				context.AddLink(taggableEvent, new Relationship("adx_eventtag_event"), tag);

				context.SaveChanges();
			}
		}

19 Source : CrmChangeTrackingManager.cs
with MIT License
from Adoxio

private bool ChangesBelongsToWebsite(IGrouping<Guid, IChangedItem> groupedChanges, CrmDbContext context, Guid websiteId)
		{
			var enreplacedyId = groupedChanges.Key;
			var enreplacedyName = this.GetEnreplacedyNameFromChangedItem(groupedChanges.First());

			if (string.Equals("adx_website", enreplacedyName, StringComparison.OrdinalIgnoreCase))
			{
				return websiteId == enreplacedyId;
			}

			// if enreplacedy hasn't relationship with website or enreplacedy was deleted -> mark as `belongs to website`
			EnreplacedyTrackingInfo info;
			if (groupedChanges.Any(gc => gc.Type == ChangeType.RemoveOrDeleted)
				|| !enreplacedyInfoList.TryGetValue(enreplacedyName, out info) 
				|| info.WebsiteLookupAttribute == null)
			{
				return true;
			}
			
			// trying to get website's id from changed items 
			var itemWithWebsiteIdValue = groupedChanges
				.OfType<NewOrUpdatedItem>()
				.FirstOrDefault(item => item.NewOrUpdatedEnreplacedy.Contains(info.WebsiteLookupAttribute));

			// if all changes doesn't contain website lookup attribute but we know that enreplacedy should have it then try to get value from service context
			var updatedEnreplacedy = itemWithWebsiteIdValue != null
				? itemWithWebsiteIdValue.NewOrUpdatedEnreplacedy
				: context.Service.RetrieveSingle(new EnreplacedyReference(enreplacedyName, enreplacedyId), new ColumnSet(info.WebsiteLookupAttribute));

			return updatedEnreplacedy?.GetAttributeValue<EnreplacedyReference>(info.WebsiteLookupAttribute)?.Id == websiteId;
		}

19 Source : EventAccessPermissionProvider.cs
with MIT License
from Adoxio

public override bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy currentEvent, CrmEnreplacedyRight right, CrmEnreplacedyCacheDependencyTrace dependencies)
		{
			currentEvent.replacedertEnreplacedyName("adx_event");

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on event ({1}).", right, currentEvent.Id));

			dependencies.AddEnreplacedyDependency(currentEvent);
			dependencies.AddEnreplacedySetDependency("adx_webrole");
			dependencies.AddEnreplacedySetDependency("adx_eventaccesspermission");

			if (!Roles.Enabled)
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Roles are not enabled for this application. Allowing Read, but not Change.");

                // If roles are not enabled on the site, grant Read, deny Change.
                return (right == CrmEnreplacedyRight.Read);
			}

			// Windows Live ID Server decided to return null for an unauthenticated user's name
			// A null username, however, breaks the Roles.GetRolesForUser() because it expects an empty string.
			var currentUsername = (HttpContext.Current.User != null && HttpContext.Current.User.Idenreplacedy != null)
				? HttpContext.Current.User.Idenreplacedy.Name ?? string.Empty
				: string.Empty;
			

			var userRoles = Roles.GetRolesForUser(currentUsername);

			// Get all rules applicable to the event, grouping equivalent rules. (Rules that
			// target the same event and confer the same right are equivalent.)
			var ruleGroupings = from rule in GetRulesApplicableToEvent(context, currentEvent, dependencies)
								let eventReference = rule.GetAttributeValue<EnreplacedyReference>("adx_eventid")
								let rightOption = rule.GetAttributeValue<OptionSetValue>("adx_right")
								where eventReference != null && rightOption != null
								group rule by new { EventID = eventReference.Id, Right = rightOption.Value } into ruleGrouping
								select ruleGrouping;

			var websiteReference = currentEvent.GetAttributeValue<EnreplacedyReference>("adx_websiteid");

			foreach (var ruleGrouping in ruleGroupings)
			{
				// Collect the names of all the roles that apply to this rule grouping
				var ruleGroupingRoles = ruleGrouping.SelectMany(rule => rule.GetRelatedEnreplacedies(context, "adx_eventaccesspermission_webrole").ToList()
					.Where(role => BelongsToWebsite(websiteReference, role))
					.Select(role => role.GetAttributeValue<string>("adx_name")));

				// Determine if the user belongs to any of the roles that apply to this rule grouping
				var userIsInAnyRoleForThisRule = ruleGroupingRoles.Any(role => userRoles.Any(userRole => userRole == role));

				// If the user belongs to one of the roles...
				if (userIsInAnyRoleForThisRule)
				{
					if (ruleGrouping.Key.Right != RestrictRead)
					{
                        ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on forum ({0}). Permission granted.", ruleGrouping.Key.EventID));

						// ...the user has all rights.
						return true;
					}
				}
				// If the user does not belong to any of the roles, the rule restricts read, and the desired right
				// is read...
				else if (ruleGrouping.Key.Right == RestrictRead && right == CrmEnreplacedyRight.Read)
				{
                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on event ({0}). Permission denied.", ruleGrouping.Key.EventID));

					// ...the user has no right.
					return false;
				}
			}
			
			//Get all membership type applicable to the event
			var membershipTypes = currentEvent.GetRelatedEnreplacedies(context, "adx_event_membershiptype");

			//If the event has membership types, specific user has right to access it. If there is no membership type, every user has right.
			if (membershipTypes.Any())
			{
				var contact = PortalContext.Current.User;

				//Anonymouse user has no right.
				if (contact == null) return false;

				foreach (var membershipType in membershipTypes)
				{
					if (contact.GetRelatedEnreplacedies(context, "adx_membership_contact").Any(m => m.GetAttributeValue<EnreplacedyReference>("adx_membershiptypeid") == membershipType.ToEnreplacedyReference()))                   
					{
						return true;
					}
				}

				return false;
			}

			// If none of the above rules apply, replacedert on parent webpage.
			var parentWebPage = currentEvent.GetRelatedEnreplacedy(context, "adx_webpage_event");

			// If there is no parent web page, grant Read by default, and deny Change.
			if (parentWebPage == null)
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and event. Allowing Read, but not Change.");

				return (right == CrmEnreplacedyRight.Read);
			}

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and event. replacederting right on parent web page.");

			return _webPageAccessControlProvider.Tryreplacedert(context, parentWebPage, right, dependencies);
		}

19 Source : ForumAccessPermissionProvider.cs
with MIT License
from Adoxio

protected override bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy forum, CrmEnreplacedyRight right, CrmEnreplacedyCacheDependencyTrace dependencies, ContentMap map)
		{
			forum.replacedertEnreplacedyName("adx_communityforum");

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on forum '{1}' ({2}).", right, forum.GetAttributeValue<string>("adx_name"), forum.Id));

			this.AddDependencies(dependencies, forum, new[] { "adx_webrole", "adx_communityforumaccesspermission" });

			if (!Roles.Enabled)
			{
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Roles are not enabled for this application. Allowing Read, but not Change.");

				// If roles are not enabled on the site, grant Read, deny Change.
				return (right == CrmEnreplacedyRight.Read);
			}

			var userRoles = this.GetUserRoles();

			// Get all rules applicable to the forum, grouping equivalent rules. (Rules that
			// target the same forum and confer the same right are equivalent.)
			var ruleGroupings = from rule in this.GetRulesApplicableToForum(forum, dependencies, map)
								let forumReference = rule.GetAttributeValue<EnreplacedyReference>("adx_forumid")
								let rightOption = rule.GetAttributeValue<OptionSetValue>("adx_right")
								where forumReference != null && rightOption != null
								group rule by new { ForumID = forumReference.Id, Right = ParseRightOption(rightOption.Value) } into ruleGrouping
								select ruleGrouping;

			var websiteReference = forum.GetAttributeValue<EnreplacedyReference>("adx_websiteid");

			// Order the rule groupings so that all GrantChange rules will be evaluated first.
			ruleGroupings = ruleGroupings.OrderByDescending(grouping => grouping.Key.Right, new RightOptionComparer());

			foreach (var ruleGrouping in ruleGroupings)
			{
				// Collect the names of all the roles that apply to this rule grouping
				var ruleGroupingRoles = ruleGrouping.SelectMany(rule => GetRolesForGrouping(map, rule, websiteReference));

				// Determine if the user belongs to any of the roles that apply to this rule grouping
				var userIsInAnyRoleForThisRule = ruleGroupingRoles.Any(role => userRoles.Any(userRole => userRole == role));

				// If the user belongs to one of the roles...
				if (userIsInAnyRoleForThisRule)
				{
					// ...and the rule is GrantChange...
					if (ruleGrouping.Key.Right == RightOption.GrantChange)
					{
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on forum ({0}). Permission granted.", ruleGrouping.Key.ForumID));

						// ...the user has all rights.
						return true;
					}
				}
				// If the user does not belong to any of the roles, the rule restricts read, and the desired right
				// is read...
				else if (ruleGrouping.Key.Right == RightOption.RestrictRead && right == CrmEnreplacedyRight.Read)
				{
					ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on forum ({0}). Permission denied.", ruleGrouping.Key.ForumID));

					// ...the user has no right.
					return false;
				}
			}

			// If none of the above rules apply, replacedert on parent webpage.
			var parentWebPage = forum.GetAttributeValue<EnreplacedyReference>("adx_parentpageid");
			WebPageNode parentPageNode;
			map.TryGetValue(parentWebPage, out parentPageNode);

			// If there is no parent web page, grant Read by default, and deny Change.
			if (parentWebPage == null || parentPageNode == null)
			{
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and forum. Allowing Read, but not Change.");

				return (right == CrmEnreplacedyRight.Read);
			}

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and forum. replacederting right on parent web page.");

			return this._webPageAccessControlProvider.Tryreplacedert(context, parentPageNode.ToEnreplacedy(), right, dependencies);
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static void AddTagToForumThreadAndSave(this OrganizationServiceContext context, Guid threadId, string tagName)
		{
			if (context.MergeOption == MergeOption.NoTracking)
			{
				throw new ArgumentException("The OrganizationServiceContext.MergeOption cannot be MergeOption.NoTracking.", "context");
			}

			if (string.IsNullOrEmpty(tagName))
			{
				throw new ArgumentException("Can't be null or empty.", "tagName");
			}

			if (threadId == Guid.Empty)
			{
				throw new ArgumentException("Argument must be a non-empty GUID.", "threadId");
			}

			var thread = context.CreateQuery("adx_communityforumthread").Single(e => e.GetAttributeValue<Guid>("adx_communityforumthreadid") == threadId);

			var tag = GetForumThreadTagByName(context, tagName);

			// If the tag doesn't exist, create it
			if (tag == null)
			{
				tag =  new Enreplacedy("adx_communityforumthreadtag");

				tag["adx_name"] = tagName;

				context.AddObject(tag);
				context.SaveChanges();
				context.ReAttach(thread);
				context.ReAttach(tag);
			}

			if (!thread.GetRelatedEnreplacedies(context, "adx_forumthreadtag_forumthread").Any(t => t.GetAttributeValue<Guid>("adx_communityforumthreadtagid") == tag.Id))
			{
				context.AddLink(thread, "adx_forumthreadtag_forumthread", tag);

				context.SaveChanges();
			}
		}

19 Source : CrmJsonConverter.cs
with MIT License
from Adoxio

public override bool CanConvert(Type objectType)
		{
			if (CanConvertTypes.Any(type => type == objectType))
			{
				 return true;
			}

			if (CanConvertBaseTypes.Any(type => type.IsreplacedignableFrom(objectType)))
			{
				 return true;
			}

			return false;
		}

19 Source : FetchXml.cs
with MIT License
from Adoxio

public void AddConditionalStatement(string type, string attributeLogicalName, string op, string value = null, string linkEnreplacedyAlias = null)
		{
			var filter = new XElement("filter");
			filter.SetAttributeValue("type", type);
			var condition = new XElement("condition");
			condition.SetAttributeValue("attribute", attributeLogicalName);
			condition.SetAttributeValue("operator", op);
			if (value != null)
			{
				condition.SetAttributeValue("value", value);
			}
			filter.Add(condition);

			if (linkEnreplacedyAlias == null)
			{
				foreach (var element in _xml.XPathSelectElements("//fetch/enreplacedy"))
				{

					element.Add(filter);
				}
			}
			else
			{
				var enreplacedy = _xml
				.XPathSelectElements("//fetch/enreplacedy")
				.FirstOrDefault(e => e.Attributes("name").Any(a => a.Value == LogicalName));

				if (enreplacedy == null)
				{
					return;
				}

				var linkEnreplacedy = enreplacedy
					.XPathSelectElements("link-enreplacedy")
					.FirstOrDefault(e => e.Attributes("alias").Any(a => a.Value == linkEnreplacedyAlias));

				if (linkEnreplacedy == null)
				{
					return;
				}

				linkEnreplacedy.Add(filter);
			}

		}

19 Source : FetchXml.cs
with MIT License
from Adoxio

public bool TryGetLinkAttribute(FetchXmlResultField field, out FetchXmlLinkAttribute linkAttribute)
		{
			linkAttribute = null;

			var nameParts = field.Name.Split('.');

			if (nameParts.Length != 2)
			{
				return false;
			}

			var enreplacedy = _xml.XPathSelectElements("//fetch/enreplacedy")
				.Where(e => e.Attributes("name").Any(a => a.Value == LogicalName))
				.FirstOrDefault();

			if (enreplacedy == null)
			{
				return false;
			}

			var linkEnreplacedy = enreplacedy.XPathSelectElements("link-enreplacedy")
				.Where(e => e.Attributes("alias").Any(a => a.Value == nameParts.First()))
				.FirstOrDefault() 
				?? enreplacedy.XPathSelectElements("link-enreplacedy").FirstOrDefault().XPathSelectElements("link-enreplacedy")
				.FirstOrDefault().XPathSelectElements("link-enreplacedy").FirstOrDefault(a => a.Attributes("alias").Any(n => n.Value == nameParts.First()));

			if (linkEnreplacedy == null)
			{
				return false;
			}

			var linkEnreplacedyAttribute =
				linkEnreplacedy.XPathSelectElements("attribute")
					.Where(e => e.Attributes("name").Any(a => a.Value == nameParts.Last()))
					.FirstOrDefault()
				?? linkEnreplacedy.XPathSelectElements("link-enreplacedy").Where(a => a.Attributes("from").Any(p => p.Value == nameParts.Last())).FirstOrDefault();

			if (linkEnreplacedyAttribute == null)
			{
				return false;
			}

			var enreplacedyName = linkEnreplacedy.Attributes("name").Select(a => a.Value).FirstOrDefault();

			if (string.IsNullOrEmpty(enreplacedyName))
			{
				return false;
			}

			var logicalName = linkEnreplacedyAttribute.Attributes("to").Select(a => a.Value).FirstOrDefault() ?? linkEnreplacedyAttribute.Attributes("name").Select(a => a.Value).FirstOrDefault();

			if (string.IsNullOrEmpty(logicalName))
			{
				return false;
			}

			linkAttribute = new FetchXmlLinkAttribute(logicalName, enreplacedyName);

			return true;
		}

19 Source : CmsIndexHelper.cs
with MIT License
from Adoxio

private static IEnumerable<string> SelectAllWebRolesForWebpage(Guid enreplacedyId, ContentMap contentMap)
		{
			EnreplacedyNode enreplacedy;
			if (!contentMap.TryGetValue(new EnreplacedyReference("adx_webpage", enreplacedyId), out enreplacedy))
			{
				return Enumerable.Empty<string>();
			}

			var webpage = enreplacedy as WebPageNode;
			if (webpage == null)
			{
				return Enumerable.Empty<string>();
			}
			var webAccessRules = GetRulesForPage(webpage).ToList();

			// If the rule doesn't have a right replacedociated to it then allow access 
			var anyReadRestrictRules =
				webAccessRules.Any(
					rule =>
						{
							if (rule.Right == null)
							{
								return false;
							}
							return rule.Right.Value.ToEnum<ForumAccessPermissionProvider.RightOption>()
							   == ForumAccessPermissionProvider.RightOption.RestrictRead;
						});

			// If there is not read restrict rules specified then allow READ access. 
			return anyReadRestrictRules || (webpage.PublishingState.IsVisible == null || webpage.PublishingState.IsVisible.Value == false) 
					? webAccessRules.SelectMany(webPageAccessControlRuleNode => webPageAccessControlRuleNode.WebRoles,
						(webPageAccessControlRuleNode, webRole) => webRole.Name).Distinct() 
					: new[] { AllowAccessDefaultValue };
		}

19 Source : CrmEntityIndexBuilder.cs
with MIT License
from Adoxio

private void UpdateWithIndexers(string enreplacedyLogicalName, IEnumerable<ICrmEnreplacedyIndexer> indexers)
		{
			if (!indexers.Any(indexer => indexer.Indexes(enreplacedyLogicalName)))
			{
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Application does not index enreplacedy {0}. No update performed.", enreplacedyLogicalName));

				return;
			}

			var enreplacedyIndexDoreplacedents = indexers.SelectMany(indexer => indexer.GetDoreplacedents()).ToArray();

			UsingWriter(MethodBase.GetCurrentMethod().Name, false, true, writer =>
			{
				foreach (var enreplacedyDoc in enreplacedyIndexDoreplacedents)
				{
					writer.DeleteDoreplacedents(GetEnreplacedyQuery(_index, enreplacedyLogicalName, enreplacedyDoc.PrimaryKey));
				}
			});

			int currentIndex = 0;
			while (currentIndex < enreplacedyIndexDoreplacedents.Length)
			{
				UsingWriter(MethodBase.GetCurrentMethod().Name, false, true, writer =>
				{
					var stopwatch = new Stopwatch();
					stopwatch.Start();

					for (; currentIndex < enreplacedyIndexDoreplacedents.Length; currentIndex++)
					{
						writer.AddDoreplacedent(enreplacedyIndexDoreplacedents[currentIndex].Doreplacedent, enreplacedyIndexDoreplacedents[currentIndex].replacedyzer);

						// We've held onto the write lock too long, there might be other updates waiting on us.
						// Release the lock so they don't time out, then re-enter the queue for the write lock.
						if (stopwatch.Elapsed.TotalSeconds > 10)
						{
							// break;
						}
					}
				});
			}
		}

19 Source : FetchXml.cs
with MIT License
from Adoxio

public void AddLinkEnreplacedyAttribute(string alias, string attributeLogicalName)
		{
			var enreplacedy = _xml
				.XPathSelectElements("//fetch/enreplacedy")
				.FirstOrDefault(e => e.Attributes("name").Any(a => a.Value == LogicalName));

			if (enreplacedy == null)
			{
				return;
			}

			var linkEnreplacedy = enreplacedy
				.XPathSelectElements("link-enreplacedy")
				.FirstOrDefault(e => e.Attributes("alias").Any(a => a.Value == alias));

			if (linkEnreplacedy == null)
			{
				return;
			}

			linkEnreplacedy.Add(new XElement("attribute", new XAttribute("name", attributeLogicalName)));
		}

19 Source : FetchXmlIndexDocumentFactory.cs
with MIT License
from Adoxio

private static bool AttributeTypeEqualsOneOf(AttributeMetadata attributeMetadata, params string[] typeNames)
		{
			if (attributeMetadata == null || attributeMetadata.AttributeType == null)
			{
				return false;
			}

			var attributeTypeName = attributeMetadata.AttributeType.Value.ToString();

			return typeNames.Any(name => string.Equals(attributeTypeName, name, StringComparison.InvariantCultureIgnoreCase));
		}

19 Source : SavedQueryIndexer.cs
with MIT License
from Adoxio

public bool Indexes(string enreplacedyLogicalName)
		{
			return Indexers.Any(indexer => indexer.Indexes(enreplacedyLogicalName));
		}

19 Source : ClientFactory.cs
with MIT License
from Adoxio

protected virtual bool IsOnline(SharePointConnection connection)
		{
			return GetOnlineDomainsSetting().Any(domain => connection.Url.Host.EndsWith(domain, StringComparison.OrdinalIgnoreCase));
		}

19 Source : CrmEntityIndexSearcher.cs
with MIT License
from Adoxio

protected ICrmEnreplacedySearchResultPage GetUserSearchResults(ICrmEnreplacedyQuery query, int searchLimit, int initialOffset, int resultLimit, ICrmEnreplacedySearchResultFactory resultFactory, int pageNumber, int pageSize, ICollection<ICrmEnreplacedySearchResult> results)
        {
            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("(searchLimit={0},rawOffset={1},resultLimit={2})", searchLimit, initialOffset, resultLimit));
            RawSearchResultSet rawSearchResults = GetRawSearchResults(query, searchLimit, initialOffset);
            
            if (initialOffset >= rawSearchResults.TotalHits)
            {
                return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
            }

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            var groupedNotes = new List<IGrouping<EnreplacedyReference, ICrmEnreplacedySearchResult>>();
            var displayNotes = IsAnnotationSearchEnabled();

            if (displayNotes && !string.IsNullOrEmpty(query.QueryTerm))
            {
                var rawNotes = this.GetRelatedAnnotations(rawSearchResults, query);

                var notes =
                    rawNotes.Select(doreplacedent => resultFactory.GetResult(doreplacedent, 1, results.Count + 1)).ToList();

                //Grouping Notes by related Knowledge Articles
                groupedNotes =
                    notes.Where(note => note.EnreplacedyLogicalName == "annotation")
                        .GroupBy(note => note.Enreplacedy.GetAttributeValue<EnreplacedyReference>("objectid"))
                        .ToList();
            }

            var offsetForNexreplacederation = initialOffset;

            foreach (var scoreDoc in rawSearchResults.Results)
            {
                offsetForNexreplacederation++;

                var result = resultFactory.GetResult(_searcher.Doc(scoreDoc.Doc), scoreDoc.Score, results.Count + 1);

                // Not a valid user result, filter out
                if (result == null)
                {
                    continue;
                }

                if (result.EnreplacedyLogicalName == "knowledgearticle" && displayNotes)
                {
                    var relatedNotes = groupedNotes.Where(a => a.Key.Id == result.EnreplacedyID).SelectMany(i => i).Take(3).ToList();

                    if (relatedNotes.Any(note => note.Fragment == result.Fragment))
                    {
                        result.Fragment = GetKnowledgeArticleDescription(result);
                    }
                    result.Enreplacedy["relatedNotes"] = relatedNotes;
                }

                results.Add(result);

                if (results.Count >= resultLimit)
                {
                    stopwatch.Stop();

					ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

                    PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

                    return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
                }
            }

            stopwatch.Stop();

            // We asked for more hits than we got back from Lucene, and we still didn't gather enough valid
            // results. That's all we're going to get, so the number of results we got is the number of hits.
            if (searchLimit >= rawSearchResults.TotalHits)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

                PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

                return GenerateResultPage(results, results.Count, pageNumber, pageSize, rawSearchResults);
            }

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

            PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

            return GetUserSearchResults(query, searchLimit * ExtendedSearchLimitMultiple, offsetForNexreplacederation, resultLimit, resultFactory, pageNumber, pageSize, results);
        }

19 Source : ExtendedAttributeSearchResultInfo.cs
with MIT License
from Adoxio

private static bool AttributeTypeEqualsOneOf(AttributeMetadata attributeMetadata, params string[] typeNames)
		{
			var attributeTypeName = attributeMetadata.AttributeType.Value.ToString();

			return typeNames.Any(name => string.Equals(attributeTypeName, name, StringComparison.InvariantCultureIgnoreCase));
		}

19 Source : AnnotationDataAdapter.cs
with MIT License
from Adoxio

private static void SetResponseParameters(HttpContextBase context,
			Enreplacedy annotation, Enreplacedy webfile, ICollection<byte> data)
		{
			context.Response.StatusCode = (int)HttpStatusCode.OK;
			context.Response.ContentType = annotation.GetAttributeValue<string>("mimetype");

			var contentDispositionText = "attachment";

			if (_allowDisplayInlineContentTypes.Any(contentType => contentType.Equals(context.Response.ContentType, StringComparison.OrdinalIgnoreCase)))
			{
				contentDispositionText = "inline";
			}

			var contentDisposition = new StringBuilder(contentDispositionText);

			AppendFilenameToContentDisposition(annotation, contentDisposition);

			context.Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
			context.Response.AppendHeader("Content-Length", data.Count.ToString(CultureInfo.InvariantCulture));

			if (webfile?.Attributes != null && webfile.Attributes.ContainsKey("adx_alloworigin"))
			{
				var allowOrigin = webfile["adx_alloworigin"] as string;

				Web.Extensions.SetAccessControlAllowOriginHeader(context, allowOrigin);
			}
		}

19 Source : CmsIndexHelper.cs
with MIT License
from Adoxio

private static IEnumerable<string> SelectAllForumsWebRoles(Guid enreplacedyId, ContentMap contentMap)
		{
			EnreplacedyNode enreplacedy;

			// Get the Forums from the content map
			if (!contentMap.TryGetValue(new EnreplacedyReference("adx_communityforum", enreplacedyId), out enreplacedy))
			{
				return Enumerable.Empty<string>();
			}

			var forum = enreplacedy as ForumNode;
			if (forum == null)
			{
				return Enumerable.Empty<string>();
			}

			var changeRules =
				forum.ForumAccessPermissions.Where(fa => fa.Right == ForumAccessPermissionNode.RightOption.GrantChange)
					.SelectMany(fa => fa.WebRoles.Select(wr => wr.Name));

			var readRules =
				forum.ForumAccessPermissions.Where(fa => fa.Right == ForumAccessPermissionNode.RightOption.RestrictRead)
					.SelectMany(fa => fa.WebRoles.Select(wr => wr.Name)).ToList();

			bool anyInheritedReadRestrictRules = false;

			// If it has a parent page we will need to inspect to see if they have different read rules.
			if (forum.ParentPage != null)
			{
				var parentPageWebRoles = GetRulesForPage(forum.ParentPage).Distinct().ToList();
				anyInheritedReadRestrictRules =
				parentPageWebRoles.Any(
					rule =>
					{
						if (rule.Right == null)
						{
							return false;
						}
						return rule.Right.Value.ToEnum<ForumAccessPermissionProvider.RightOption>()
						   == ForumAccessPermissionProvider.RightOption.RestrictRead;
					});

				// If Both the webpage tree do not have read restrict rules then give access to all.  
				var parentPageWebRoleNames = anyInheritedReadRestrictRules || readRules.Any()
						? parentPageWebRoles.SelectMany(
							webPageAccessControlRuleNode => webPageAccessControlRuleNode.WebRoles,
								(webPageAccessControlRuleNode, webRole) => webRole.Name).Distinct()
						: new[] { AllowAccessDefaultValue };

				// If there are no read restrict rules then we just follow the parents roles and change roles
				if (!readRules.Any() && !anyInheritedReadRestrictRules)
				{
					return changeRules.Concat(parentPageWebRoleNames).Distinct();
				}

				readRules = parentPageWebRoleNames.Union(readRules).ToList();
			}

			// Since it didn't have a parent page make sure there isn't a read restrict rule if no then give access to all. 
			return readRules.Any() || anyInheritedReadRestrictRules ? changeRules.Concat(readRules).Distinct() : new[] { AllowAccessDefaultValue };
		}

19 Source : CrmEntityIndexerExtensions.cs
with MIT License
from Adoxio

public static FetchXml GetFetchXmlFilteredToSingleEnreplacedy(this ICrmEnreplacedyIndexer indexer, string fetchXml, OrganizationServiceContext dataContext, string enreplacedyLogicalName, Guid id)
		{
			var filteredFetchXml = XDoreplacedent.Parse(fetchXml);

			var enreplacedy = filteredFetchXml.XPathSelectElements("/fetch/enreplacedy")
				.Where(e => e.Attributes("name").Any(a => a.Value == enreplacedyLogicalName))
				.FirstOrDefault();

			if (enreplacedy == null)
			{
				throw new InvalidOperationException("Invalid FetchXML, unable to find enreplacedy element in FetchXML:\n\n{0}".FormatWith(filteredFetchXml));
			}

			var existingFilter = enreplacedy.XPathSelectElement("filter");

			var idFilter = new XElement("filter");

			idFilter.Add(new XAttribute("type", "and"));

			var condition = new XElement("condition");

			var primaryKey = GetPrimaryKeyField(indexer, dataContext, enreplacedyLogicalName);

			condition.Add(new XAttribute("attribute", primaryKey));
			condition.Add(new XAttribute("operator", "eq"));
			condition.Add(new XAttribute("value", id.ToString()));

			idFilter.Add(condition);

			if (existingFilter != null)
			{
				existingFilter.Remove();

				idFilter.Add(existingFilter);
			}

			enreplacedy.Add(idFilter);

			return new FetchXml(filteredFetchXml);
		}

19 Source : FetchXml.cs
with MIT License
from Adoxio

public bool ContainsAttribute(string attributeLogicalName)
		{
			return this._xml.XPathSelectElements("//fetch/enreplacedy/attribute").Any(x => x.GetAttributeValue("name") == attributeLogicalName);
		}

19 Source : FetchXml.cs
with MIT License
from Adoxio

public bool ContainsLinkEnreplacedy(string alias)
		{
			var enreplacedy = _xml
			.XPathSelectElements("//fetch/enreplacedy")
			.FirstOrDefault(e => e.Attributes("name").Any(a => a.Value == LogicalName));

			if (enreplacedy == null)
			{
				return false;
			}

			var linkEnreplacedy = enreplacedy
				.XPathSelectElements("link-enreplacedy")
				.FirstOrDefault(e => e.Attributes("alias").Any(a => a.Value == alias));

			return !(linkEnreplacedy == null);
		}

19 Source : SiteMapExtensions.cs
with MIT License
from Adoxio

public static IEnumerable<SiteMapNode> CurrentWebLinkChildNodes(this HtmlHelper html, IWebLinkSet webLinkSet, IEnumerable<string> enreplacedyLogicalNamesToExclude = null)
		{
			if (webLinkSet == null)
			{
				throw new ArgumentNullException("webLinkSet");
			}

			var currentWebLink = webLinkSet.WebLinks.FirstOrDefault(e =>
				e.Url != null
				&& !html.IsRootSiteMapNode(e.Url)
				&& ((html.IsCurrentSiteMapNode(e.Url) && html.IsFirstGenerationParentSiteMapNode(e.Url))
					|| html.IsAncestorSiteMapNode(e.Url, true)));

			return currentWebLink == null
				? Enumerable.Empty<SiteMapNode>()
				: enreplacedyLogicalNamesToExclude == null
					? html.SiteMapChildNodes(currentWebLink.Url)
					: html.SiteMapChildNodes(currentWebLink.Url).Where(e =>
					{
						var enreplacedyNode = e as CrmSiteMapNode;

						if (enreplacedyNode == null)
						{
							return true;
						}

						return !enreplacedyLogicalNamesToExclude.Any(enreplacedyNode.HasCrmEnreplacedyName);
					});
		}

19 Source : CrmProfileProvider.cs
with MIT License
from Adoxio

public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
		{
			var username = context["UserName"] as string;

			var xrm = CrmConfigurationManager.CreateContext(ContextName);

			var enreplacedy = GetProfileEnreplacedy(xrm, username);

			if (collection.Count < 1 || string.IsNullOrEmpty(username) || enreplacedy == null)
			{
				return;
			}

			var userIsAuthenticated = (context["IsAuthenticated"] as bool?).GetValueOrDefault();

			if (!userIsAuthenticated && collection.Cast<SettingsPropertyValue>().Any(propertyValue => (propertyValue.Property.Attributes["AllowAnonymous"] as bool?).GetValueOrDefault()))
			{
				throw new NotSupportedException("Anonymous properties aren't supported.");
			}

			var propertyValuesToUpdate = collection.Cast<SettingsPropertyValue>().Where(value => value.IsDirty && !value.UsingDefaultValue);

			foreach (var propertyValue in propertyValuesToUpdate)
			{
				var logicalName = GetCustomProviderData(propertyValue.Property);

				enreplacedy.SetAttributeValue(logicalName, propertyValue.PropertyValue);
			}

			enreplacedy.SetAttributeValue(_attributeMapLastActivityDate, DateTime.UtcNow);
			
			enreplacedy.SetAttributeValue(_attributeMapLastUpdatedDate, DateTime.UtcNow);

			xrm.UpdateObject(enreplacedy);

			xrm.SaveChanges();
		}

19 Source : CrmContactRoleProvider.cs
with MIT License
from Adoxio

public override string[] GetUsersInRole(string roleName)
		{
			if (!RoleExists(roleName))
			{
				return new string[0];
			}
			
			var roles = GetRolesInWebsiteByName(roleName).ToList();

			if (!roles.Any())
			{
				return new string[0];
			}

			// If any of the role enreplacedies in question have the Authenticated Users flag switched on, return the names of all users with
			// a non-null username.
			if (_authenticatedUsersRolesEnabled && roles.Any(role => role.GetAttributeValue<bool?>(_attributeMapIsAuthenticatedUsersRole) == true))
			{
				var authenticatedUsers = HttpContext.Current.GetOrganizationService()
					.RetrieveAll(_userEnreplacedyName, new[] { _attributeMapUsername }, GetAllUsersPredicate())
					.Select(user => user.GetAttributeValue<string>(_attributeMapUsername))
					.Distinct()
					.ToArray();

				return authenticatedUsers;
			}

			var roleIds = roles.Select(e => e.Id).Cast<object>().ToList();

			var fetch = new Fetch
			{
				Enreplacedy = new FetchEnreplacedy(_userEnreplacedyName)
				{
					Attributes = new[] { new FetchAttribute(_attributeMapUsername) },
					Filters = new[] { new Filter { Conditions = GetAllUsersPredicate() } },
					Links = new[] { new Link
					{
						Name = _roleToUserRelationshipName,
						ToAttribute = _userEnreplacedyId,
						FromAttribute = _userEnreplacedyId,
						Links = new[] { new Link
						{
							Name = _roleEnreplacedyName,
							ToAttribute = _roleEnreplacedyId,
							FromAttribute = _roleEnreplacedyId,
							Filters = new[] { new Filter
							{
								Conditions = new[] { new Condition(_roleEnreplacedyId, ConditionOperator.In, roleIds)  }
							} }
						} }
					} }
				}
			};

			var users = HttpContext.Current.GetOrganizationService()
				.RetrieveAll(fetch)
				.Select(e => e.GetAttributeValue<string>(_attributeMapUsername))
				.Distinct()
				.ToArray();

			return users;
		}

19 Source : StyleExtensions.cs
with MIT License
from Adoxio

private static IEnumerable<string> ContentStyles(IPortalViewContext portalViewContext, SiteMapNode node, IDictionary<string, object> cache, IEnumerable<string> except, IEnumerable<KeyValuePair<string, string>> only)
		{
			var styles = ContentStyles(portalViewContext, node, cache).ToArray();

			string[] allDisplayModes;
			string[] availableDisplayModes;

			if (TryGetDisplayModes(out allDisplayModes, out availableDisplayModes))
			{
				var partialUrlTrie = new FileNameTrie(styles);
				var displayModeComparer = new DisplayModeComparer(availableDisplayModes);

				var groups = GetDisplayModeFileGroups(partialUrlTrie, allDisplayModes);

				if (only != null)
				{
					return only.Select(o =>
					{
						var extensionless = Path.GetFileNameWithoutExtension(o.Key);

						var matchGroup = groups.FirstOrDefault(s => string.Equals(s.Prefix, extensionless, StringComparison.OrdinalIgnoreCase));

						if (matchGroup == null)
						{
							return o.Value;
						}

						var file = matchGroup.Where(f => availableDisplayModes.Contains(f.DisplayModeId))
							.OrderBy(f => f, displayModeComparer)
							.FirstOrDefault();

						return file == null ? o.Value : file.Name.Item1;
					});
				}

				if (except != null)
				{
					return groups
						.Where(group => !except.Any(e => string.Equals(Path.GetFileNameWithoutExtension(e), group.Prefix, StringComparison.OrdinalIgnoreCase)))
						.Select(group => group.Where(f => availableDisplayModes.Contains(f.DisplayModeId))
							.OrderBy(f => f, displayModeComparer)
							.FirstOrDefault())
						.Where(f => f != null)
						.Select(f => f.Name.Item1);
				}

				return groups
					.Select(group => group.Where(f => availableDisplayModes.Contains(f.DisplayModeId))
						.OrderBy(f => f, displayModeComparer)
						.FirstOrDefault())
					.Where(f => f != null)
					.Select(f => f.Name.Item1);
			}

			if (only != null)
			{
				return only.Select(o =>
				{
					var match = styles.FirstOrDefault(s => string.Equals(s.Item2, o.Key, StringComparison.InvariantCultureIgnoreCase));

					return match == null ? o.Value : match.Item1;
				});
			}

			if (except != null)
			{
				return styles
					.Where(s => !except.Any(e => string.Equals(e, s.Item2, StringComparison.InvariantCultureIgnoreCase)))
					.Select(s => s.Item1);
			}

			return styles.Select(s => s.Item1);
		}

19 Source : Expression.cs
with MIT License
from Adoxio

protected override bool Evaluate(IEnumerable<bool> operands)
		{
			// find any expression that is true

			return operands.Any(operand => operand);
		}

19 Source : Expression.cs
with MIT License
from Adoxio

protected override bool Evaluate(IEnumerable<bool> operands)
		{
			// find any expression that is false

			return !operands.Any(operand => !operand);
		}

19 Source : EntityExtensions.cs
with MIT License
from Adoxio

public static void SetRelatedEnreplacedies<TEnreplacedy>(this Enreplacedy enreplacedy, string relationshipSchemaName, EnreplacedyRole? primaryEnreplacedyRole, IEnumerable<TEnreplacedy> enreplacedies) where TEnreplacedy : Enreplacedy
		{
			relationshipSchemaName.ThrowOnNullOrWhitespace("relationshipSchemaName");

			if (enreplacedies != null && enreplacedies.Any(e => string.IsNullOrWhiteSpace(e.LogicalName)))
			{
				throw new ArgumentException("An enreplacedy is missing a value for the 'LogicalName' property.", "enreplacedies");
			}

			var relationship = new Relationship(relationshipSchemaName) { PrimaryEnreplacedyRole = primaryEnreplacedyRole };

			SetRelatedEnreplacedies(enreplacedy, relationship, enreplacedies);
		}

19 Source : CrmRoleProvider.cs
with MIT License
from Adoxio

public override string[] GetUsersInRole(string roleName)
		{
			if (!RoleExists(roleName))
			{
				return new string[0];
			}

			var context = ServiceContext;

			var roles = GetRolesInWebsiteByName(roleName);

			// If any of the role enreplacedies in question have the Authenticated Users flag switched on, return the names of all users with
			// a non-null username.
			if (_authenticatedUsersRolesEnabled && roles.Any(r => r.GetAttributeValue<bool?>(_attributeMapIsAuthenticatedUsersRole) == true))
			{
				return context.CreateQuery(_userEnreplacedyName)
					.Where(u => u.GetAttributeValue<string>(_attributeMapUsername) != null)
					.Select(u => u.GetAttributeValue<string>(_attributeMapUsername))
					.Distinct().ToArray();
			}

			var usernames = roles.SelectMany(role => role.GetRelatedEnreplacedies(context, _roleToUserRelationshipName).Select(user => user.GetAttributeValue<string>(_attributeMapUsername)));

			return usernames.Distinct().ToArray();
		}

19 Source : CrmEntityFormView.cs
with MIT License
from Adoxio

protected virtual ITemplate GetFormTemplate()
		{
			var context = OrganizationServiceContextFactory.Create() as OrganizationServiceContext;

			var cellTemplateFactory = CreateCellTemplateFactory();

			if (!string.IsNullOrEmpty(TabName))
			{
				var formXml = context.CreateQuery("systemform")
					.Single(form => form.GetAttributeValue<string>("objecttypecode") == EnreplacedyName
						&& form.GetAttributeValue<OptionSetValue>("type").Value == 2)
					.GetAttributeValue<string>("formxml");

				var sections = XDoreplacedent.Parse(formXml).XPathSelectElements("form/tabs/tab").Where(
					tab => tab.XPathSelectElements("labels/label").Any(
						label => label.Attributes("description").Any(description => description.Value == TabName))).SelectMany(tab => tab.XPathSelectElements("columns/column/sections/section"));

				cellTemplateFactory.Initialize(this, new FormXmlCellMetadataFactory(), CellBindings, LanguageCode, ValidationGroup, ShowUnsupportedFields);

				var rowTemplateFactory = new RowTemplateFactory(LanguageCode);

				var sectionTemplates = sections.Select(s => new SectionTemplate(s, LanguageCode, EnreplacedyMetadata, cellTemplateFactory, rowTemplateFactory));

				return new CompositeTemplate(sectionTemplates);
			}

			if (!string.IsNullOrEmpty(SavedQueryName))
			{
				cellTemplateFactory.Initialize(this, new SavedQueryCellMetadataFactory(), CellBindings, LanguageCode, ValidationGroup, ShowUnsupportedFields);

				var layoutXml = context.CreateQuery("savedquery")
					.Single(view => view.GetAttributeValue<string>("name") == SavedQueryName)
					.GetAttributeValue<string>("layoutxml");

				var rows = XDoreplacedent.Parse(layoutXml).XPathSelectElements("grid/row");

				var rowTemplates = rows.Select(r => new SavedQueryRowTemplate(r, LanguageCode, EnreplacedyMetadata, cellTemplateFactory));

				return new CompositeTemplate(rowTemplates);
			}

			return new EmptyTemplate();
		}

19 Source : CitizenProfile.aspx.cs
with MIT License
from Adoxio

public void ManageLists(OrganizationServiceContext context, Enreplacedy contact)
		{
			foreach (var item in MarketingListsListView.Items)
			{
				if (item == null)
				{
					continue;
				}

				var listViewItem = item;

				var hiddenListId = (HiddenField)listViewItem.FindControl("ListID");

				if (hiddenListId == null)
				{
					continue;
				}

				var listId = new Guid(hiddenListId.Value);

				var ml = context.CreateQuery("list").First(m => m.GetAttributeValue<Guid>("listid") == listId);

				var listCheckBox = (CheckBox)item.FindControl("ListCheckbox");

				if (listCheckBox == null)
				{
					continue;
				}

				var contactLists = contact.GetRelatedEnreplacedies(XrmContext, new Relationship("listcontact_replacedociation")).ToList();

				var inList = contactLists.Any(list => list.GetAttributeValue<Guid>("listid") == ml.Id);

				if (listCheckBox.Checked && !inList)
				{
					context.AddMemberList(ml.GetAttributeValue<Guid>("listid"), contact.GetAttributeValue<Guid>("contactid"));
				}
				else if (!listCheckBox.Checked && inList)
				{
					context.RemoveMemberList(ml.GetAttributeValue<Guid>("listid"), contact.GetAttributeValue<Guid>("contactid"));
				}
			}
		}

19 Source : ChildNavigation.ascx.cs
with MIT License
from Adoxio

private Tuple<IEnumerable<SiteMapNode>, IEnumerable<SiteMapNode>> GetChildNodes()
		{
			var currentNode = SiteMap.CurrentNode;

			if (currentNode == null)
			{
				return new Tuple<IEnumerable<SiteMapNode>, IEnumerable<SiteMapNode>>(new SiteMapNode[] { }, new SiteMapNode[] { });
			}

			var excludeLogicalNames = string.IsNullOrEmpty(Exclude)
				? new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
				: new HashSet<string>(Exclude.Split(',').Select(name => name.Trim()), StringComparer.InvariantCultureIgnoreCase);

			var shortcutNodes = new List<SiteMapNode>();
			var otherNodes = new List<SiteMapNode>();

			foreach (SiteMapNode childNode in currentNode.ChildNodes)
			{
				var enreplacedyNode = childNode as CrmSiteMapNode;

				if (enreplacedyNode != null && excludeLogicalNames.Any(enreplacedyNode.HasCrmEnreplacedyName))
				{
					continue;
				}

				if (enreplacedyNode != null && enreplacedyNode.HasCrmEnreplacedyName("adx_shortcut"))
				{
					shortcutNodes.Add(childNode);

					continue;
				}
				
				otherNodes.Add(childNode);
			}

			return new Tuple<IEnumerable<SiteMapNode>, IEnumerable<SiteMapNode>>(otherNodes, shortcutNodes);
		}

See More Examples