Microsoft.Xrm.Sdk.Entity.GetAttributeValue(string)

Here are the examples of the csharp api Microsoft.Xrm.Sdk.Entity.GetAttributeValue(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

748 Examples 7

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

private PageCommentPolicy? GetParentPagePolicy()
		{
			if (_webPage.GetAttributeValue<EnreplacedyReference>("adx_parentpageid") == null)
			{
				return null;
			}

			var enreplacedyRef = _webPage.GetAttributeValue<EnreplacedyReference>("adx_parentpageid");
			var portalOrgService = HttpContext.Current.GetOrganizationService();
			var parentPage = portalOrgService.RetrieveSingle(
				enreplacedyRef.LogicalName,
				FetchAttribute.None,
				new Condition("adx_webpageid", ConditionOperator.Equal, enreplacedyRef.Id));

			if (parentPage == null)
			{
				return null;
			}

			var parentPolicyReader = new PageCommentPolicyReader(parentPage);

			return parentPolicyReader.Policy;
		}

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

private void IncrementVoteCount(OrganizationServiceContext serviceContext, IPollOption pollOption)
		{
			var option = serviceContext.CreateQuery("adx_polloption")
				.FirstOrDefault(o => o.GetAttributeValue<Guid>("adx_polloptionid") == pollOption.Enreplacedy.Id);

			if (option == null)
			{
				throw new InvalidOperationException("Unable to retrieve the current poll option.");
			}

			int? voteCount = option.GetAttributeValue<int?>("adx_votes") ?? 0;

			option.SetAttributeValue("adx_votes", (voteCount + 1));

			serviceContext.UpdateObject(option);
		}

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

private IPoll CreatePoll(Enreplacedy enreplacedy, OrganizationServiceContext serviceContext)
		{
			var user = Dependencies.GetPortalUser();
			var anon = Dependencies.GetRequestContext().HttpContext.Profile.UserName;

			var poll = new Poll(enreplacedy);

			poll.Options = enreplacedy.GetRelatedEnreplacedies(serviceContext, new Relationship("adx_poll_polloption"))
				.Select(e => CreatePollOption(poll, e));

			var submitted = enreplacedy.GetRelatedEnreplacedies(serviceContext, new Relationship("adx_poll_pollsubmission"))
				.FirstOrDefault(e => user != null
					&& user.LogicalName == "contact"
					&& e.GetAttributeValue<EnreplacedyReference>("adx_contactid") != null
					? e.GetAttributeValue<EnreplacedyReference>("adx_contactid").Id == user.Id
					: e.GetAttributeValue<string>("adx_visitorid") == anon);

			poll.UserSelectedOption = submitted != null
				? new PollOption(submitted.GetRelatedEnreplacedy(serviceContext, "adx_polloption_pollsubmission"), poll)
				: null;

			return poll;
		}

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

private IPollPlacement CreatePollPlacement(Enreplacedy enreplacedy, OrganizationServiceContext serviceContext)
		{
			var polls = enreplacedy.GetRelatedEnreplacedies(serviceContext, new Relationship("adx_pollplacement_poll"))
				.Where(e => ((DateTime.Compare(e.GetAttributeValue<DateTime?>("adx_releasedate") ?? DateTime.UtcNow,
					DateTime.UtcNow.AddDays(1))) <= 0
					&& (DateTime.Compare(e.GetAttributeValue<DateTime?>("adx_expirationdate") ?? DateTime.UtcNow,
						DateTime.UtcNow)) >= 0))
				.Where(IsActive)
				.Select(e => CreatePoll(e, serviceContext));

			var pollPlacement = new PollPlacement(enreplacedy, polls);

			return pollPlacement;
		}

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

protected override bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy enreplacedy, CrmEnreplacedyRight right, CrmEnreplacedyCacheDependencyTrace dependencies, ContentMap map)
		{
			if (enreplacedy == null || right == CrmEnreplacedyRight.Change)
			{
				return false;
			}

			dependencies.AddEnreplacedyDependency(enreplacedy);
			dependencies.AddEnreplacedySetDependency("adx_webrole");
			dependencies.AddEnreplacedySetDependency("adx_websiteaccess");

			var enreplacedyName = enreplacedy.LogicalName;

			var releaseDate = DateTime.MinValue;
			var expiryDate = DateTime.MaxValue;

			if (enreplacedyName == "adx_webpage" ||
				enreplacedyName == "adx_webfile" ||
				enreplacedyName == "adx_event" ||
				enreplacedyName == "adx_survey" ||
				enreplacedyName == "adx_ad")
			{
				releaseDate = enreplacedy.GetAttributeValue<DateTime?>("adx_releasedate").GetValueOrDefault(DateTime.MinValue);
				expiryDate = enreplacedy.GetAttributeValue<DateTime?>("adx_expirationdate").GetValueOrDefault(DateTime.MaxValue);
			}
			else if (enreplacedyName == "adx_weblink")
			{
				if (!enreplacedy.GetAttributeValue<bool?>("adx_disablepagevalidation").GetValueOrDefault(false))
				{
					var pageReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_pageid");

					if (pageReference != null)
					{
						WebPageNode rootPage;
						if (map.TryGetValue(pageReference, out rootPage))
						{
							var weblinkWebPage = HttpContext.Current.GetContextLanguageInfo().FindLanguageSpecificWebPageNode(rootPage, false);

							if (weblinkWebPage != null)
							{
								return Tryreplacedert(context, weblinkWebPage.ToEnreplacedy(), right, dependencies);
							}
						}
					}
				}

				return true;
			}
			else if (enreplacedyName == "adx_shortcut")
			{
				if (!enreplacedy.GetAttributeValue<bool?>("adx_disabletargetvalidation").GetValueOrDefault(false))
				{

					var pageReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_webpageid");
					var webFileReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_webfileid");

					if (pageReference != null)
					{
						WebPageNode rootPage;
						if (map.TryGetValue(pageReference, out rootPage))
						{
							var shortcutWebPage = HttpContext.Current.GetContextLanguageInfo().FindLanguageSpecificWebPageNode(rootPage, false);

							if (shortcutWebPage != null)
							{
								return Tryreplacedert(context, shortcutWebPage.ToEnreplacedy(), right, dependencies);
							}
						}
					}
					else if (webFileReference != null)
					{
						WebFileNode webFile;
						if (map.TryGetValue(webFileReference, out webFile))
						{
							return Tryreplacedert(context, webFile.ToEnreplacedy(), right, dependencies);
						}
					}
				}

				var parentPageReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_parentpage_webpageid");

				if (parentPageReference != null)
				{
					WebPageNode rootPage;
					if (map.TryGetValue(parentPageReference, out rootPage))
					{
						var parentPage = HttpContext.Current.GetContextLanguageInfo().FindLanguageSpecificWebPageNode(rootPage, false);

						return Tryreplacedert(context, parentPage.ToEnreplacedy(), right, dependencies);
					}

				}

				return true;
			}

			return UserCanPreview(context, enreplacedy) || InnerTryreplacedert(releaseDate, expiryDate);
		}

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

