System.Linq.IQueryable.Where(System.Linq.Expressions.Expression)

Here are the examples of the csharp api System.Linq.IQueryable.Where(System.Linq.Expressions.Expression) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1159 Examples 7

19 View Source File : RepositoryBase.cs
License : MIT License
Project Creator : a34546

public virtual IQueryable<TEnreplacedy> Query(Expression<Func<TEnreplacedy, bool>> predicate)
        {
            return Query().Where(predicate);
        }

19 View Source File : RepositoryBase.cs
License : MIT License
Project Creator : a34546

public virtual IQueryable<TEnreplacedy> QueryNoTracking(Expression<Func<TEnreplacedy, bool>> predicate)
        {
            return QueryNoTracking().Where(predicate);
        }

19 View Source File : RepositoryBase.cs
License : MIT License
Project Creator : a34546

public virtual int Count(Expression<Func<TEnreplacedy, bool>> predicate)
        {
            return Query().Where(predicate).Count();
        }

19 View Source File : RepositoryBase.cs
License : MIT License
Project Creator : a34546

public virtual long LongCount(Expression<Func<TEnreplacedy, bool>> predicate)
        {
            return Query().Where(predicate).LongCount();
        }

19 View Source File : WorkFlowManagementEfCoreQueryableExtensions.cs
License : Apache License 2.0
Project Creator : AbpApp

public static IQueryable<WorkflowDefinitionVersion> WithVersion(
            this IQueryable<WorkflowDefinitionVersion> query,
            VersionOptions version)
        {

            if (version.IsDraft)
                query = query.Where(x => !x.IsPublished);
            else if (version.IsLatest)
                query = query.Where(x => x.IsLatest);
            else if (version.IsPublished)
                query = query.Where(x => x.IsPublished);
            else if (version.IsLatestOrPublished)
                query = query.Where(x => x.IsPublished || x.IsLatest);
            else if (version.AllVersions)
            {
                // Nothing to filter.
            }
            else if (version.Version > 0)
                query = query.Where(x => x.Version == version.Version);

            return query.OrderByDescending(x => x.Version);
        }

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

public bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy website, Guid fromStateId, Guid toStateId)
		{
			// 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).ToLookup(role => role);

			//Get publshing state transitional rules 
			var publishingStateRulesApplicable = context.CreateQuery("adx_publishingstatetransitionrule").Where(psr =>
				psr.GetAttributeValue<EnreplacedyReference>("adx_fromstate_publishingstateid") == new EnreplacedyReference("adx_publishingstate", fromStateId) &&
				psr.GetAttributeValue<EnreplacedyReference>("adx_tostate_publishingstateid") == new EnreplacedyReference("adx_publishingstate", toStateId) &&
				psr.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website.ToEnreplacedyReference()).ToList();

			var webRoles = publishingStateRulesApplicable.SelectMany(rule => rule.GetRelatedEnreplacedies(context, "adx_publishingstatetransitionrule_webrole")
				.Where(role => role.GetAttributeValue<EnreplacedyReference>("adx_websiteid") != null && role.GetAttributeValue<EnreplacedyReference>("adx_websiteid").Id == website.Id))
					.ToList().Select(role => role.GetAttributeValue<string>("adx_name"));

			// Determine if the user belongs to any of the roles that apply to this rule grouping
			// If the user belongs to one of the roles... or if there are no rules applicable
			return (!publishingStateRulesApplicable.Any()) || webRoles.Any(role => userRoles.Contains(role));
		}

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

private static Enreplacedy CreateInvoiceFromOrder(OrganizationServiceContext context, Guid salesOrderId)
		{
			ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount");

			var convertOrderRequest = new ConvertSalesOrderToInvoiceRequest()
			{
				SalesOrderId = salesOrderId,
				ColumnSet = invoiceColumns
			};

			var convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)context.Execute(convertOrderRequest);

			var invoice = convertOrderResponse.Enreplacedy;

            var setStateRequest = new SetStateRequest()
            {
                EnreplacedyMoniker = invoice.ToEnreplacedyReference(),
                State = new OptionSetValue(2),
                Status = new OptionSetValue(100001)
            };

            var setStateResponse = (SetStateResponse)context.Execute(setStateRequest);

            invoice = context.CreateQuery("invoice").Where(i => i.GetAttributeValue<Guid>("invoiceid") == convertOrderResponse.Enreplacedy.Id).FirstOrDefault();

            return invoice;
		}

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