public override bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy enreplacedy, CrmEnreplacedyRight right, CrmEnreplacedyCacheDependencyTrace dependencies)
			{
				if (enreplacedy == null || right == CrmEnreplacedyRight.Change)
				{
					return false;
				}

				dependencies.AddEnreplacedyDependency(enreplacedy);
				dependencies.AddEnreplacedySetDependency("adx_webrole");
				dependencies.AddEnreplacedySetDependency("adx_webrole_contact");
				dependencies.AddEnreplacedySetDependency("adx_webrole_account");
				dependencies.AddEnreplacedySetDependency("adx_websiteaccess");

				var enreplacedyName = enreplacedy.LogicalName;

				// Weblinks require some special handling.
				if (enreplacedyName == "adx_weblink")
				{
					var weblinkPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_weblink");

					// If a weblink has a publishing state, and that state is not visible, state access is
					// denied (unless the user can preview).
					if (weblinkPublishingState != null && !weblinkPublishingState.GetAttributeValue<bool?>("adx_isvisible").GetValueOrDefault())
					{
						dependencies.AddEnreplacedyDependency(weblinkPublishingState);

						return UserCanPreview(context, enreplacedy);
					}

					var weblinkPage = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_webpage_weblink");
						
					// If a weblink has an replacedociated page, and page validation is not disabled, return the
					// result of replacedertion on that page.
					if (weblinkPage != null && !enreplacedy.GetAttributeValue<bool?>("adx_disablepagevalidation").GetValueOrDefault(false))
					{
						return Tryreplacedert(context, weblinkPage, right, dependencies);
					}
				}

				if (enreplacedyName == "adx_idea")
				{
					return enreplacedy.GetAttributeValue<bool?>("adx_approved").GetValueOrDefault(false);
				}

				if (enreplacedyName == "adx_ideacomment")
				{
					return enreplacedy.GetAttributeValue<bool?>("adx_approved").GetValueOrDefault(false);
				}

				EnreplacedyReference publishingStateReference = null;
				Enreplacedy enreplacedyPublishingState = null;

				switch (enreplacedyName)
				{
					case "adx_webpage":
						publishingStateReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid");
						break;
					case "adx_weblinkset":
						publishingStateReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid");
						break;
					case "adx_webfile":
						publishingStateReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid");
						break;
					case "adx_communityforum":
						publishingStateReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid");
						break;
					case "adx_communityforumpost":
						publishingStateReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid");
						break;
					case "adx_ad":
						publishingStateReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid");
						break;

					// legacy enreplacedies
					case "adx_event":
						enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_event");
						break;
					case "adx_eventschedule":
						enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_eventschedule");
						break;
					case "adx_eventspeaker":
						enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_eventspeaker");
						break;
					case "adx_eventsponsor":
						enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_eventsponsor");
						break;
					case "adx_survey":
						enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_survey");
						break;
				}

				if (publishingStateReference != null)
				{
					enreplacedyPublishingState = context.RetrieveSingle(
						"adx_publishingstate",
						new[] { "adx_isvisible" },
						new Condition("adx_publishingstateid", ConditionOperator.Equal, publishingStateReference.Id));
				}

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

				dependencies.AddEnreplacedyDependency(enreplacedyPublishingState);

				if (enreplacedyPublishingState.GetAttributeValue<bool?>("adx_isvisible").GetValueOrDefault())
				{
					return true;
				}

				return UserCanPreview(context, enreplacedyPublishingState);
			}

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

public static Enreplacedy CreateSupportPlan(decimal total, IPortalContext portal, OrganizationServiceContext context,
			Enreplacedy uom, Enreplacedy contact, Enreplacedy product, Enreplacedy account)
		{
			var supportPlanId = Guid.NewGuid();

			var supportPlan = new Enreplacedy("adx_supportplan") { Id = supportPlanId };

			supportPlan.Attributes["adx_supportplanid"] = supportPlanId;

			var siteSettingStringFormat = context.GetSiteSettingValueByName(portal.Website, "HelpDesk/SupportPlanNameFormat");
			var contactName = string.Empty;
			var accountName = string.Empty;

			if (account != null)
			{
				supportPlan.Attributes["adx_customer"] = account.ToEnreplacedyReference();
				supportPlan.Attributes["adx_billtocustomer"] = account.ToEnreplacedyReference();
				accountName = account.GetAttributeValue<string>("name");
			}
			else if (contact != null)
			{
				supportPlan.Attributes["adx_customercontact"] = contact.ToEnreplacedyReference();
				contactName = contact.GetAttributeValue<string>("fullname");
			}

			supportPlan.Attributes["adx_name"] = !string.IsNullOrWhiteSpace(siteSettingStringFormat)
															? string.Format(siteSettingStringFormat,
																			accountName,
																			contactName,
																			DateTime.UtcNow)
															: string.Format(ResourceManager.GetString("Support_Plan_For_Purchased"),
																			accountName,
																			contactName,
																			DateTime.UtcNow);

			supportPlan.Attributes["adx_startdate"] = DateTime.UtcNow;

			supportPlan.Attributes["adx_enddate"] = DateTime.UtcNow.AddYears(1);

			if (product != null)
			{
				supportPlan.Attributes["adx_product"] = product.ToEnreplacedyReference();
			}

			supportPlan.Attributes["adx_totalprice"] = new Money(total);

			if (uom != null)
			{
				supportPlan.Attributes["adx_allotmentsused"] = 0;
				supportPlan.Attributes["adx_allotmentsissued"] = (int)uom.GetAttributeValue<decimal>("quanreplacedy");
				supportPlan.Attributes["adx_allotmentsremaining"] = (int)uom.GetAttributeValue<decimal>("quanreplacedy");
			}

			try
			{
				context.AddObject(supportPlan);

				context.SaveChanges();
			}
			catch
			{

			}

			supportPlan = context.CreateQuery("adx_supportplan")
				.FirstOrDefault(sr => sr.GetAttributeValue<Guid>("adx_supportplanid") == supportPlanId);
			return supportPlan;
		}

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

public static void UpdateSupportRequest(out Enreplacedy supportRequest, Enreplacedy supportPlan, Guid supportRequestId,
			OrganizationServiceContext context)
		{

			supportRequest = context.CreateQuery("adx_supportrequest")
				.FirstOrDefault(sr => sr.GetAttributeValue<Guid>("adx_supportrequestid") == supportRequestId);

			supportRequest.Attributes["adx_supportplan"] = supportPlan.ToEnreplacedyReference();

			context.UpdateObject(supportRequest);

			context.SaveChanges();
		}

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

private void CreateOrderPayPal(Dictionary<string, string> values, IPortalContext xrm, bool getCreateInvoiceSettingValue)
		{
			System.Diagnostics.Debug.Write("A commerce order is being created...");

			_context = xrm.ServiceContext;

			if (!values.ContainsKey("invoice"))
			{
				throw new Exception("no invoice found");
			}

			var shoppingCart =
				_context.CreateQuery("adx_shoppingcart").FirstOrDefault(
					q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"]));

			var order = new Enreplacedy("salesorder");

			var orderGuid = Guid.NewGuid();

			order.Attributes["salesorderid"] = orderGuid;
			order.Id = orderGuid;

			order.Attributes["name"] = "order created by: " + shoppingCart.GetAttributeValue<string>("adx_name");

			order.Attributes["adx_shoppingcartid"] = shoppingCart.ToEnreplacedyReference();

			System.Diagnostics.Debug.Write(string.Format("shopping cart ID:{0}", shoppingCart.Id.ToString()));

			var supportRequest = _context.CreateQuery("adx_supportrequest")
					.FirstOrDefault(sr => sr.GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid").Id == shoppingCart.Id);
			if (supportRequest != null)
			{
				System.Diagnostics.Debug.Write(string.Format("Support Request ID:{0}", supportRequest.Id.ToString()));

				var supportPlanReference = supportRequest.GetAttributeValue<EnreplacedyReference>("adx_supportplan");

				System.Diagnostics.Debug.Write(string.Format("Support Reference:{0}", supportPlanReference));

				var supportPlan = _context.CreateQuery("adx_supportplan").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_supportplanid")
							== supportPlanReference.Id);

				order.Attributes["adx_supportplanid"] = supportPlan.ToEnreplacedyReference();
			}
			else
			{
				System.Diagnostics.Debug.Write("support request is null");
			}

			//Ensure that there is a customer
			var customer = GetOrderCustomer(values, _context, shoppingCart);

			if (!_context.IsAttached(shoppingCart))
			{
				_context.Attach(shoppingCart);
			}

			shoppingCart.Attributes["adx_contactid"] = customer.ToEnreplacedyReference();

			var parentCustomer = customer.GetAttributeValue<EnreplacedyReference>("parentcustomerid");

			var parentCustomerEnreplacedy =
				_context.CreateQuery("account").FirstOrDefault(pce => pce.GetAttributeValue<Guid>("accountid") == parentCustomer.Id);

			order.Attributes["customerid"] = (parentCustomerEnreplacedy != null) ? parentCustomerEnreplacedy.ToEnreplacedyReference() : customer.ToEnreplacedyReference();

			var priceLevel =
				_context.CreateQuery("pricelevel").FirstOrDefault(pl => pl.GetAttributeValue<string>("name") == "Web");

			if (priceLevel == null)
			{
				throw new Exception("price level null");
			}

			//Set the price level
			var priceLevelReference = priceLevel.ToEnreplacedyReference();

			order.Attributes["pricelevelid"] = priceLevelReference;

			//Set the address for the order
			SetOrderAddresses(values, order, customer);

			//order.Attributes["adx_confirmationnumber"] = shoppingCart.GetAttributeValue<string>("adx_confirmationnumber");
			order.Attributes["adx_receiptnumber"] = values.ContainsKey("ipn_trac_id") ? values["ipn_track_id"] : null;

			_context.AddObject(order);

			_context.UpdateObject(shoppingCart);

			_context.SaveChanges();

			//Set the products of the order
			SetOrderProducts(shoppingCart, _context, orderGuid, null);


			//Time to replacedociate order with support plan

			//sw.WriteLine("ok, we are at the weird part!");


			//Deactivate the shopping Cart
			shoppingCart =
				_context.CreateQuery("adx_shoppingcart").FirstOrDefault(
					q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"]));


			try
			{
				_context.SetState(1, 2, shoppingCart);
				_context.SaveChanges();
			}
			catch
			{
				//Unlikely that there is an issue, most likely it has already been deactiveated.
			}

			//At this point we want to Create an Invoice, if that is indeed what we are doing.

			if (getCreateInvoiceSettingValue)
			{
				InvoiceEnreplacedy = CreateInvoiceFromOrder(_context, orderGuid);
			}

			Enreplacedy = _context.CreateQuery("salesorder").FirstOrDefault(o => o.GetAttributeValue<Guid>("salesorderid") == orderGuid);
			Id = Enreplacedy.Id;
		}

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

private void CreateOrderAuthorizeNet(Dictionary<string, string> values,
			IPortalContext xrm,
			bool getCreateInvoiceSettingValue,
			Enreplacedy account = null,
			string tombstoneEnreplacedyLogicalName = null,
			string tombstoneEnreplacedyPrimaryKeyName = null)
		{
			_context = xrm.ServiceContext;

			if (!values.ContainsKey("order_id"))
			{
				throw new Exception("no order_id found");
			}

			var orderId = values["order_id"];

			string[] guids = orderId.Split('&');

			var tombstoneEnreplacedyId = new Guid(guids[0]);

			Enreplacedy tombstoneEnreplacedy = null; Enreplacedy shoppingCart = null; Enreplacedy supportPlan = null;



			if (tombstoneEnreplacedyLogicalName != null)
			{
				tombstoneEnreplacedy = _context.CreateQuery(tombstoneEnreplacedyLogicalName)
					.FirstOrDefault(sr => sr.GetAttributeValue<Guid>(tombstoneEnreplacedyPrimaryKeyName) == tombstoneEnreplacedyId);

				shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_shoppingcartid") ==
							tombstoneEnreplacedy.GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid").Id);

			}
			else
			{
				shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_shoppingcartid") ==
							tombstoneEnreplacedyId);
			}

			if (tombstoneEnreplacedyLogicalName == "adx_supportrequest")
			{
				supportPlan = _context.CreateQuery("adx_supportplan").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_supportplanid")
								== tombstoneEnreplacedy.GetAttributeValue<EnreplacedyReference>("adx_supportplan").Id);
			}


			var orderGuid = Guid.NewGuid();

			var order = new Enreplacedy("salesorder") { Id = orderGuid };

			order.Attributes["salesorderid"] = orderGuid;
			order.Id = orderGuid;

			order.Attributes["name"] = "order created by: " + shoppingCart.GetAttributeValue<string>("adx_name");

			order.Attributes["adx_shoppingcartid"] = shoppingCart.ToEnreplacedyReference();

			if (tombstoneEnreplacedyLogicalName == "adx_supportrequest")
			{
				order.Attributes["adx_supportplanid"] = supportPlan.ToEnreplacedyReference();
			}

			//Ensure that there is a customer
			var customer = GetOrderCustomer(values, _context, shoppingCart);

			if (!_context.IsAttached(shoppingCart))
			{
				_context.Attach(shoppingCart);
			}

			shoppingCart.Attributes["adx_contactid"] = customer.ToEnreplacedyReference();

			if (account == null)
			{
				var parentCustomer = customer.GetAttributeValue<EnreplacedyReference>("parentcustomerid");

				Enreplacedy parentCustomerEnreplacedy = null;

				if (parentCustomer != null)
				{
					parentCustomerEnreplacedy =
					_context.CreateQuery("account").FirstOrDefault(pce => pce.GetAttributeValue<Guid>("accountid") == parentCustomer.Id);
				}

				order.Attributes["customerid"] = (parentCustomerEnreplacedy != null) ? parentCustomerEnreplacedy.ToEnreplacedyReference() : customer.ToEnreplacedyReference();
			}
			else
			{
				order.Attributes["customerid"] = account.ToEnreplacedyReference();
			}

			var priceLevel =
				_context.CreateQuery("pricelevel").FirstOrDefault(pl => pl.GetAttributeValue<string>("name") == "Web");

			if (priceLevel == null)
			{
				throw new Exception("price level null");
			}

			//Set the price level
			var priceLevelReference = priceLevel.ToEnreplacedyReference();

			order.Attributes["pricelevelid"] = priceLevelReference;

			//Set the address for the order
			SetOrderAddresses(values, order, customer);

			//order.Attributes["adx_confirmationnumber"] = shoppingCart.GetAttributeValue<string>("adx_confirmationnumber");
			order.Attributes["adx_receiptnumber"] = values.ContainsKey("x_trans_id") ? values["x_trans_id"] : null;

			//Set the tax 
			//order.Attributes["totaltax"] = values.ContainsKey("x_tax")	? new Money(decimal.Parse(values["x_tax"]))	: null;
			var tax = values.ContainsKey("x_tax") ? new Money(decimal.Parse(values["x_tax"])) : null;

			_context.AddObject(order);

			_context.UpdateObject(shoppingCart);

			_context.SaveChanges();

			//Set the products of the order
			SetOrderProducts(shoppingCart, _context, orderGuid, tax);

			tombstoneEnreplacedy = _context.CreateQuery(tombstoneEnreplacedyLogicalName)
					.FirstOrDefault(sr => sr.GetAttributeValue<Guid>(tombstoneEnreplacedyPrimaryKeyName) == tombstoneEnreplacedyId);

			shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_shoppingcartid")
							== tombstoneEnreplacedy.GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid").Id);

			//Deactivate the shopping Cart

			try
			{
				_context.SetState(1, 2, shoppingCart);
				_context.SaveChanges();
			}
			catch
			{
				//Unlikely that there is an issue, most likely it has already been deactiveated.
			}

			//At this point we want to Create an Invoice, if that is indeed what we are doing.

			if (getCreateInvoiceSettingValue)
			{
				InvoiceEnreplacedy = CreateInvoiceFromOrder(_context, orderGuid);
			}

			Enreplacedy = _context.CreateQuery("salesorder").FirstOrDefault(o => o.GetAttributeValue<Guid>("salesorderid") == orderGuid);
			Id = Enreplacedy.Id;

			//writer.Close();
		}

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 : CommerceOrder.cs
License : MIT License
Project Creator : Adoxio