private static void SetOrderProducts(Enreplacedy shoppingCart, OrganizationServiceContext context, Guid salesOrderGuid, Money tax)
		{
			bool first = true;

			var carreplacedems = context.CreateQuery("adx_shoppingcarreplacedem")
				.Where(
					qp =>
					qp.GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid").Id ==
					shoppingCart.GetAttributeValue<Guid>("adx_shoppingcartid")).ToList();

			foreach (var item in carreplacedems)
			{
				var invoiceOrder =
					context.CreateQuery("salesorder").FirstOrDefault(o => o.GetAttributeValue<Guid>("salesorderid") == salesOrderGuid);

				var orderProduct = new Enreplacedy("salesorderdetail");

				var detailGuid = Guid.NewGuid();

				orderProduct.Attributes["salesorderdetailid"] = detailGuid;
				orderProduct.Id = detailGuid;

				var product = context.CreateQuery("product")
					.FirstOrDefault(
						p => p.GetAttributeValue<Guid>("productid") == item.GetAttributeValue<EnreplacedyReference>("adx_productid").Id);
				var unit = context.CreateQuery("uom")
					.FirstOrDefault(
						uom => uom.GetAttributeValue<Guid>("uomid") == item.GetAttributeValue<EnreplacedyReference>("adx_uomid").Id) ??
						context.CreateQuery("uom").FirstOrDefault(uom => uom.GetAttributeValue<Guid>("uomid")
							== product.GetAttributeValue<EnreplacedyReference>("defaultuomid").Id);
				/*var unit = context.CreateQuery("uom")
					.FirstOrDefault(
						uom => uom.GetAttributeValue<Guid>("uomid") == item.GetAttributeValue<EnreplacedyReference>("adx_uomid").Id);*/

				orderProduct.Attributes["productid"] = product.ToEnreplacedyReference();
				orderProduct.Attributes["uomid"] = unit.ToEnreplacedyReference();
				orderProduct.Attributes["ispriceoverridden"] = true;
				orderProduct.Attributes["priceperunit"] = item.GetAttributeValue<Money>("adx_quotedprice");
				orderProduct.Attributes["quanreplacedy"] = item.GetAttributeValue<decimal>("adx_quanreplacedy");
				orderProduct.Attributes["salesorderid"] = invoiceOrder.ToEnreplacedyReference();

				//We only place our tax on the first item
				if (first)
				{
					first = false;
					orderProduct.Attributes["tax"] = tax;
				}

				context.AddObject(orderProduct);
				//context.UpdateObject(invoiceOrder);
				context.SaveChanges();

				var detail =
					context.CreateQuery("salesorderdetail").FirstOrDefault(sod => sod.GetAttributeValue<Guid>("salesorderdetailid") == detailGuid);

			}
		}

19 View Source File : DiscountCodeValidationResult.cs
License : MIT License
Project Creator : 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 View Source File : CommerceQuote.cs
License : MIT License
Project Creator : Adoxio

private static void SetQuoteProducts(Enreplacedy shoppingCart, OrganizationServiceContext context, Guid quoteGuid)
		{
			var carreplacedems = context.CreateQuery("adx_shoppingcarreplacedem")
				.Where(
					qp =>
					qp.GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid").Id ==
					shoppingCart.GetAttributeValue<Guid>("adx_shoppingcartid")).ToList();

			foreach (var item in carreplacedems)
			{
				var invoiceOrder =
					context.CreateQuery("quote").FirstOrDefault(o => o.GetAttributeValue<Guid>("quoteid") == quoteGuid);

				var orderProduct = new Enreplacedy("quotedetail");

				var detailGuid = Guid.NewGuid();

				orderProduct.Attributes["quotedetailid"] = detailGuid;
				orderProduct.Id = detailGuid;

				var product = context.CreateQuery("product")
					.FirstOrDefault(
						p => p.GetAttributeValue<Guid>("productid") == item.GetAttributeValue<EnreplacedyReference>("adx_productid").Id);
				var unit = context.CreateQuery("uom")
					.FirstOrDefault(
						uom => uom.GetAttributeValue<Guid>("uomid") == product.GetAttributeValue<EnreplacedyReference>("defaultuomid").Id);
				/*var unit = context.CreateQuery("uom")
					.FirstOrDefault(
						uom => uom.GetAttributeValue<Guid>("uomid") == item.GetAttributeValue<EnreplacedyReference>("adx_uomid").Id);*/

				orderProduct.Attributes["productid"] = product.ToEnreplacedyReference();
				orderProduct.Attributes["uomid"] = unit.ToEnreplacedyReference();
				orderProduct.Attributes["ispriceoverridden"] = true;
				orderProduct.Attributes["priceperunit"] = item.GetAttributeValue<Money>("adx_quotedprice");
				orderProduct.Attributes["quanreplacedy"] = item.GetAttributeValue<decimal>("adx_quanreplacedy");
				orderProduct.Attributes["quoteid"] = invoiceOrder.ToEnreplacedyReference();

				context.AddObject(orderProduct);
				//context.UpdateObject(invoiceOrder);
				context.SaveChanges();

				var detail =
					context.CreateQuery("quotedetail").FirstOrDefault(sod => sod.GetAttributeValue<Guid>("quotedetailid") == detailGuid);

			}
		}

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

public IShoppingCarreplacedem GetCarreplacedemByID(Guid id)
		{
			var findShoppingCarreplacedems = _context.CreateQuery("adx_shoppingcarreplacedem")
				.Where(sci => sci.GetAttributeValue<Guid>("adx_shoppingcarreplacedemid") == id).Select(
					sci => new ShoppingCarreplacedem(sci, _context));

			return findShoppingCarreplacedems.FirstOrDefault();
		}

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

public IShoppingCart SelectCart()
		{
			var serviceContext = Dependencies.GetServiceContextForWrite();
			var website = Dependencies.GetWebsite();
			var user = Dependencies.GetPortalUser();

			var enreplacedy = SelectCarts(serviceContext, website, user)
				.Where(e => e.GetAttributeValue<bool>("adx_system") == false)
				.OrderByDescending(e => e.GetAttributeValue<DateTime>("createdon"))
				.FirstOrDefault();

			return enreplacedy == null
				? null
				: new ShoppingCart(enreplacedy, serviceContext);
		}

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

protected static IQueryable<Enreplacedy> SelectActiveCartsInWebsite(OrganizationServiceContext serviceContext, EnreplacedyReference website)
		{
			return serviceContext.CreateQuery("adx_shoppingcart")
				.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website)
				.Where(e => e.GetAttributeValue<OptionSetValue>("statecode") != null && e.GetAttributeValue<OptionSetValue>("statecode").Value == 0);
		}

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