private static void SetOrderAddresses(Dictionary<string, string> values, Enreplacedy order, Enreplacedy customer)
		{
			order.Attributes["billto_line1"] = customer.GetAttributeValue<string>("address1_line1");
			order.Attributes["billto_city"] = customer.GetAttributeValue<string>("address1_city");
			order.Attributes["billto_country"] = customer.GetAttributeValue<string>("address1_country");
			order.Attributes["billto_stateorprovince"] = customer.GetAttributeValue<string>("address1_stateorprovince");
			order.Attributes["billto_postalcode"] = customer.GetAttributeValue<string>("address1_postalcode");

			order.Attributes["shipto_line1"] = (values.ContainsKey("address_street") ? values["address_street"] : null) ??
				(values.ContainsKey("x_address") ? values["x_address"] : null) ??
				(values.ContainsKey("address1") ? values["address1"] : null) ?? customer.GetAttributeValue<string>("address1_line1");
			order.Attributes["shipto_city"] = (values.ContainsKey("address_city") ? values["address_city"] : null) ??
				(values.ContainsKey("x_city") ? values["x_city"] : null) ??
				(values.ContainsKey("city") ? values["city"] : null) ?? customer.GetAttributeValue<string>("address1_city");
			order.Attributes["shipto_country"] = (values.ContainsKey("address_country") ? values["address_country"] : null) ??
				(values.ContainsKey("x_country") ? values["x_country"] : null) ??
				(values.ContainsKey("country") ? values["country"] : null) ?? customer.GetAttributeValue<string>("address1_country");
			order.Attributes["shipto_stateorprovince"] = (values.ContainsKey("address_state") ? values["address_state"] : null) ??
				(values.ContainsKey("x_state") ? values["x_state"] : null) ??
				(values.ContainsKey("state") ? values["state"] : null) ?? customer.GetAttributeValue<string>("address1_stateorprovince");
			order.Attributes["shipto_postalcode"] = (values.ContainsKey("address_zip") ? values["address_zip"] : null) ??
				(values.ContainsKey("x_zip") ? values["x_zip"] : null) ??
				(values.ContainsKey("zip") ? values["zip"] : null) ?? customer.GetAttributeValue<string>("address1_postalcode");
		}

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

private void CreateQuotePayPal(Dictionary<string, string> values, IPortalContext xrm)
		{
			_context = xrm.ServiceContext;

			if (!values.ContainsKey("invoice"))
			{
				throw new Exception("no invoice found");
			}

			var shoppingCart =
				_context.CreateQuery("adx_shoppingcart").FirstOrDefault(
					q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"]));

			var quote = new Enreplacedy("quote");

			var orderGuid = Guid.NewGuid();

			quote.Attributes["quoteid"] = orderGuid;
			quote.Id = orderGuid;

			quote.Attributes["name"] = "quote created by: " + shoppingCart.GetAttributeValue<string>("adx_name");

			quote.Attributes["adx_shoppingcartid"] = shoppingCart.ToEnreplacedyReference();

			//Ensure that there is a customer
			var customer = GetQuoteCustomer(values, _context, shoppingCart);

			if (!_context.IsAttached(shoppingCart))
			{
				_context.Attach(shoppingCart);
			}

			shoppingCart.Attributes["adx_contactid"] = customer.ToEnreplacedyReference();

			quote.Attributes["customerid"] = customer.ToEnreplacedyReference();

			var priceLevel =
				_context.CreateQuery("pricelevel").FirstOrDefault(pl => pl.GetAttributeValue<string>("name") == "Web");

			if (priceLevel == null)
			{
                throw new Exception("price level null");
			}

			//Set the price level
			var priceLevelReference = priceLevel.ToEnreplacedyReference();

			quote.Attributes["pricelevelid"] = priceLevelReference;

			//Set the address for the order
			SetQuoteAddresses(values, quote, customer);

			//order.Attributes["adx_confirmationnumber"] = shoppingCart.GetAttributeValue<string>("adx_confirmationnumber");
			//order.Attributes["adx_receiptnumber"] = values.ContainsKey("ipn_trac_id") ? values["ipn_track_id"] : null;

			_context.AddObject(quote);

			_context.UpdateObject(shoppingCart);

			_context.SaveChanges();

			//Set the products of the order
			SetQuoteProducts(shoppingCart, _context, orderGuid);


			//Deactivate the shopping Cart
			shoppingCart =
				_context.CreateQuery("adx_shoppingcart").FirstOrDefault(
					q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"]));

			try
			{
				_context.SetState(1, 2, shoppingCart);
				_context.SaveChanges();
			}
			catch
			{
				//Unlikely that there is an issue, most likely it has already been deactiveated.
			}

			Enreplacedy = _context.CreateQuery("quote").FirstOrDefault(o => o.GetAttributeValue<Guid>("quoteid") == orderGuid);
			Id = Enreplacedy.Id;
		}

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 : CommerceQuote.cs
License : MIT License
Project Creator : Adoxio

private static void SetQuoteAddresses(Dictionary<string, string> values, Enreplacedy quote, Enreplacedy customer)
		{
			quote.Attributes["billto_line1"] = customer.GetAttributeValue<string>("address1_line1");
			quote.Attributes["billto_city"] = customer.GetAttributeValue<string>("address1_city");
			quote.Attributes["billto_country"] = customer.GetAttributeValue<string>("address1_country");
			quote.Attributes["billto_stateorprovince"] = customer.GetAttributeValue<string>("address1_stateorprovince");
			quote.Attributes["billto_postalcode"] = customer.GetAttributeValue<string>("address1_postalcode");

			quote.Attributes["shipto_line1"] = (values.ContainsKey("address_street") ? values["address_street"] : null) ??
				(values.ContainsKey("address1") ? values["address1"] : null) ?? customer.GetAttributeValue<string>("address1_line1");
			quote.Attributes["shipto_city"] = (values.ContainsKey("address_street") ? values["address_city"] : null) ??
				(values.ContainsKey("city") ? values["city"] : null) ?? customer.GetAttributeValue<string>("address1_city");
			quote.Attributes["shipto_country"] = (values.ContainsKey("address_street") ? values["address_country"] : null) ??
				(values.ContainsKey("country") ? values["country"] : null) ?? customer.GetAttributeValue<string>("address1_country");
			quote.Attributes["shipto_stateorprovince"] = (values.ContainsKey("address_street") ? values["address_state"] : null) ??
				(values.ContainsKey("state") ? values["state"] : null) ?? customer.GetAttributeValue<string>("address1_stateorprovince");
			quote.Attributes["shipto_postalcode"] = (values.ContainsKey("address_street") ? values["address_zip"] : null) ??
				(values.ContainsKey("zip") ? values["zip"] : null) ?? customer.GetAttributeValue<string>("address1_postalcode");
		}

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

public Enreplacedy CreateOrder()
		{
			var shoppingCartReference = GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid");

			ConvertQuoteToOrder(_context, Enreplacedy);

			var orderCreated = _context.CreateQuery("salesorder").FirstOrDefault(so => so.GetAttributeValue<EnreplacedyReference>("quoteid").Id
				== Enreplacedy.GetAttributeValue<Guid>("quoteid"));

			orderCreated.Attributes["adx_shoppingcartid"] = shoppingCartReference;

			_context.UpdateObject(orderCreated);

			_context.SaveChanges();

			orderCreated = _context.CreateQuery("salesorder").FirstOrDefault(so => so.GetAttributeValue<Guid>("salesorderid")
				== orderCreated.GetAttributeValue<Guid>("salesorderid"));

			return orderCreated;
		}

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 : DiscountCodeValidationResult.cs
License : MIT License
Project Creator : Adoxio

private static decimal GetDecimalFromMoney(Enreplacedy enreplacedy, string attributeLogicalName, decimal defaultValue = 0)
		{
			var value = enreplacedy.GetAttributeValue<Money>(attributeLogicalName);

			return value == null ? defaultValue : value.Value;
		}

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

public virtual EnreplacedyReference GetUnitOfMeasure(IEnumerable<Enreplacedy> productPriceLisreplacedems)
		{
			productPriceLisreplacedems = productPriceLisreplacedems.ToArray();

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

			// Favour a price list item matching the line item UoM, if it has one.
			if (UnitOfMeasure != null)
			{
				var itemMatchingUom = productPriceLisreplacedems.FirstOrDefault(e => UnitOfMeasure.Equals(e.GetAttributeValue<EnreplacedyReference>("uomid")));

				if (itemMatchingUom != null)
				{
					return itemMatchingUom.GetAttributeValue<EnreplacedyReference>("uomid");
				}
			}

			// Otherwise, just take the first. Hopefully that's fine...
			return productPriceLisreplacedems.First().GetAttributeValue<EnreplacedyReference>("uomid");
		}

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

public static LineItem GetLineItemFromLineItemEnreplacedy(Enreplacedy enreplacedy, string productAttribute, string descriptionAttribute, string instructionsAttribute, string orderAttribute, string requiredAttribute, string quanreplacedyAttribute, string uomAttribute, Dictionary<Guid, Enreplacedy> products)
		{
			if (enreplacedy == null)
			{
				return null;
			}

			var productReference = enreplacedy.GetAttributeValue<EnreplacedyReference>(productAttribute);

			if (productReference == null || productReference.LogicalName != "product")
			{
				return null;
			}

			Enreplacedy product;

			if (!products.TryGetValue(productReference.Id, out product))
			{
				return null;
			}

			var description = string.IsNullOrEmpty(descriptionAttribute)
				? product.GetAttributeValue<string>("description")
				: enreplacedy.GetAttributeValue<string>(descriptionAttribute);

			var instructions = string.IsNullOrEmpty(instructionsAttribute)
				? null
				: enreplacedy.GetAttributeValue<string>(instructionsAttribute);

			var order = string.IsNullOrEmpty(orderAttribute)
				? int.MaxValue
				: enreplacedy.GetAttributeValue<int?>(orderAttribute).GetValueOrDefault(int.MaxValue);

			var required = string.IsNullOrEmpty(requiredAttribute)
				|| enreplacedy.GetAttributeValue<bool?>(requiredAttribute).GetValueOrDefault();

			var quanreplacedy = string.IsNullOrEmpty(quanreplacedyAttribute)
				? required ? 1 : 0
				: enreplacedy.GetAttributeValue<decimal?>(quanreplacedyAttribute).GetValueOrDefault();

			var uom = string.IsNullOrEmpty(uomAttribute)
				? null
				: enreplacedy.GetAttributeValue<EnreplacedyReference>(uomAttribute);

			return new LineItem(product, uom, quanreplacedy, !required, description, instructions, order);
		}

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

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

			var findShoppingCarts =
				from sc in context.CreateQuery("adx_shoppingcart")
				where sc.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference()
					&& sc.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website.ToEnreplacedyReference()
					&& sc.GetAttributeValue<OptionSetValue>("statuscode") != null && sc.GetAttributeValue<OptionSetValue>("statuscode").Value == 1
					&& sc.GetAttributeValue<bool?>("adx_system").GetValueOrDefault(false) == false
				select sc;

			return findShoppingCarts;
		}

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

public static IEnumerable<Enreplacedy> GetCartsForVisitor(this OrganizationServiceContext context, string visitorId, Enreplacedy website)
		{
			website.replacedertEnreplacedyName("adx_website");

			var findShoppingCarts =
				from sc in context.CreateQuery("adx_shoppingcart")
				where sc.GetAttributeValue<string>("adx_visitorid") == visitorId
					&& sc.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website.ToEnreplacedyReference()
					&& sc.GetAttributeValue<OptionSetValue>("statuscode") != null && sc.GetAttributeValue<OptionSetValue>("statuscode").Value == 1
					&& sc.GetAttributeValue<bool?>("adx_system").GetValueOrDefault(false) == false
				select sc;

			return findShoppingCarts;
		}

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

public static string GetPriceListNameForParentAccount(this OrganizationServiceContext context, Enreplacedy contact)
		{
			var priceLevel = context.GetPriceListForParentAccount(contact);

			return priceLevel != null ? priceLevel.GetAttributeValue<string>("name") : null;
		}

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

public static Enreplacedy GetPriceListForParentAccount(this OrganizationServiceContext context, Enreplacedy contact)
		{
			contact.replacedertEnreplacedyName("contact");

			var priceLevels = from pricelevel in context.CreateQuery("pricelevel")
								join account in context.CreateQuery("account")
								on pricelevel.GetAttributeValue<Guid>("pricelevelid") equals account.GetAttributeValue<EnreplacedyReference>("defaultpricelevelid").Id
								where account.GetAttributeValue<Guid>("accountid") == (contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == null ? Guid.Empty : contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id)
								select pricelevel;

			return priceLevels.FirstOrDefault();
		}

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 : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio

public static Enreplacedy GetDefaultUomByProduct(this OrganizationServiceContext context, Enreplacedy product)
		{
			var uom = context.CreateQuery("uom").FirstOrDefault(um => um.GetAttributeValue<Guid>("uomid") == product.GetAttributeValue<EnreplacedyReference>("defaultuomid").Id);

			return uom;
		}

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

public static Money GetProductPriceByPriceListName(this OrganizationServiceContext context, Enreplacedy product, string priceListName)
		{
			product.replacedertEnreplacedyName("product");

			return context.GetProductPriceByPriceListName(product.GetAttributeValue<Guid>("productid"), priceListName);
		}

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

public static Enreplacedy GetPriceLisreplacedemByPriceListNameAndUom(this OrganizationServiceContext context, Guid productID, Guid uomid, string priceListName)
		{
			var product = context.CreateQuery("product").FirstOrDefault(p => p.GetAttributeValue<Guid>("productid") == productID);

			return context.GetPriceLisreplacedemByPriceListNameAndUom(product, uomid, priceListName);
		}

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

public static Enreplacedy GetPriceLisreplacedemByPriceListNameAndUom(this OrganizationServiceContext context, Enreplacedy product, Guid uomid, string priceListName)
		{
			var priceLisreplacedems =
				from pl in context.CreateQuery("pricelevel")
				join ppl in context.CreateQuery("productpricelevel") on pl.GetAttributeValue<Guid>("pricelevelid") equals ppl.GetAttributeValue<EnreplacedyReference>("pricelevelid").Id
				where
					ppl.GetAttributeValue<EnreplacedyReference>("pricelevelid") != null &&
					ppl.GetAttributeValue<EnreplacedyReference>("productid") != null &&
					ppl.GetAttributeValue<EnreplacedyReference>("productid") == product.ToEnreplacedyReference() &&
					ppl.GetAttributeValue<EnreplacedyReference>("uomid") == new EnreplacedyReference("uom", uomid)
				where
					pl.GetAttributeValue<string>("name") == priceListName &&
					((pl.GetAttributeValue<DateTime?>("begindate") == null ||
					pl.GetAttributeValue<DateTime?>("begindate") <= DateTime.UtcNow) &&
					(pl.GetAttributeValue<DateTime?>("enddate") == null ||
					pl.GetAttributeValue<DateTime?>("enddate") >= DateTime.UtcNow))
				select ppl;
			
			return priceLisreplacedems.FirstOrDefault();
		}

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

private static void Refresh(CrmDbContext context, ContentMap map, List<EnreplacedyReference> references)
		{
			if (references.Count > 0)
			{
				references[0].ThrowOnNull("reference");
				EnreplacedyDefinition ed;
				Dictionary<Guid, Enreplacedy> mapEnreplacedies = new Dictionary<Guid, Enreplacedy>();
				bool getEnreplacedyDefinition = map.Solution.Enreplacedies.TryGetValue(references[0].LogicalName, out ed);

				if (getEnreplacedyDefinition)
				{
					List<Guid> guids = new List<Guid>();
					foreach (var reference in references)
					{
						reference.ThrowOnNull("reference");
						guids.Add(reference.Id);
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("LogicalName={0}, Id={1}", EnreplacedyNamePrivacy.GetEnreplacedyName(reference.LogicalName), reference.Id));
					}
					try
					{
						string primaryEnreplacedyAttribute = EventHubBasedInvalidation.CrmChangeTrackingManager.Instance.TryGetPrimaryKey(references[0].LogicalName);

						var enreplacedies = RetrieveCRMRecords(context, primaryEnreplacedyAttribute, references[0], ed, guids);
						foreach (var enreplacedy in enreplacedies)
						{
							mapEnreplacedies.Add(enreplacedy.Id, enreplacedy);
						}

						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Retrieve Multiple Response for Enreplacedy {0} has Record Count {1} , Refrence Count {2} ", references[0].LogicalName, enreplacedies.Count, references.Count));

						// check if the enreplacedy is inactive according to the definition
						foreach (var reference in references)
						{
							var enreplacedy = mapEnreplacedies.ContainsKey(reference.Id) ? (Enreplacedy)mapEnreplacedies[reference.Id] : null;

							// Check if the enreplacedy matches on the defined relationships.
							if (!ed.ShouldIncludeInContentMap(enreplacedy))
							{
								continue;
							}

							var option = enreplacedy != null ? enreplacedy.GetAttributeValue<OptionSetValue>("statecode") : null;
							var isActive = ed.ActiveStateCode == null || (option != null && ed.ActiveStateCode.Value == option.Value);
							var node = map.Using(ContentMapLockType.Write, () => enreplacedy != null
								? isActive
									? map.Replace(enreplacedy)
									: map.Deactivate(reference)
								: map.Remove(reference));
						}

					}
					catch (FaultException<OrganizationServiceFault>)
					{
						// an exception occurs when trying to retrieve a non-existing enreplacedy
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("An exception occurs when trying to retrieve a non-existing enreplacedy"));
					}
				}
				else
				{
					ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Unknown: logicalName={0}", EnreplacedyNamePrivacy.GetEnreplacedyName(references[0].LogicalName)));
				}
			}
		}

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