protected static IQueryable<Enreplacedy> SelectCartsByContact(OrganizationServiceContext serviceContext, EnreplacedyReference website, EnreplacedyReference contact)
		{
			return SelectActiveCartsInWebsite(serviceContext, website)
				.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_contactid") != null && e.GetAttributeValue<EnreplacedyReference>("adx_contactid").Equals(contact));
		}

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

public static IQueryable<T> WhereIn<T, TValue>(this IQueryable<T> queryable, Expression<Func<T, TValue>> selector, IEnumerable<TValue> values)
		{
			return values.Any() ? queryable.Where(In(selector, values)) : Enumerable.Empty<T>().AsQueryable();
		}

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

public static IEnumerable<Enreplacedy> GetActiveCasesForContact(this OrganizationServiceContext context, EnreplacedyReference contact)
		{
			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var access = context.CreateQuery("adx_caseaccess")
				.Where(c => c.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
					&& c.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) == false && c.GetAttributeValue<OptionSetValue>("adx_scope") != null && c.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Self);

			if (access.ToArray().Any())
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var cases = context.CreateQuery("incident")
				.Where(i => i.GetAttributeValue<EnreplacedyReference>("customerid") == contact
					&& i.GetAttributeValue<OptionSetValue>("statecode") != null && i.GetAttributeValue<OptionSetValue>("statecode").Value == (int)IncidentState.Active);

			return cases.ToArray();
		}

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

public static IEnumerable<Enreplacedy> GetClosedCasesForContact(this OrganizationServiceContext context, EnreplacedyReference contact)
		{
			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var access = context.CreateQuery("adx_caseaccess")
				.Where(c => c.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
					&& c.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) == false && c.GetAttributeValue<OptionSetValue>("adx_scope") != null && c.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Self);

			if (access.ToArray().Any())
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var cases = context.CreateQuery("incident")
				.Where(i => i.GetAttributeValue<EnreplacedyReference>("customerid") == contact
					&& i.GetAttributeValue<OptionSetValue>("statecode") != null && i.GetAttributeValue<OptionSetValue>("statecode").Value != (int)IncidentState.Active);

			return cases;
		}

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

public static IEnumerable<Enreplacedy> GetCaseAccessByContact(this OrganizationServiceContext context, EnreplacedyReference contact)
		{
			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			return context.CreateQuery("adx_caseaccess")
				.Where(ca => ca.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact)
				.AsEnumerable();
		}

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

public static EnreplacedyReference CreateQuote(IEnumerable<LineItem> lineItems, EnreplacedyReference purchaseEnreplacedy, OrganizationServiceContext context, 
			OrganizationServiceContext serviceContextForWrite,  EnreplacedyReference user, EnreplacedyReference priceList, string visitorId = null, EnreplacedyReference target = null, 
			Enreplacedy purchaseMetadata = null)
		{
			lineItems = lineItems.ToArray();

			// Filter line items to only valid (active) products, that are in the current price list. If there are
			// no line items remaining at that point either return null or throw an exception?

			var validLineItems = GetValidLineItems(lineItems).ToArray();

			if (!validLineItems.Any()) { return null; }

			var productIds = validLineItems.Select(e => e.Product.Id).ToArray();

			var priceLisreplacedems = context.CreateQuery("productpricelevel")
				.Where(e => e.GetAttributeValue<EnreplacedyReference>("pricelevelid") == priceList)
				.WhereIn(e => e.GetAttributeValue<Guid>("productid"), productIds)
				.ToArray()
				.ToLookup(e => e.GetAttributeValue<EnreplacedyReference>("productid").Id);

			// Determine the UOM for each line item. If there is only one price list item for the product in the price list,
			// use the UOM from that. If there is more than one, favour them in this order: explict UOM on line item, default
			// product UOM... then random, basically?

			var lineItemsWithUom = validLineItems
				.Select(e => new { LineItem = e, UnitOfMeasure = e.GetUnitOfMeasure(priceLisreplacedems[e.Product.Id]) })
				.Where(e => e.UnitOfMeasure != null)
				.OrderBy(e => e.LineItem.Optional)
				.ThenBy(e => e.LineItem.Order)
				.ThenBy(e => e.LineItem.Product.GetAttributeValue<string>("adx_name"))
				.ToArray();

			if (!lineItemsWithUom.Any()) { return null; }

			// Set quote customer to current portal user. If there is no current portal user, create a contact on the fly
			// using the web form session anonymous visitor ID.

			var quote = new Enreplacedy("quote");

			var customer = GetQuoteCustomer(context, user, visitorId);

			quote["pricelevelid"] = priceList;

			quote["transactioncurrencyid"] = GetPriceListCurrency(context, priceList);

			quote["customerid"] = customer;

			quote["adx_specialinstructions"] = GetQuoteInstructions(lineItems);

			quote["name"] = GetQuoteName(context, purchaseMetadata);

			// If the purchase enreplacedy or target enreplacedy is a shopping cart, set that on the quote.
			if (purchaseEnreplacedy.LogicalName == "adx_shoppingcart")
			{
				quote["adx_shoppingcartid"] = purchaseEnreplacedy;
			}
			else if (target != null && target.LogicalName == "adx_shoppingcart")
			{
				quote["adx_shoppingcartid"] = target;
			}

			if (user != null)
			{
				var contact = context.CreateQuery("contact")
					.FirstOrDefault(e => e.GetAttributeValue<Guid>("contactid") == user.Id);

				if (contact != null)
				{
					quote["billto_city"] = contact.GetAttributeValue<string>("address1_city");
					quote["billto_country"] = contact.GetAttributeValue<string>("address1_country");
					quote["billto_line1"] = contact.GetAttributeValue<string>("address1_line1");
					quote["billto_line2"] = contact.GetAttributeValue<string>("address1_line2");
					quote["billto_line3"] = contact.GetAttributeValue<string>("address1_line3");
					quote["billto_name"] = contact.GetAttributeValue<string>("fullname");
					quote["billto_postalcode"] = contact.GetAttributeValue<string>("address1_postalcode");
					quote["billto_stateorprovince"] = contact.GetAttributeValue<string>("address1_stateorprovince");

					quote["shipto_city"] = contact.GetAttributeValue<string>("address1_city");
					quote["shipto_country"] = contact.GetAttributeValue<string>("address1_country");
					quote["shipto_line1"] = contact.GetAttributeValue<string>("address1_line1");
					quote["shipto_line2"] = contact.GetAttributeValue<string>("address1_line2");
					quote["shipto_line3"] = contact.GetAttributeValue<string>("address1_line3");
					quote["shipto_name"] = contact.GetAttributeValue<string>("fullname");
					quote["shipto_postalcode"] = contact.GetAttributeValue<string>("address1_postalcode");
					quote["shipto_stateorprovince"] = contact.GetAttributeValue<string>("address1_stateorprovince");
				}
			}

			if (serviceContextForWrite == null) serviceContextForWrite = context;

			serviceContextForWrite.AddObject(quote);
			serviceContextForWrite.SaveChanges();

			var quoteReference = quote.ToEnreplacedyReference();

			var lineItemNumber = 1;

			foreach (var lineItem in lineItemsWithUom)
			{
				var quoteProduct = new Enreplacedy("quotedetail");

				quoteProduct["quoteid"] = quoteReference;
				quoteProduct["productid"] = lineItem.LineItem.Product.ToEnreplacedyReference();
				quoteProduct["quanreplacedy"] = lineItem.LineItem.Quanreplacedy;
				quoteProduct["uomid"] = lineItem.UnitOfMeasure;
				quoteProduct["description"] = lineItem.LineItem.Description;
				quoteProduct["lineitemnumber"] = lineItemNumber;
				quoteProduct["adx_isrequired"] = !lineItem.LineItem.Optional;

				serviceContextForWrite.AddObject(quoteProduct);

				lineItemNumber++;
			}

			serviceContextForWrite.SaveChanges();

			return quoteReference;
		}

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

public static string GetDefaultPriceListName(this OrganizationServiceContext context, Enreplacedy website)
		{
			website.replacedertEnreplacedyName("adx_website");

			var defaultPriceLevelSetting = context.CreateQuery("adx_sitesetting")
				.Where(ss => ss.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website.ToEnreplacedyReference())
				.FirstOrDefault(purl => purl.GetAttributeValue<string>("adx_name") == "Ecommerce/DefaultPriceLevelName");

			return defaultPriceLevelSetting == null || string.IsNullOrWhiteSpace(defaultPriceLevelSetting.GetAttributeValue<string>("adx_value")) ? "Web" : defaultPriceLevelSetting.GetAttributeValue<string>("adx_value");
		}

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

public static string GetDefaultPriceListName(this OrganizationServiceContext context, Guid websiteid)
		{
			var defaultPriceLevelSetting = context.CreateQuery("adx_sitesetting")
				.Where(ss => ss.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == new EnreplacedyReference("adx_website", websiteid))
				.FirstOrDefault(purl => purl.GetAttributeValue<string>("adx_name") == "Ecommerce/DefaultPriceLevelName");

			return defaultPriceLevelSetting == null || string.IsNullOrWhiteSpace(defaultPriceLevelSetting.GetAttributeValue<string>("adx_value")) ? "Web" : defaultPriceLevelSetting.GetAttributeValue<string>("adx_value");
		}

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

public IEnumerable<IShoppingCarreplacedem> GetCarreplacedems()
		{
			var items =
				_context.CreateQuery("adx_shoppingcarreplacedem").Where(
					sci => sci.GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid").Id
						   == Enreplacedy.GetAttributeValue<Guid>("adx_shoppingcartid")).Select(sci => new ShoppingCarreplacedem(sci, _context));

			return items;
		}

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

protected static IQueryable<Enreplacedy> SelectCartsByVisitorId(OrganizationServiceContext serviceContext, EnreplacedyReference website, string vistorId)
		{
			return SelectActiveCartsInWebsite(serviceContext, website)
				.Where(e => e.GetAttributeValue<string>("adx_visitorid") == vistorId);
		}

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

internal static string GetTimeZoneStandardName(OrganizationServiceContext serviceContext, int timeZoneCode)
		{
			var timeZoneDefinition = serviceContext.CreateQuery("timezonedefinition")
				.Where(e => e.GetAttributeValue<int?>("timezonecode") == timeZoneCode)
				.Select(e => new { StandardName = e.GetAttributeValue<string>("standardname") })
				.ToArray()
				.FirstOrDefault();

			if (timeZoneDefinition == null || string.IsNullOrEmpty(timeZoneDefinition.StandardName))
			{
				return null;
			}

			return timeZoneDefinition.StandardName;
		}

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

private static IQueryable<Enreplacedy> CreateThreadEnreplacedyQuery(OrganizationServiceContext serviceContext, EnreplacedyReference forum)
		{
			return serviceContext.CreateQuery("adx_communityforumthread")
				.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_forumid") == forum)
				.OrderByDescending(e => e.GetAttributeValue<bool?>("adx_sticky"))
				.OrderByDescending(e => e.GetAttributeValue<DateTime?>("adx_lastpostdate"));
		}

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