public bool IsInactive(Enreplacedy enreplacedy)
		{
			enreplacedy.replacedertEnreplacedyName(EnreplacedyName);

			var status = enreplacedy.GetAttributeValue<OptionSetValue>(StatusPropertyName);

			return status != null && status.Value == InactiveStatus;
		}

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

public static void RemoveTagFromWebPageAndSave(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, do nothing
			if (tag == null)
			{
				return;
			}

			context.DeleteLink(page, new Relationship("adx_pagetag_webpage"), tag);
			context.SaveChanges();
		}

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

public static Enreplacedy GetSiteMarkerByName(this OrganizationServiceContext context, Enreplacedy website, string siteMarkerName)
		{
			var siteMarkers = context.GetSiteMarkers(website);
			return siteMarkers.FirstOrDefault(sm => sm.GetAttributeValue<string>("adx_name") == siteMarkerName);
		}

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

public static IEnumerable<Enreplacedy> GetVisibleChildPagesBySiteMarker(this OrganizationServiceContext context, Enreplacedy website, string siteMarker)
		{
			website.replacedertEnreplacedyName("adx_website");

			var findPages =
				from cwp in context.CreateQuery("adx_webpage")
				join wp in context.CreateQuery("adx_webpage")
					on cwp.GetAttributeValue<EnreplacedyReference>("adx_parentpageid").Id equals wp.GetAttributeValue<Guid>("adx_webpageid")
				join sm in context.CreateQuery("adx_sitemarker")
					on wp.GetAttributeValue<Guid>("adx_webpageid") equals sm.GetAttributeValue<EnreplacedyReference>("adx_pageid").Id
				// filter to current site
				where sm.GetAttributeValue<EnreplacedyReference>("adx_pageid") != null && sm.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website.ToEnreplacedyReference() && sm.GetAttributeValue<string>("adx_name") == siteMarker
				select cwp;

			return findPages.Cast<Enreplacedy>().ToList();
		}

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

public static IEnumerable<Enreplacedy> GetRecentlyPublishedEvents(this OrganizationServiceContext context, Enreplacedy website, int daysOut = 7, string portalName = null)
		{
			website.replacedertEnreplacedyName("adx_website");

			var now = DateTime.Now.Floor(RoundTo.Minute);

			return
				from evnt in context.GetPublishedEvents(website)
				where evnt.GetAttributeValue<DateTime>("createdon") > now.AddDays(-daysOut)
				select evnt;
		}

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

public static Enreplacedy GetSettingByName(this OrganizationServiceContext context, string settingName)
		{
			var settings = context.GetSettings();
			return (from s in settings where s.GetAttributeValue<string>("adx_name") == settingName select s).FirstOrDefault();
		}

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

public static string GetSettingValueByName(this OrganizationServiceContext context, string settingName)
		{
			var setting = context.GetSettingByName(settingName);
			return (setting == null ? null : setting.GetAttributeValue<string>("adx_value"));
		}

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

public override bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy enreplacedy, CrmEnreplacedyRight right, CrmEnreplacedyCacheDependencyTrace dependencies)
		{
			if (enreplacedy == null || right == CrmEnreplacedyRight.Change)
			{
				return false;
			}

			dependencies.AddEnreplacedyDependency(enreplacedy);
			dependencies.AddEnreplacedySetDependency("adx_webrole");
			dependencies.AddEnreplacedySetDependency("adx_webrole_contact");
			dependencies.AddEnreplacedySetDependency("adx_webrole_account");
			dependencies.AddEnreplacedySetDependency("adx_websiteaccess");

			var enreplacedyName = enreplacedy.LogicalName;

			if (enreplacedyName == "adx_idea")
			{
				return enreplacedy.GetAttributeValue<bool?>("adx_approved").GetValueOrDefault(false);
			}

			if (enreplacedyName == "adx_ideacomment")
			{
				return enreplacedy.GetAttributeValue<bool?>("adx_approved").GetValueOrDefault(false);
			}

			EnreplacedyReference publishingStateReference = null;
			Enreplacedy enreplacedyPublishingState = null;

			switch (enreplacedyName)
			{
				case "adx_communityforumpost":
					publishingStateReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid");
					break;
				case "adx_ad":
					publishingStateReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid");
					break;

				// legacy enreplacedies
				case "adx_event":
					enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_event");
					break;
				case "adx_eventschedule":
					enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_eventschedule");
					break;
				case "adx_eventspeaker":
					enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_eventspeaker");
					break;
				case "adx_eventsponsor":
					enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_eventsponsor");
					break;
				case "adx_survey":
					enreplacedyPublishingState = context.RetrieveRelatedEnreplacedy(enreplacedy, "adx_publishingstate_survey");
					break;
			}

			if (publishingStateReference != null)
			{
				enreplacedyPublishingState = context.RetrieveSingle(
					"adx_publishingstate",
					new[] { "adx_isvisible" },
					new Condition("adx_publishingstateid", ConditionOperator.Equal, publishingStateReference.Id));
			}

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

			dependencies.AddEnreplacedyDependency(enreplacedyPublishingState);

			if (enreplacedyPublishingState.GetAttributeValue<bool?>("adx_isvisible").GetValueOrDefault())
			{
				return true;
			}

			return UserCanPreview(context, enreplacedyPublishingState);
		}

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

public void AddRating(Enreplacedy enreplacedy, int rating, int maxRating, int minRating)
		{
			var serviceContext = Dependencies.GetServiceContext();

			enreplacedy.Attributes["regardingobjectid"] = RateableReference;
			enreplacedy.Attributes[FeedbackMetadataAttributes.RatingValueAttributeName] = rating;
			enreplacedy.Attributes[FeedbackMetadataAttributes.MaxRatingAttributeName] = maxRating;
			enreplacedy.Attributes[FeedbackMetadataAttributes.MinRatingAttributeName] = minRating;
			enreplacedy.Attributes["source"] = new OptionSetValue((int)FeedbackSource.Portal);

			var enreplacedyMetadata = GetRelatedEnreplacedyMetadata(serviceContext);

			var replacedle = string.Empty;
			var displayName = string.Empty;

			if (enreplacedyMetadata != null)
			{
				displayName = enreplacedyMetadata.DisplayName.UserLocalizedLabel.Label;

				var relatedEnreplacedy = GetRelatedEnreplacedy(serviceContext, enreplacedyMetadata.PrimaryIdAttribute);
				replacedle = relatedEnreplacedy.GetAttributeValue<string>(enreplacedyMetadata.PrimaryNameAttribute);
			}

			enreplacedy.Attributes["replacedle"] = ResourceManager.GetString("Feedback_Default_replacedle").FormatWith(displayName, replacedle);

			serviceContext.AddObject(enreplacedy);
			serviceContext.SaveChanges();
		}

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

private static string GetLanguageName(Enreplacedy enreplacedy, ContextLanguageInfo language)
		{
			if (language.IsCrmMultiLanguageEnabled)
			{
				var langReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_contentsnippetlanguageid");
				if (langReference != null)
				{
					var websiteLanguages = language.ActiveWebsiteLanguages.ToArray();
					var snippetLanguage = language.GetWebsiteLanguage(langReference.Id, websiteLanguages);

					if (snippetLanguage != null)
					{
						return snippetLanguage.DisplayName;
					}
				}
			}

			return null;
		}

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