public static IEnumerable<Enreplacedy> GetActiveSupportPlansForContact(this OrganizationServiceContext context, Guid contactid)
		{
			var plans = context.CreateQuery("adx_supportplan").Where(o =>
							o.GetAttributeValue<EnreplacedyReference>("adx_customercontact") == new EnreplacedyReference("contact", contactid) &&
							(o.GetAttributeValue<OptionSetValue>("adx_allotmenttype") != null && o.GetAttributeValue<OptionSetValue>("adx_allotmenttype").Value == (int)AllotmentType.NumberCases && o.GetAttributeValue<int?>("adx_allotmentsremaining").GetValueOrDefault(0) > 0) &&
							o.GetAttributeValue<OptionSetValue>("statecode") != null && o.GetAttributeValue<OptionSetValue>("statecode").Value == (int)EnreplacedyState.Active);

			return plans;
		}

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

public static IEnumerable<Enreplacedy> GetActiveSupportPlansForContact(this OrganizationServiceContext context, Guid contactid, Guid productid)
		{
			var plans = context.CreateQuery("adx_supportplan").Where(o =>
							o.GetAttributeValue<EnreplacedyReference>("adx_customercontact") == new EnreplacedyReference("contact", contactid) &&
							o.GetAttributeValue<EnreplacedyReference>("adx_product") == new EnreplacedyReference("product", productid) &&
							(o.GetAttributeValue<OptionSetValue>("adx_allotmenttype") != null && o.GetAttributeValue<OptionSetValue>("adx_allotmenttype").Value == (int)AllotmentType.NumberCases && o.GetAttributeValue<int?>("adx_allotmentsremaining").GetValueOrDefault(0) > 0) &&
							o.GetAttributeValue<OptionSetValue>("statecode") != null && o.GetAttributeValue<OptionSetValue>("statecode").Value == (int)EnreplacedyState.Active);

			return plans;
		}

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

public static IEnumerable<Enreplacedy> GetActiveSupportPlansForAccount(this OrganizationServiceContext context, Guid accountid)
		{
			var plans = context.CreateQuery("adx_supportplan").Where(o =>
							o.GetAttributeValue<EnreplacedyReference>("adx_customer") == new EnreplacedyReference("account", accountid) &&
							(o.GetAttributeValue<OptionSetValue>("adx_allotmenttype") != null && o.GetAttributeValue<OptionSetValue>("adx_allotmenttype").Value == (int)AllotmentType.NumberCases && o.GetAttributeValue<int?>("adx_allotmentsremaining").GetValueOrDefault(0) > 0) &&
							o.GetAttributeValue<OptionSetValue>("statecode") != null && o.GetAttributeValue<OptionSetValue>("statecode").Value == (int)EnreplacedyState.Active);

			return plans;
		}

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

public static IEnumerable<Enreplacedy> GetActiveSupportPlansForAccount(this OrganizationServiceContext context, Guid accountid, Guid productid)
		{
			var plans = context.CreateQuery("adx_supportplan").Where(o =>
							o.GetAttributeValue<EnreplacedyReference>("adx_customer") == new EnreplacedyReference("account", accountid) &&
							o.GetAttributeValue<EnreplacedyReference>("adx_product") == new EnreplacedyReference("product", productid) &&
							(o.GetAttributeValue<OptionSetValue>("adx_allotmenttype") != null && o.GetAttributeValue<OptionSetValue>("adx_allotmenttype").Value == (int)AllotmentType.NumberCases && o.GetAttributeValue<int?>("adx_allotmentsremaining").GetValueOrDefault(0) > 0) &&
							o.GetAttributeValue<OptionSetValue>("statecode") != null && o.GetAttributeValue<OptionSetValue>("statecode").Value == (int)EnreplacedyState.Active);

			return plans;
		}

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

public static IEnumerable<Enreplacedy> GetOpportunitiesSpecificToContact(this OrganizationServiceContext context, Enreplacedy contact)
		{
			contact.replacedertEnreplacedyName("contact");

			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var access = context.CreateQuery("adx_opportunitypermissions").Where(c =>
				c.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference() &&
				c.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false));

			if (!access.ToList().Any())
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var opportunities = context.CreateQuery("opportunity").Where(i =>
				i.GetAttributeValue<EnreplacedyReference>("msa_partneroppid") == contact.ToEnreplacedyReference());

			return opportunities;
		}

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

public static IEnumerable<OpportunityHistory> GetOpportunityHistories(this OrganizationServiceContext context, Enreplacedy opportunity)
		{
			opportunity.replacedertEnreplacedyName("opportunity");

			var allOpportunityHistories = context.CreateQuery("adx_opportunitynote")
				.Where(on => on.GetAttributeValue<EnreplacedyReference>("adx_opportunityid") == opportunity.ToEnreplacedyReference())
				.OrderBy(on => on.GetAttributeValue<DateTime?>("createdon"))
				.Select(on => new OpportunityHistory(on))
				.ToList();

			var opportunityHistories = new List<OpportunityHistory>();

			var distinctHistories = allOpportunityHistories
				.Where(history => !string.IsNullOrEmpty(history.Name))
				.Select(history => history.Name + history.PartnerreplacedignedTo + history.Details)
				.Distinct();

			opportunityHistories.AddRange(distinctHistories.Select(uniqueHistory => allOpportunityHistories.FirstOrDefault(history => history.Name + history.PartnerreplacedignedTo + history.Details == uniqueHistory)));

			return opportunityHistories;
		}

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