public static Enreplacedy GetSupportPlan(IPortalContext portal, Enreplacedy account, OrganizationServiceContext context, Enreplacedy contact, Enreplacedy supportRequest)
		{
			var shoppingCart =
				context.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_shoppingcartid")
					== supportRequest.GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid").Id);

			var myCart = new ShoppingCart(shoppingCart, context);

			var total = myCart.GetCartTotal();

			//lookup shopping cart item(s)?
			//for now we only care about ONE shopping cart item, since this is an "instant purchase" and there is no cart experience.
			var shoppingCarreplacedem =
				context.CreateQuery("adx_shoppingcarreplacedem").FirstOrDefault(sci => sci.GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid").Id ==
					shoppingCart.GetAttributeValue<Guid>("adx_shoppingcartid"));

			var uom = context.CreateQuery("uom").FirstOrDefault(
				u => u.GetAttributeValue<Guid>("uomid") == shoppingCarreplacedem.GetAttributeValue<EnreplacedyReference>("adx_uomid").Id);

			var supportRequestProduct = supportRequest.GetAttributeValue<EnreplacedyReference>("adx_product");

			Enreplacedy product = null;

			if (supportRequestProduct != null)
			{
				product = context.CreateQuery("product").FirstOrDefault(p => p.GetAttributeValue<Guid>("productid") == supportRequestProduct.Id);	
			}
			
			var supportPlan = CreateSupportPlan(total, portal, context, uom, contact, product, account);

			return supportPlan;
		}

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

private static Enreplacedy GetOrderCustomer(Dictionary<string, string> values, OrganizationServiceContext context, Enreplacedy shoppingCart)
		{
			Guid customerID;

			Enreplacedy customer;

			if (shoppingCart.GetAttributeValue<EnreplacedyReference>("adx_contactid") != null)
			{
				customerID = shoppingCart.GetAttributeValue<EnreplacedyReference>("adx_contactid").Id;
			}
			else
			{
				customerID = Guid.NewGuid();
				customer = new Enreplacedy("contact") { Id = customerID };

				customer.Attributes["contactid"] = customerID;
				customer.Id = customerID;

				var firstName = (values.ContainsKey("first_name") ? values["first_name"] : null) ?? "Tim";

				customer.Attributes["firstname"] = firstName;
				customer.Attributes["lastname"] = (values.ContainsKey("last_name") ? values["last_name"] : null) ?? "Sample";
				customer.Attributes["telephone1"] = (values.ContainsKey("contact_phone") ? values["contact_phone"] : null) ??
					((string.IsNullOrEmpty(firstName)) ? "555-9765" : null);
				customer.Attributes["address1_line1"] = (values.ContainsKey("address_street") ? values["address_street"] : null) ??
					(values.ContainsKey("address1") ? values["address1"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "123 easy street" : null);
				customer.Attributes["address1_city"] = (values.ContainsKey("address_city") ? values["address_city"] : null) ??
					(values.ContainsKey("city") ? values["city"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "Anytown" : null);
				customer.Attributes["address1_country"] = (values.ContainsKey("address_country") ? values["address_country"] : null) ??
					(values.ContainsKey("country") ? values["country"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "USA" : null);
				customer.Attributes["address1_stateorprovince"] = (values.ContainsKey("address_state") ? values["address_state"] : null) ??
					(values.ContainsKey("state") ? values["state"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "NY" : null);
				customer.Attributes["address1_postalcode"] = (values.ContainsKey("address_zip") ? values["address_zip"] : null) ??
					(values.ContainsKey("zip") ? values["zip"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "91210" : null);

				context.AddObject(customer);
				context.SaveChanges();
			}

			customer = context.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == customerID);

			return customer;
		}

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

public T GetAttributeValue<T>(string attributeName)
		{
			return Enreplacedy.GetAttributeValue<T>(attributeName);
		}

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

public static Enreplacedy GetCarreplacedemByID(this OrganizationServiceContext context, Guid id)
		{
			var findShoppingCarreplacedem =
				from sc in context.CreateQuery("adx_shoppingcarreplacedem")
				where sc.GetAttributeValue<Guid>("adx_shoppingcarreplacedemid") == id
				select sc;

			return findShoppingCarreplacedem.FirstOrDefault();
		}

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

public static IEnumerable<Enreplacedy> GetOrdersForContact(this OrganizationServiceContext context, Enreplacedy contact)
		{

			var findOrders =
				from o in context.CreateQuery("salesorder")
				where o.GetAttributeValue<EnreplacedyReference>("customerid") == contact.ToEnreplacedyReference()
				select o;

			return findOrders;
		}

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

public static Money GetProductPriceByPriceListName(this OrganizationServiceContext context, Enreplacedy product, Enreplacedy website, string priceListName)
		{
			product.replacedertEnreplacedyName("product");

			website.replacedertEnreplacedyName("adx_website");

			var priceLisreplacedem = context.GetPriceLisreplacedemByPriceListName(product, priceListName);

			var returnPrice = priceLisreplacedem != null ? priceLisreplacedem.GetAttributeValue<Money>("amount") : null;

			if (returnPrice == null)
			{
				priceLisreplacedem = context.GetPriceLisreplacedemByPriceListName(product, context.GetDefaultPriceListName(website));

				returnPrice = priceLisreplacedem != null ? priceLisreplacedem.GetAttributeValue<Money>("amount") : null;
			}

			return returnPrice;
		}

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

public static Money GetProductPriceByPriceListName(this OrganizationServiceContext context, Guid productID, string priceListName)
		{
			var priceLisreplacedem = context.GetPriceLisreplacedemByPriceListName(productID, priceListName);

			return priceLisreplacedem != null ? priceLisreplacedem.GetAttributeValue<Money>("amount") : null;
		}

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

public static decimal GetDecimalFromMoney(Enreplacedy quote, string attributeLogicalName, decimal defaultValue = 0)
		{
			var value = quote.GetAttributeValue<Money>(attributeLogicalName);

			return value == null ? defaultValue : value.Value;
		}

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 : QuotePurchaseDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private static IPurchasableItem GetPurchasableItemFromQuoteProduct(OrganizationServiceContext serviceContext, Enreplacedy quoteProduct, IDictionary<Guid, Enreplacedy> products)
		{
			var productReference = quoteProduct.GetAttributeValue<EnreplacedyReference>("productid");

			if (productReference == null)
			{
				return null;
			}

			Enreplacedy product;

			if (!products.TryGetValue(productReference.Id, out product))
			{
				return null;
			}

			serviceContext.LoadProperty(quoteProduct, new Relationship("adx_discount_quotedetail"));

			var discounts = quoteProduct.GetRelatedEnreplacedies<Enreplacedy>(new Relationship("adx_discount_quotedetail"))
							.Select(e => new Discount(e.Id, e.GetAttributeValue<string>("adx_code"), e.GetAttributeValue<string>("adx_name"),
								e.GetAttributeValue<OptionSetValue>("adx_scope") == null ? 0 : e.GetAttributeValue<OptionSetValue>("adx_scope").Value,
								e.GetAttributeValue<OptionSetValue>("adx_type") == null ? 0 : e.GetAttributeValue<OptionSetValue>("adx_type").Value,
								e.GetAttributeValue<OptionSetValue>("adx_type") == null ? 0 : (e.GetAttributeValue<OptionSetValue>("adx_type").Value == (int)DiscountType.Amount) ? QuoteFunctions.GetDecimalFromMoney(e, "adx_amount") : e.GetAttributeValue<decimal?>("adx_percentage") ?? 0))
							.ToArray();

			return new PurchaseableItem(
				quoteProduct,
				product.GetAttributeValue<string>("name"),
				productReference,
				discounts,
				product.GetAttributeValue<decimal?>("stockweight").GetValueOrDefault(0) > 0);
		}

See More Examples