public static IEnumerable<Enreplacedy> GetContactsForContactByAccountId(this OrganizationServiceContext context, Enreplacedy contact, Guid accountid)
		{
			contact.replacedertEnreplacedyName("contact");

			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var contactAccess = context.GetContactAccessByContact(contact).Where(ca => ca.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false)
				&& ca.GetAttributeValue<OptionSetValue>("adx_scope") != null && ca.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)ContactAccessScope.Account
				&& ca.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && ca.GetAttributeValue<EnreplacedyReference>("adx_accountid").Equals(new EnreplacedyReference("account", accountid)));

			var returnSet = new List<Enreplacedy>();

			foreach (Enreplacedy access in contactAccess)
			{
				var accountcontacts =
					context.CreateQuery("contact").Where(
						c => c.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == access.GetAttributeValue<EnreplacedyReference>("adx_accountid"));

				returnSet.AddRange(accountcontacts);

			}

			return returnSet.AsEnumerable();
		}

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

public static IEnumerable<Enreplacedy> GetAccountAccessByContact(this OrganizationServiceContext context, Enreplacedy contact)
		{
			contact.replacedertEnreplacedyName("contact");

			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var access = context.CreateQuery("adx_accountaccess").Where(aa => aa.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference());

			return access;
		}

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

public IEnumerable<IProduct> SelectProducts(string brand, int? rating, int startRowIndex, int maximumRows, string sortExpression)
		{
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("brand={0}, rating={1}, startRowIndex={2}, maximumRows={3}, sortExpression={4}: Start", brand, rating, startRowIndex, maximumRows, sortExpression));

			if (startRowIndex < 0)
			{
				throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
			}

			if (maximumRows == 0)
			{
				return Enumerable.Empty<IProduct>();
			}

			var serviceContext = Dependencies.GetServiceContext();

			var query = SelectEnreplacedies(serviceContext);

			Guid brandId;

			if (Guid.TryParse(brand, out brandId))
			{
				query = query.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_brand") == new EnreplacedyReference("adx_brand", brandId));
			}

			if (rating.HasValue)
			{
				var minValue = Convert.ToDouble(rating.Value);

				query = query.Where(e => e.GetAttributeValue<double?>("adx_ratingaverage") >= minValue);
			}

			var sorts = ParseSortExpression(string.IsNullOrEmpty(sortExpression) ? DefaultSortExpression : sortExpression);

			query = sorts.Aggregate(query, (current, sort) => sort.Item2 == SortDirection.Ascending
				? current.OrderBy(sort.Item1)
				: current.OrderByDescending(sort.Item1));

			if (startRowIndex > 0)
			{
				query = query.Skip(startRowIndex);
			}

			if (maximumRows > 0)
			{
				query = query.Take(maximumRows);
			}

			var user = Dependencies.GetPortalUser();
			var website = Dependencies.GetWebsite();

			var products = new ProductFactory(serviceContext, user, website).Create(query);

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");

			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
			{
				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Product, HttpContext.Current, "read_product", string.Empty, products.Count(), string.Empty, "read");
			}

			return products;
		}

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

private IEnumerable<ISalesAttachment> SelectSalesAttachments(EnreplacedyReference salesLiterature)
		{
			return _serviceContext.CreateQuery("salesliteratureitem")
				.Where(e => e.GetAttributeValue<EnreplacedyReference>("salesliteratureid") != null && e.GetAttributeValue<EnreplacedyReference>("salesliteratureid").Id == salesLiterature.Id)
				.ToArray()
				.Select(e => new SalesAttachment(e, _website))
				.OrderBy(e => e.FileName)
				.ToArray();
		}

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

private static IQueryable<Enreplacedy> CreateReviewEnreplacedyQuery(OrganizationServiceContext serviceContext, EnreplacedyReference product)
		{
			return serviceContext.CreateQuery("adx_review")
				.Where(review => review.GetAttributeValue<EnreplacedyReference>("adx_product") == product)
				.Where(review => review.GetAttributeValue<OptionSetValue>("statecode") != null && review.GetAttributeValue<OptionSetValue>("statecode").Value == (int)ReviewState.Active)
				.Where(review => review.GetAttributeValue<bool?>("adx_publishtoweb").GetValueOrDefault(false));
		}

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

private static IQueryable<Enreplacedy> CreateProductEnreplacedyQuery(EnreplacedyReference subject, OrganizationServiceContext serviceContext)
		{
			return serviceContext.CreateQuery("product")
				.Where(product => product.GetAttributeValue<EnreplacedyReference>("subjectid") == subject)
				.Where(product => product.GetAttributeValue<OptionSetValue>("statecode") != null && product.GetAttributeValue<OptionSetValue>("statecode").Value == (int)ProductState.Active);
		}

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

private string GetNotesFilterPrefix()
		{
			var prefix =
			_dataContext.CreateQuery("adx_sitesetting")
				.Where(s => s.GetAttributeValue<string>("adx_name") == "KnowledgeManagement/NotesFilter")
				.Select(v => v.GetAttributeValue<string>("adx_value"))
				.FirstOrDefault();

			return prefix ?? string.Empty;
		}

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

protected virtual IQueryable<Enreplacedy> GetSavedQueries(OrganizationServiceContext dataContext)
		{
			return dataContext.CreateQuery("savedquery")
				.Where(e => e.GetAttributeValue<string>("name") == SavedQueryName
					&& e.GetAttributeValue<int?>("statecode") == 0);
		}

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

private static XDoreplacedent GetAttributeLayoutXml(OrganizationServiceContext context, EnreplacedyMetadata metadata, int typeCode)
		{
			var queries = context.CreateQuery("savedquery")
				.Where(e => e.GetAttributeValue<bool?>("isdefault").GetValueOrDefault(false) && e.GetAttributeValue<int>("returnedtypecode") == typeCode)
				.ToList();

			return (
				from queryType in _extendedInfoAttributeQueryTypes
				select queries.FirstOrDefault(e => e.GetAttributeValue<int>("querytype") == queryType)
				into query where query != null
				select XDoreplacedent.Parse(query.GetAttributeValue<string>("layoutxml"))).FirstOrDefault();
		}

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

public static IEnumerable<IEnumerable<Enreplacedy>> GetDoreplacedentLocationPaths(this OrganizationServiceContext context, Enreplacedy enreplacedy)
		{
			if (enreplacedy == null) throw new ArgumentNullException("enreplacedy");

			if (enreplacedy.LogicalName == _sharepointdoreplacedentlocation)
			{
				// return a single path for this doreplacedent location

				var path = GetDoreplacedentLocationPath(context, enreplacedy);

				yield return path;
			}
			else
			{
				// this is an arbitrary enreplacedy, find all doreplacedent locations replacedociated with the enreplacedy

				var locations = context.CreateQuery(_sharepointdoreplacedentlocation)
					.Where(sdl => sdl.GetAttributeValue<EnreplacedyReference>("regardingobjectid") == enreplacedy.ToEnreplacedyReference());

				foreach (var location in locations)
				{
					// return a path for each doreplacedent location

					var path = GetDoreplacedentLocationPath(context, location);

					yield return path;
				}
			}
		}

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

private static Enreplacedy GetDoreplacedentLocation(OrganizationServiceContext context, Enreplacedy enreplacedy, EnreplacedyMetadata enreplacedyMetadata, Enreplacedy spSite)
		{
			var locations = context.CreateQuery(SharePointDoreplacedentLocationLogicalName)
				.Where(docLoc => docLoc.GetAttributeValue<EnreplacedyReference>("regardingobjectid").Id == enreplacedy.Id && docLoc.GetAttributeValue<int>("statecode") == 0)
				.OrderBy(docLoc => docLoc.GetAttributeValue<DateTime>("createdon"))
				.ToArray();

			Enreplacedy location;

			if (locations.Count() > 1)
			{
				// Multiple doc locations found, choose the first created.
				location = locations.First();
			}
			else if (locations.Count() == 1)
			{
				location = locations.First();
			}
			else
			{
				// No doreplacedent locations found, create an auto-generated one.
				var autoGeneratedRelativeUrl = "{0}_{1}".FormatWith(
					enreplacedy.GetAttributeValue<string>(enreplacedyMetadata.PrimaryNameAttribute),
					enreplacedy.Id.ToString("N").ToUpper());

				location = context.AddOrGetExistingDoreplacedentLocationAndSave<Enreplacedy>(spSite, enreplacedy, autoGeneratedRelativeUrl);
			}

			if (location == null)
			{
				throw new Exception("A doreplacedent location couldn't be found or created for the enreplacedy.");
			}

			return location;
		}

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

public static Enreplacedy GetSharePointSiteFromUrl(this OrganizationServiceContext context, Uri absoluteUrl)
		{
			var sharePointSites = context.CreateQuery("sharepointsite").Where(site => site.GetAttributeValue<int?>("statecode") == 0).ToArray(); // all active sites

			var siteUrls = new Dictionary<Guid, string>();

			foreach (var sharePointSite in sharePointSites)
			{
				var siteUrl = sharePointSite.GetAttributeValue<string>("absoluteurl") ?? string.Empty;

				var parentSiteReference = sharePointSite.GetAttributeValue<EnreplacedyReference>("parentsite");

				if (parentSiteReference != null)
				{
					var parentSite = sharePointSites.FirstOrDefault(site => site.Id == parentSiteReference.Id);

					if (parentSite != null)
					{
						siteUrl = "{0}/{1}".FormatWith(parentSite.GetAttributeValue<string>("absoluteurl").TrimEnd('/'), sharePointSite.GetAttributeValue<string>("relativeurl"));
					}
				}

				siteUrls.Add(sharePointSite.Id, siteUrl);
			}

			var siteKeyAndUrl = siteUrls.Select(pair => pair as KeyValuePair<Guid, string>?)
				.FirstOrDefault(pair => string.Equals(pair.Value.Value.TrimEnd('/'), absoluteUrl.ToString().TrimEnd('/'), StringComparison.InvariantCultureIgnoreCase));

			if (siteKeyAndUrl == null)
			{
				throw new ApplicationException("Couldn't find an active SharePoint site with the URL {0}.".FormatWith(absoluteUrl));
			}

			return sharePointSites.First(site => site.Id == siteKeyAndUrl.Value.Key);
		}

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

public override IEnumerable<Tuple<Enreplacedy, EnreplacedyReference>> GetTreeParents(OrganizationServiceContext serviceContext, EnreplacedyReference website)
		{
			if (serviceContext == null) throw new ArgumentNullException("serviceContext");
			if (website == null) throw new ArgumentNullException("website");

			try
			{
				return serviceContext.CreateQuery("adx_blog")
					.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website)
					.ToArray()
					.Select(e => new Tuple<Enreplacedy, EnreplacedyReference>(e, e.GetAttributeValue<EnreplacedyReference>("adx_parentpageid")));
			}
			catch (FaultException<OrganizationServiceFault>)
			{
				return new Tuple<Enreplacedy, EnreplacedyReference>[] { };
			}
		}

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

protected override void ProcessRequest(HttpContext context, ICmsEnreplacedyServiceProvider serviceProvider, Guid portalScopeId, IPortalContext portal, OrganizationServiceContext serviceContext, EnreplacedyReference enreplacedyReference)
		{
			var enreplacedyMetadata = new CmsEnreplacedyMetadata(serviceContext, enreplacedyReference.LogicalName);

			var query = serviceContext.CreateQuery(enreplacedyReference.LogicalName);

			// If the target enreplacedy is scoped to a website, filter the query by the current website.
			if (enreplacedyMetadata.HasAttribute("adx_websiteid"))
			{
				query = query.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == portal.Website.ToEnreplacedyReference());
			}

			var enreplacedy = query.FirstOrDefault(e => e.GetAttributeValue<Guid>(enreplacedyMetadata.PrimaryIdAttribute) == enreplacedyReference.Id);

			if (enreplacedy == null)
			{
				throw new CmsEnreplacedyServiceException(HttpStatusCode.NotFound, "Enreplacedy not found.");
			}

			var security = PortalCrmConfigurationManager.CreateCrmEnreplacedySecurityProvider(PortalName);

			if (!security.Tryreplacedert(serviceContext, enreplacedy, CrmEnreplacedyRight.Read))
			{
				throw new CmsEnreplacedyServiceException(HttpStatusCode.Forbidden, "Enreplacedy access denied.");
			}

			var url = serviceContext.GetUrl(enreplacedy);

			if (url == null)
			{
				throw new CmsEnreplacedyServiceException(HttpStatusCode.NotFound, "URL for enreplacedy not found.");
			}

			WriteResponse(context.Response, new JObject
			{
				{ "d",  new JObject { { "Url", new JValue(url) } } }
			});
		}

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

public static IEnumerable<Enreplacedy> GetOpportunityAccessByContact(this OrganizationServiceContext context, Enreplacedy contact)
		{
			contact.replacedertEnreplacedyName("contact");

			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var access = context.CreateQuery("adx_opportunitypermissions").Where(oa => oa.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference());

			return access;
		}

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

public static IEnumerable<Enreplacedy> GetOpportunityAccessByContactForParentAccount(this OrganizationServiceContext context, Enreplacedy contact)
		{
			contact.replacedertEnreplacedyName("contact");

			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var access = context.CreateQuery("adx_opportunitypermissions")
				.Where(oa => oa.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference()
						&& oa.GetAttributeValue<EnreplacedyReference>("adx_accountid") == contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid")
						&& oa.GetAttributeValue<OptionSetValue>("adx_scope") != null && oa.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)OpportunityAccessScope.Account);

			return access;
		}

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

public static IEnumerable<Enreplacedy> GetContactAccessByContact(this OrganizationServiceContext context, Enreplacedy contact)
		{
			contact.replacedertEnreplacedyName("contact");

			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			var access = context.CreateQuery("adx_contactaccess").Where(ca => ca.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference());

			return access;
		}

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

public override IEnumerable<Tuple<Enreplacedy, EnreplacedyReference>> GetTreeParents(OrganizationServiceContext serviceContext, EnreplacedyReference website)
		{
			if (serviceContext == null) throw new ArgumentNullException("serviceContext");
			if (website == null) throw new ArgumentNullException("website");

			return serviceContext.CreateQuery("adx_webpage")
				.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website)
				.ToArray()
				.Select(e => new Tuple<Enreplacedy, EnreplacedyReference>(e, e.GetAttributeValue<EnreplacedyReference>("adx_parentpageid")));
		}

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

public Enreplacedy ExecuteEnreplacedyQuery(HttpContext context, IPortalContext portal, OrganizationServiceContext serviceContext, EnreplacedyReference enreplacedyReference, CmsEnreplacedyMetadata enreplacedyMetadata)
		{
			if (context == null)
			{
				throw new ArgumentNullException("context");
			}

			if (portal == null)
			{
				throw new ArgumentNullException("portal");
			}

			if (serviceContext == null)
			{
				throw new ArgumentNullException("serviceContext");
			}

			if (enreplacedyReference == null)
			{
				throw new ArgumentNullException("enreplacedyReference");
			}

			if (enreplacedyMetadata == null)
			{
				throw new ArgumentNullException("enreplacedyMetadata");
			}

			var website = portal.Website.ToEnreplacedyReference();

			WebsiteJoin websiteJoin;

			if (WebsiteJoins.TryGetValue(enreplacedyReference.LogicalName, out websiteJoin))
			{
				return (
					from referencing in serviceContext.CreateQuery(websiteJoin.ReferencingEnreplacedy)
					join referenced in serviceContext.CreateQuery(websiteJoin.ReferencedEnreplacedy) on referencing.GetAttributeValue<EnreplacedyReference>(websiteJoin.ReferencingAttribute) equals referenced.GetAttributeValue<EnreplacedyReference>(websiteJoin.ReferencedAttribute)
					where referenced.GetAttributeValue<EnreplacedyReference>(websiteJoin.WebsiteReferenceAttribute) == website
					where referencing.GetAttributeValue<Guid>(enreplacedyMetadata.PrimaryIdAttribute) == enreplacedyReference.Id
					select referencing).FirstOrDefault();
			}

			var query = serviceContext.CreateQuery(enreplacedyReference.LogicalName);

			// If the target enreplacedy is scoped to a website, filter the query by the current website.
			if (enreplacedyMetadata.HasAttribute("adx_websiteid"))
			{
				query = query.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == portal.Website.ToEnreplacedyReference());
			}

			return query.FirstOrDefault(e => e.GetAttributeValue<Guid>(enreplacedyMetadata.PrimaryIdAttribute) == enreplacedyReference.Id);
		}

See More Examples