Here are the examples of the csharp api Microsoft.Xrm.Sdk.Entity.ToEntityReference() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
260 Examples
19
Source : CrmInvitationStore.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual IEnumerable<OrganizationRequest> ToRedeemRequests(TInvitation invitation, CrmUser<TKey> user, string userHostAddress)
{
// updating the invitation
var enreplacedy = new Enreplacedy("adx_invitation") { Id = ToGuid(invitation.InvitationId), EnreplacedyState = EnreplacedyState.Changed };
// update the redemption counter
var redemptions = invitation.Redemptions + 1;
enreplacedy.SetAttributeValue("adx_redemptions", redemptions);
// replacedociate a new redemption enreplacedy to the invitation
var redemption = new Enreplacedy("adx_inviteredemption") { EnreplacedyState = EnreplacedyState.Created };
redemption.SetAttributeValue("subject", user.UserName);
redemption.SetAttributeValue("adx_ipaddress", userHostAddress);
redemption.SetAttributeValue("regardingobjectid", enreplacedy.ToEnreplacedyReference());
redemption.RelatedEnreplacedies[new Relationship("adx_invitation_adx_inviteredemptions")] = new EnreplacedyCollection(new[] { enreplacedy });
if (user.ContactId != null)
{
// replacedociate the invited contact to the invitation
if (invitation.Type == InvitationType.Single)
{
enreplacedy.SetAttributeValue("adx_redeemedcontact", user.ContactId);
}
else if (invitation.Type == InvitationType.Group)
{
var contact = new Enreplacedy(user.ContactId.LogicalName) { Id = user.ContactId.Id, EnreplacedyState = EnreplacedyState.Unchanged };
enreplacedy.RelatedEnreplacedies[new Relationship("adx_invitation_redeemedcontacts")] = new EnreplacedyCollection(new[] { contact });
}
var activityparty = new Enreplacedy("activityparty");
activityparty["partyid"] = user.ContactId;
redemption.SetAttributeValue("customers", new EnreplacedyCollection(new[] { activityparty }));
}
yield return new CreateRequest { Target = redemption };
if (redemptions >= invitation.MaximumRedemptions)
{
// set invitation to redeemed state
yield return new SetStateRequest
{
EnreplacedyMoniker = enreplacedy.ToEnreplacedyReference(),
State = new OptionSetValue(0),
Status = new OptionSetValue(756150001) //Redeemed
};
}
}
19
Source : CrmEntityStore.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public virtual async Task UpdateAsync(TModel model)
{
ThrowIfDisposed();
if (model == null) throw new ArgumentNullException("model");
var enreplacedy = ToEnreplacedy(model);
var snapshot = await FetchByIdAsync(enreplacedy.ToEnreplacedyReference()).WithCurrentCulture();
Execute(ToUpdateRequests(enreplacedy, snapshot));
}
19
Source : CrmEntityStore.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected void MergeRelatedEnreplacedies(ICollection<Enreplacedy> parents, Relationship relationship, string relatedLogicalName, ColumnSet relatedColumns)
{
if (parents == null || parents.Count == 0)
{
return;
}
var parentIds = parents.Select(parent => parent.Id).Cast<object>().ToList();
var parentIdsCondition = new[] { new Condition { Attribute = PrimaryIdAttribute, Operator = ConditionOperator.In, Values = parentIds } };
var fetchRelatedEnreplacedies = new Fetch
{
Enreplacedy = new FetchEnreplacedy(relatedLogicalName, relatedColumns.Columns)
{
Filters = new[] { new Filter {
Conditions = GetActiveStateConditions().Concat(parentIdsCondition).ToList()
} }
}
};
var relatedEnreplacedies = Context.Service.RetrieveMultiple(fetchRelatedEnreplacedies);
foreach (var parent in parents)
{
var parentId = parent.ToEnreplacedyReference();
var relatedSubset = relatedEnreplacedies.Enreplacedies.Where(binding => Equals(binding.GetAttributeValue<EnreplacedyReference>(PrimaryIdAttribute), parentId));
parent.RelatedEnreplacedies[relationship] = new EnreplacedyCollection(relatedSubset.ToList());
}
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<Enreplacedy> ToChangedRelationship(IEnumerable<Enreplacedy> enreplacedies, EnreplacedyCollection collection)
{
foreach (var enreplacedy in enreplacedies)
{
var snapshot = collection != null
? collection.Enreplacedies.SingleOrDefault(e => Equals(e.ToEnreplacedyReference(), enreplacedy.ToEnreplacedyReference()))
: null;
var result = ToChangedEnreplacedy(enreplacedy, snapshot);
if (result != null)
{
yield return result;
}
}
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<Enreplacedy> ToRemovedRelationship(EnreplacedyCollection collection, IEnumerable<Enreplacedy> enreplacedies)
{
foreach (var snapshot in enreplacedies)
{
var enreplacedy = collection != null
? collection.Enreplacedies.SingleOrDefault(e => Equals(e.ToEnreplacedyReference(), snapshot.ToEnreplacedyReference()))
: null;
var result = ToRemovedEnreplacedy(enreplacedy, snapshot);
if (result != null)
{
yield return result;
}
}
}
19
Source : AuthorizeNetHelper.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : AuthorizeNetHelper.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : CommerceOrder.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : CommerceOrder.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : CommerceQuote.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : ContentMap.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public bool TryGetValue<T>(Enreplacedy enreplacedy, out T node)
where T : EnreplacedyNode
{
if (enreplacedy != null)
{
return TryGetValue(enreplacedy.ToEnreplacedyReference(), out node);
}
node = null;
return false;
}
19
Source : ContentMap.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public EnreplacedyNode Replace(Enreplacedy enreplacedy)
{
enreplacedy.ThrowOnNull("enreplacedy");
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("LogicalName={0}, Id={1}", EnreplacedyNamePrivacy.GetEnreplacedyName(enreplacedy.LogicalName), enreplacedy.Id));
var reference = enreplacedy.ToEnreplacedyReference();
// remove the existing node
var removed = Unmerge(reference, ToEnreplacedyIdentifier);
if (removed != null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Removed: Id={0}", removed.Id));
}
// add the new node
var added = AddOrGetExisting(enreplacedy);
if (added != null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Added: Id={0}", added.Id));
}
return added;
}
19
Source : ContentMapProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<EnreplacedyReference> RetrieveDisreplacedociatedIntersectEnreplacedies(CrmDbContext context, ContentMap map, EnreplacedyReference target, Relationship relationship, IEnumerable<EnreplacedyReference> relatedEnreplacedies)
{
var solution = map.Solution;
// retrieve the intersect enreplacedy definition
ManyRelationshipDefinition mrd;
EnreplacedyDefinition ed;
if (solution.ManyRelationships != null
&& solution.ManyRelationships.TryGetValue(relationship.SchemaName, out mrd)
&& solution.Enreplacedies.TryGetValue(mrd.IntersectEnreplacedyname, out ed))
{
// retrieve the target node
EnreplacedyNode targetNode;
if (map.TryGetValue(target, out targetNode))
{
// retrieve the set of existing relationships for validation purposes
var enreplacedies = RetrieveIntersectEnreplacedies(context, map, target, relationship, relatedEnreplacedies).Select(e => e.ToEnreplacedyReference()).ToList();
// reflexive N:N relationships are not supported
var targetRelationship = ed.Relationships.Single(r => r.ForeignEnreplacedyLogicalname == target.LogicalName && r.ToMany != null);
// retrieve the intersect nodes that point to the target
var intersects = targetRelationship.ToMany(targetNode).ToList();
foreach (var related in relatedEnreplacedies)
{
EnreplacedyNode relatedNode;
if (map.TryGetValue(related, out relatedNode))
{
var relatedRelationship = ed.Relationships.Single(r => r.ForeignEnreplacedyLogicalname == related.LogicalName && r.ToOne != null);
// filter the intersect nodes that point to the related node (as well as the target)
// ensure that the intersect does not exist in the collection of retrieved intersects
var intersectsToRemove = intersects
.Where(i => Equals(relatedRelationship.ToOne(i), relatedNode))
.Select(i => i.ToEnreplacedyReference())
.Where(i => enreplacedies.All(e => !Equals(e, i)));
foreach (var intersect in intersectsToRemove)
{
yield return intersect;
}
}
}
}
}
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : WebLinkSetDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IWebLink CreateWebLink(OrganizationServiceContext serviceContext, Enreplacedy enreplacedy, ICrmEnreplacedySecurityProvider securityProvider, IEnreplacedyUrlProvider urlProvider, ILookup<Guid, Enreplacedy> childWebLinkLookup)
{
return new WebLink(
enreplacedy,
new PortalViewEnreplacedy(serviceContext, enreplacedy, securityProvider, urlProvider),
urlProvider.GetApplicationPath(serviceContext, enreplacedy),
CreateWebLinkSubTree(serviceContext, enreplacedy.ToEnreplacedyReference(), securityProvider, urlProvider, childWebLinkLookup));
}
19
Source : DiscountCodeValidationResult.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static DiscountCodeValidationResult ValidateDiscountCode(OrganizationServiceContext context, Guid quoteId, string code)
{
var errorCode = DiscountErrorCode.Unknown;
var isValid = false;
var discountableQuoteProductIds = new List<Guid>();
if (string.IsNullOrWhiteSpace(code))
{
var result = new DiscountCodeValidationResult
{
ErrorCode = DiscountErrorCode.CodeNotSpecified
};
return result;
}
var quote = context.CreateQuery("quote").FirstOrDefault(q => q.GetAttributeValue<Guid>("quoteid") == quoteId);
if (quote == null)
{
var result = new DiscountCodeValidationResult
{
ErrorCode = DiscountErrorCode.QuoteNotFound,
};
return result;
}
var existingDiscountCodes = quote.GetAttributeValue<string>("adx_discountcodes") ?? string.Empty;
if (existingDiscountCodes.Contains(code))
{
var result = new DiscountCodeValidationResult
{
ErrorCode = DiscountErrorCode.AlreadyApplied,
};
return result;
}
var prefreightAmount = GetDecimalFromMoney(quote, "totalamountlessfreight");
if (prefreightAmount <= 0)
{
var result = new DiscountCodeValidationResult
{
ErrorCode = DiscountErrorCode.ZeroAmount,
};
return result;
}
var discountErrors = new List<DiscountError>();
var orderScopedDiscounts =
context.CreateQuery("adx_discount")
.Where(
d =>
d.GetAttributeValue<OptionSetValue>("statecode").Value == 0 &&
(d.GetAttributeValue<OptionSetValue>("adx_scope") != null &&
d.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)DiscountScope.Order) &&
((d.GetAttributeValue<DateTime?>("adx_startdate") == null ||
d.GetAttributeValue<DateTime?>("adx_startdate") <= DateTime.UtcNow) &&
(d.GetAttributeValue<DateTime?>("adx_enddate") == null ||
d.GetAttributeValue<DateTime?>("adx_enddate") >= DateTime.UtcNow)) &&
d.GetAttributeValue<string>("adx_code") == code)
.ToList();
if (orderScopedDiscounts.Any())
{
var discountPercentage = quote.GetAttributeValue<decimal?>("discountpercentage") ?? 0;
var discountAmount = GetDecimalFromMoney(quote, "discountamount");
var newDiscountPercentage = discountPercentage;
var newDiscountAmount = discountAmount;
var appliedDiscounts = (from d in context.CreateQuery("adx_discount")
join dq in context.CreateQuery("adx_discount_quote") on
d.GetAttributeValue<Guid>("adx_discountid") equals dq.GetAttributeValue<Guid>("adx_discountid")
where dq.GetAttributeValue<Guid>("quoteid") == quote.Id
select d).ToList();
var newDiscounts = new List<Enreplacedy>();
foreach (var discount in orderScopedDiscounts)
{
var applied = appliedDiscounts.Any(d => d.GetAttributeValue<Guid>("adx_discountid") == discount.Id);
if (applied)
{
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.AlreadyApplied });
continue;
}
var minimumPurchaseAmount = GetDecimalFromMoney(discount, "adx_minimumpurchaseamount");
var maximumRedemptions = discount.GetAttributeValue<int?>("adx_maximumredemptions").GetValueOrDefault(0);
var redemptions = discount.GetAttributeValue<int?>("adx_redemptions").GetValueOrDefault(0);
var typeOption = discount.GetAttributeValue<OptionSetValue>("adx_type");
decimal percentage = 0;
decimal amount = 0;
if (typeOption == null)
{
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
continue;
}
switch (typeOption.Value)
{
case (int)DiscountType.Percentage:
percentage = discount.GetAttributeValue<decimal?>("adx_percentage") ?? 0;
break;
case (int)DiscountType.Amount:
amount = GetDecimalFromMoney(discount, "adx_amount");
break;
default:
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
continue;
}
if (minimumPurchaseAmount > 0 && prefreightAmount < minimumPurchaseAmount)
{
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MinimumAmountNotMet });
}
else if (maximumRedemptions > 0 && redemptions >= maximumRedemptions)
{
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MaximumRedemptions });
}
else
{
newDiscountPercentage += percentage;
newDiscountAmount += amount;
appliedDiscounts.Add(discount);
newDiscounts.Add(discount);
}
}
if (newDiscountPercentage != discountPercentage || newDiscountAmount != discountAmount)
{
isValid = true;
}
}
if (!isValid)
{
// Check for valid quotedetail items
var quoteDetails =
context.CreateQuery("quotedetail")
.Where(q => q.GetAttributeValue<EnreplacedyReference>("quoteid").Equals(quote.ToEnreplacedyReference()))
.ToList();
if (quoteDetails.Any())
{
var priceList = quote.GetAttributeValue<EnreplacedyReference>("pricelevelid");
var productScopeDiscounts =
context.CreateQuery("adx_discount")
.Where(
d =>
d.GetAttributeValue<OptionSetValue>("statecode").Value == 0 &&
(d.GetAttributeValue<OptionSetValue>("adx_scope") != null &&
d.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)DiscountScope.Product) &&
((d.GetAttributeValue<DateTime?>("adx_startdate") == null ||
d.GetAttributeValue<DateTime?>("adx_startdate") <= DateTime.UtcNow) &&
(d.GetAttributeValue<DateTime?>("adx_enddate") == null ||
d.GetAttributeValue<DateTime?>("adx_enddate") >= DateTime.UtcNow)) &&
d.GetAttributeValue<string>("adx_code") == code)
.ToList();
if (!productScopeDiscounts.Any())
{
var result = new DiscountCodeValidationResult
{
ErrorCode = DiscountErrorCode.DoesNotExist,
DiscountErrors = discountErrors
};
return result;
}
foreach (var quotedetail in quoteDetails)
{
var baseAmount = GetDecimalFromMoney(quotedetail, "baseamount");
if (baseAmount <= 0)
{
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.ZeroAmount });
continue;
}
var appliedDiscounts = (from d in context.CreateQuery("adx_discount")
join i in context.CreateQuery("adx_discount_quotedetail") on
d.GetAttributeValue<Guid>("adx_discountid") equals i.GetAttributeValue<Guid>("adx_discountid")
where i.GetAttributeValue<Guid>("quotedetailid") == quotedetail.Id
select d).ToList();
var newDiscounts = new List<Enreplacedy>();
var discountAmount = GetDecimalFromMoney(quotedetail, "manualdiscountamount");
var newDiscountAmount = discountAmount;
foreach (var discount in productScopeDiscounts)
{
var applied = appliedDiscounts.Any(d => d.GetAttributeValue<Guid>("adx_discountid") == discount.Id);
if (applied)
{
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.AlreadyApplied });
continue;
}
var discountProductPriceLevel = (from pl in context.CreateQuery("productpricelevel")
join dp in context.CreateQuery("adx_discount_productpricelevel") on
pl.GetAttributeValue<Guid>("productpricelevelid") equals dp.GetAttributeValue<Guid>("productpricelevelid")
where dp.GetAttributeValue<Guid>("adx_discountid") == discount.Id
where pl.GetAttributeValue<EnreplacedyReference>("pricelevelid").Equals(priceList)
select pl).ToList();
if (!discountProductPriceLevel.Any())
{
continue;
}
var quotedetailid = quotedetail.Id;
var quoteProductDiscounts = (from d in discountProductPriceLevel
join q in
context.CreateQuery("quotedetail")
.Where(q => q.GetAttributeValue<Guid>("quotedetailid") == quotedetailid)
on
new
{
productid = d.GetAttributeValue<EnreplacedyReference>("productid"),
uomid = d.GetAttributeValue<EnreplacedyReference>("uomid")
} equals
new
{
productid = q.GetAttributeValue<EnreplacedyReference>("productid"),
uomid = q.GetAttributeValue<EnreplacedyReference>("uomid")
}
select q).ToList();
if (!quoteProductDiscounts.Any())
{
continue;
}
var maximumRedemptions = discount.GetAttributeValue<int?>("adx_maximumredemptions").GetValueOrDefault(0);
var redemptions = discount.GetAttributeValue<int?>("adx_redemptions").GetValueOrDefault(0);
var typeOption = discount.GetAttributeValue<OptionSetValue>("adx_type");
decimal amount = 0;
if (typeOption == null)
{
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
continue;
}
switch (typeOption.Value)
{
case (int)DiscountType.Percentage:
var percentage = discount.GetAttributeValue<decimal?>("adx_percentage") ?? 0;
if (percentage > 0 && baseAmount > 0)
{
amount = baseAmount * percentage / 100;
}
break;
case (int)DiscountType.Amount:
amount = GetDecimalFromMoney(discount, "adx_amount");
break;
default:
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
continue;
}
if (maximumRedemptions > 0 && redemptions >= maximumRedemptions)
{
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MaximumRedemptions });
continue;
}
newDiscountAmount += amount;
appliedDiscounts.Add(discount);
newDiscounts.Add(discount);
discountableQuoteProductIds.Add(quotedetail.Id);
}
if (newDiscountAmount == discountAmount)
{
continue;
}
isValid = true;
break;
}
}
}
if (!isValid && !discountErrors.Any())
{
discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.NotApplicable });
errorCode = DiscountErrorCode.NotApplicable;
}
return new DiscountCodeValidationResult(isValid)
{
ErrorCode = errorCode,
ExistingDiscountCodes = existingDiscountCodes,
DiscountableQuoteProductIds = discountableQuoteProductIds.Distinct(),
DiscountErrors = discountErrors
};
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetQuotesForContact(this OrganizationServiceContext context, Enreplacedy contact)
{
var findOrders =
from o in context.CreateQuery("quote")
where o.GetAttributeValue<EnreplacedyReference>("customerid") == contact.ToEnreplacedyReference()
select o;
return findOrders;
}
19
Source : QuoteFunctions.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : WebFormPurchaseDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void CompletePurchase(bool fulfillOrder = false, bool createInvoice = false)
{
TraceMethodInfo("Start");
var purchaseMetadata = WebFormMetadata.FirstOrDefault(IsPurchaseMetadata);
if (purchaseMetadata == null)
{
return;
}
if (WebFormSession.QuoteId == Guid.Empty)
{
throw new InvalidOperationException("Failed to retrieve purchase quote from web form session.");
}
fulfillOrder = purchaseMetadata.GetAttributeValue<bool?>(PurchaseMetadataAttributes.FulfillOrderOnPayment).GetValueOrDefault(fulfillOrder);
createInvoice = purchaseMetadata.GetAttributeValue<bool?>(PurchaseMetadataAttributes.CreateInvoiceOnPayment).GetValueOrDefault(createInvoice);
var orderRelationshipName = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.TargetEnreplacedyOrderRelationship);
var setOrderRelationship = !string.IsNullOrEmpty(orderRelationshipName);
var invoiceRelationshipName = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.TargetEnreplacedyInvoiceRelationship);
var setInvoiceRelationship = !string.IsNullOrEmpty(invoiceRelationshipName);
if (!(fulfillOrder || setOrderRelationship || createInvoice || setInvoiceRelationship))
{
// Nothing to do, return.
return;
}
var quote = new EnreplacedyReference("quote", WebFormSession.QuoteId);
var serviceContext = Dependencies.GetServiceContext();
var order = serviceContext.CreateQuery("salesorder")
.Where(e => e.GetAttributeValue<EnreplacedyReference>("quoteid") == quote)
.OrderByDescending(e => e.GetAttributeValue<DateTime>("createdon"))
.FirstOrDefault();
if (order == null)
{
TraceMethodError("Unable to retrieve replacedociated order for quote {0}.", quote.Id);
return;
}
var serviceContextForUpdates = Dependencies.GetServiceContextForWrite();
var hasUpdates = false;
var targetUpdate = new Enreplacedy(Target.LogicalName)
{
Id = Target.Id
};
serviceContextForUpdates.Attach(targetUpdate);
if (setOrderRelationship)
{
var orderUpdate = new Enreplacedy(order.LogicalName)
{
Id = order.Id
};
serviceContextForUpdates.Attach(orderUpdate);
serviceContextForUpdates.AddLink(orderUpdate, new Relationship(orderRelationshipName), targetUpdate);
hasUpdates = true;
}
if (createInvoice)
{
var convertOrderRequest = new ConvertSalesOrderToInvoiceRequest()
{
ColumnSet = new ColumnSet("invoiceid"),
SalesOrderId = order.Id
};
var convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)serviceContext.Execute(convertOrderRequest);
var invoice = convertOrderResponse.Enreplacedy;
var setStateRequest = new SetStateRequest()
{
EnreplacedyMoniker = invoice.ToEnreplacedyReference(),
State = new OptionSetValue(2),
Status = new OptionSetValue(100001)
};
var setStateResponse = (SetStateResponse)serviceContext.Execute(setStateRequest);
invoice = serviceContext.CreateQuery("invoice").Where(i => i.GetAttributeValue<Guid>("invoiceid") == convertOrderResponse.Enreplacedy.Id).FirstOrDefault();
if (setInvoiceRelationship && convertOrderResponse != null && convertOrderResponse.Enreplacedy != null)
{
var invoiceUpdate = new Enreplacedy(invoice.LogicalName)
{
Id = convertOrderResponse.Enreplacedy.Id
};
serviceContextForUpdates.Attach(invoiceUpdate);
serviceContextForUpdates.AddLink(invoiceUpdate, new Relationship(invoiceRelationshipName), targetUpdate);
hasUpdates = true;
}
}
if (hasUpdates)
{
serviceContextForUpdates.SaveChanges();
}
if (fulfillOrder)
{
var orderClose = new Enreplacedy("orderclose");
orderClose["salesorderid"] = order.ToEnreplacedyReference();
serviceContext.Execute(new FulfillSalesOrderRequest
{
OrderClose = orderClose,
Status = new OptionSetValue(-1),
});
}
}
19
Source : EntityListCalendarDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected Func<Enreplacedy, EnreplacedyListEvent> CreateEvent(OrganizationServiceContext serviceContext, EnreplacedyListSettings settings)
{
var organizerCache = new Dictionary<string, EnreplacedyListEventOrganizer>();
var urlFactory = GetEventUrlFactory(settings);
var timeZone = GetTimeZoneInfo(settings);
return e =>
{
var start = e.GetAttributeValue<DateTime?>(settings.StartDateFieldName);
if (start == null)
{
return null;
}
return new EnreplacedyListEvent(e.ToEnreplacedyReference())
{
Start = start.Value,
End = string.IsNullOrWhiteSpace(settings.EndDateFieldName)
? null
: e.GetAttributeValue<DateTime?>(settings.EndDateFieldName),
Summary = string.IsNullOrWhiteSpace(settings.SummaryFieldName)
? null
: e.GetAttributeValue<string>(settings.SummaryFieldName),
Description = string.IsNullOrWhiteSpace(settings.DescriptionFieldName)
? null
: e.GetAttributeValue<string>(settings.DescriptionFieldName),
Organizer = string.IsNullOrWhiteSpace(settings.OrganizerFieldName)
? null
: GetEventOrganizer(serviceContext, e, settings, organizerCache),
Location = string.IsNullOrWhiteSpace(settings.LocationFieldName)
? null
: e.GetAttributeValue<string>(settings.LocationFieldName),
IsAllDay = !string.IsNullOrWhiteSpace(settings.IsAllDayFieldName)
&& e.GetAttributeValue<bool?>(settings.IsAllDayFieldName).GetValueOrDefault(),
TimeZone = timeZone,
TimeZoneDisplayMode = timeZone == null
? EnreplacedyListTimeZoneDisplayMode.UserLocalTimeZone
: EnreplacedyListTimeZoneDisplayMode.SpecificTimeZone,
TimeZoneCode = settings.DisplayTimeZone,
Url = urlFactory(e),
};
};
}
19
Source : CaseDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static void CancelRelatedActivities(OrganizationServiceContext serviceContext, Enreplacedy incident)
{
if (serviceContext == null) throw new ArgumentNullException("serviceContext");
if (incident == null) throw new ArgumentNullException("incident");
var activityPointers = incident.GetRelatedEnreplacedies(serviceContext, new Relationship("Incident_ActivityPointers"));
foreach (var activityPointer in activityPointers)
{
var statecode = activityPointer.GetAttributeValue<OptionSetValue>("statecode");
if (statecode == null)
{
continue;
}
if (!(statecode.Value == (int)ActivityPointerState.Open || statecode.Value == (int)ActivityPointerState.Scheduled))
{
continue;
}
var activityid = activityPointer.GetAttributeValue<Guid>("activityid");
var activitytypecode = activityPointer.GetAttributeValue<string>("activitytypecode");
var activityEnreplacedy = serviceContext.CreateQuery(activitytypecode).FirstOrDefault(e => e.GetAttributeValue<Guid>("activityid") == activityid);
if (activityEnreplacedy == null)
{
continue;
}
serviceContext.SetState(activityEnreplacedy.ToEnreplacedyReference(), new OptionSetValue((int)ActivityPointerState.Canceled), new OptionSetValue(-1));
}
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetActiveCasesForContact(this OrganizationServiceContext context, Enreplacedy contact)
{
if (contact == null)
{
return Enumerable.Empty<Enreplacedy>();
}
contact.replacedertEnreplacedyName("contact");
return GetActiveCasesForContact(context, contact.ToEnreplacedyReference());
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetActiveCasesForContactByAccountId(this OrganizationServiceContext context, Enreplacedy contact, Guid accountid)
{
if (contact == null)
{
return Enumerable.Empty<Enreplacedy>();
}
contact.replacedertEnreplacedyName("contact");
return GetActiveCasesForContactByAccountId(context, contact.ToEnreplacedyReference(), accountid);
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetClosedCasesForContactByAccountId(this OrganizationServiceContext context, Enreplacedy contact, Guid accountid)
{
if (contact == null)
{
return Enumerable.Empty<Enreplacedy>();
}
contact.replacedertEnreplacedyName("contact");
return GetClosedCasesForContactByAccountId(context, contact.ToEnreplacedyReference(), accountid);
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetCaseAccessByContact(this OrganizationServiceContext context, Enreplacedy contact)
{
if (contact == null)
{
return Enumerable.Empty<Enreplacedy>();
}
contact.replacedertEnreplacedyName("contact");
return GetCaseAccessByContact(context, contact.ToEnreplacedyReference());
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetAccountsRelatedToCaseAccessForContact(this OrganizationServiceContext context, Enreplacedy contact)
{
if (contact == null)
{
return Enumerable.Empty<Enreplacedy>();
}
contact.replacedertEnreplacedyName("contact");
return GetAccountsRelatedToCaseAccessForContact(context, contact.ToEnreplacedyReference());
}
19
Source : CrmEntityReplication.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected EnreplacedyReference GetDefaultPublishingState(EnreplacedyReference website)
{
if (website == null)
{
return null;
}
var defaultStateSetting = Context.CreateQuery("adx_sitesetting")
.FirstOrDefault(s => s.GetAttributeValue<string>("adx_name") == "replication/default_publishing_state/name" && s.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website);
if (defaultStateSetting == null)
{
return null;
}
var defaultStateName = defaultStateSetting.GetAttributeValue<string>("adx_value");
var defaultState = Context.CreateQuery("adx_publishingstate")
.FirstOrDefault(s => s.GetAttributeValue<string>("adx_name") == defaultStateName && s.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website);
return defaultState == null ? null : defaultState.ToEnreplacedyReference();
}
19
Source : PublishingStateTransitionSecurityProvider.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : ContentMap.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public EnreplacedyNode AddOrGetExisting(Enreplacedy enreplacedy)
{
var reference = enreplacedy.ToEnreplacedyReference();
// retrieve the global lookup for the enreplacedy
EnreplacedyNode node;
if (!TryGetValue(reference, out node))
{
EnreplacedyDefinition ed;
if (Solution.Enreplacedies.TryGetValue(reference.LogicalName, out ed))
{
// create a new node for the enreplacedy
node = ed.ToNode(enreplacedy);
// replacedociate the enreplacedy nodes
Merge(ed, reference, node);
}
}
else
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Exists: LogicalName={0}, Id={1}", EnreplacedyNamePrivacy.GetEnreplacedyName(enreplacedy.LogicalName), enreplacedy.Id));
}
return node;
}
19
Source : CommerceOrder.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : CommerceQuote.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static void ConvertQuoteToOrder(Microsoft.Xrm.Sdk.Client.OrganizationServiceContext context, Microsoft.Xrm.Sdk.Enreplacedy myQuote)
{
// Activate the quote
SetStateRequest activateQuote = new SetStateRequest()
{
EnreplacedyMoniker = myQuote.ToEnreplacedyReference(),
State = new OptionSetValue(1),
Status = new OptionSetValue(2)
};
context.Execute(activateQuote);
//Console.WriteLine("Quote activated.");
Guid quoteId = myQuote.GetAttributeValue<Guid>("quoteid");
var quoteClose = new Enreplacedy("quoteclose");
quoteClose.Attributes["quoteid"] = myQuote.ToEnreplacedyReference();
quoteClose.Attributes["subject"] = "Won The Quote";
WinQuoteRequest winQuoteRequest = new WinQuoteRequest()
{
QuoteClose = quoteClose,
Status = new OptionSetValue(-1) //2? -1??
};
var winQuoteResponse = (WinQuoteResponse)context.Execute(winQuoteRequest);
ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount");
var convertOrderRequest = new ConvertQuoteToSalesOrderRequest()
{
QuoteId = quoteId,
ColumnSet = salesOrderColumns
};
var convertOrderResponse = (ConvertQuoteToSalesOrderResponse)context.Execute(convertOrderRequest);
}
19
Source : CommerceOrder.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : CommerceQuote.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : ShoppingCart.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public void AddProductToCart(Enreplacedy product, Enreplacedy uom, string priceListName, int quanreplacedy)
{
product.replacedertEnreplacedyName("product");
var items = GetCarreplacedems().Where(i => product.ToEnreplacedyReference().Equals(i.GetAttributeValue<EnreplacedyReference>("adx_productid")));
// Check if this product is already in the cart
if (items.Any())
{
//update the first item
var item = items.FirstOrDefault() as ShoppingCarreplacedem;
item.Quanreplacedy = item.Quanreplacedy + (quanreplacedy == 0 ? 1 : quanreplacedy);
item.UpdateItemPrice(priceListName);
//Other items are bugs; there should be no others
return;
}
//else we create a new shopping cart item
var portal = PortalCrmConfigurationManager.CreatePortalContext();
var website = portal.Website;
var priceLisreplacedem = _context.GetPriceLisreplacedemByPriceListNameAndUom(product, uom.Id, (!(string.IsNullOrEmpty(priceListName))
? priceListName : _context.GetDefaultPriceListName(website))) ??
_context.GetPriceLisreplacedemByPriceListName(product, _context.GetDefaultPriceListName(website));
//var quotedPrice = _context.GetProductPriceByPriceListNameAndUom(product, uom.Id, (!(string.IsNullOrEmpty(priceListName))
// ? priceListName : _context.GetDefaultPriceListName(website))) ??
// _context.GetProductPriceByPriceListName(product, _context.GetDefaultPriceListName(website));
var shoppingCarreplacedem = new Enreplacedy("adx_shoppingcarreplacedem");
shoppingCarreplacedem["adx_quanreplacedy"] = (decimal)quanreplacedy;
shoppingCarreplacedem["adx_name"] = "{0}-{1}-{2}".FormatWith(Enreplacedy.GetAttributeValue<string>("adx_name"), product.GetAttributeValue<string>("name"), DateTime.UtcNow);
shoppingCarreplacedem["adx_shoppingcartid"] = Enreplacedy.ToEnreplacedyReference();
shoppingCarreplacedem["adx_productid"] = product.ToEnreplacedyReference();
shoppingCarreplacedem["adx_uomid"] = uom.ToEnreplacedyReference();
if (priceLisreplacedem != null)
{
shoppingCarreplacedem["adx_productpricelevelid"] = priceLisreplacedem.GetAttributeValue<EnreplacedyReference>("pricelevelid");
shoppingCarreplacedem["adx_quotedprice"] = priceLisreplacedem.GetAttributeValue<Money>("amount");
}
_context.AddObject(shoppingCarreplacedem);
if (!_context.IsAttached(Enreplacedy)) _context.Attach(Enreplacedy);
_context.UpdateObject(Enreplacedy);
_context.SaveChanges();
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : QuoteFunctions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static EnreplacedyReference GetQuoteCustomer(OrganizationServiceContext serviceContext, EnreplacedyReference user, string visitorId)
{
if (user != null) { return user; }
if (string.IsNullOrEmpty(visitorId))
{
throw new InvalidOperationException("Unable to create anonymous quote customer record.");
}
var visitor = new Enreplacedy("contact");
visitor["firstname"] = "Anonymous Portal User";
visitor["lastname"] = visitorId;
visitor["adx_username"] = "anonymous:{0}".FormatWith(visitorId);
serviceContext.AddObject(visitor);
serviceContext.SaveChanges();
return visitor.ToEnreplacedyReference();
}
19
Source : QuotePurchaseDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public void CompletePurchase(bool fulfillOrder = false, bool createInvoice = false)
{
if (!(fulfillOrder || createInvoice))
{
return;
}
var serviceContext = Dependencies.GetServiceContext();
var order = serviceContext.CreateQuery("salesorder")
.Where(e => e.GetAttributeValue<EnreplacedyReference>("quoteid") == Quote)
.OrderByDescending(e => e.GetAttributeValue<DateTime>("createdon"))
.FirstOrDefault();
if (order == null)
{
throw new InvalidOperationException("Unable to retrieve replacedociated order for quote {0}.".FormatWith(Quote.Id));
}
if (fulfillOrder)
{
var orderClose = new Enreplacedy("orderclose");
orderClose["salesorderid"] = order.ToEnreplacedyReference();
serviceContext.Execute(new FulfillSalesOrderRequest
{
OrderClose = orderClose,
Status = new OptionSetValue(-1),
});
}
if (createInvoice)
{
var convertOrderRequest = new ConvertSalesOrderToInvoiceRequest()
{
ColumnSet = new ColumnSet("invoiceid"),
SalesOrderId = order.Id
};
var convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)serviceContext.Execute(convertOrderRequest);
var invoice = convertOrderResponse.Enreplacedy;
var setStateRequest = new SetStateRequest()
{
EnreplacedyMoniker = invoice.ToEnreplacedyReference(),
State = new OptionSetValue(2),
Status = new OptionSetValue(100001)
};
var setStateResponse = (SetStateResponse)serviceContext.Execute(setStateRequest);
}
}
19
Source : ShoppingCart.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public void AddProductToCart(Enreplacedy product, Enreplacedy uom, string priceListName)
{
product.replacedertEnreplacedyName("product");
var items = GetCarreplacedems().Where(i => product.ToEnreplacedyReference().Equals(i.GetAttributeValue<EnreplacedyReference>("adx_productid")));
// Check if this product is already in the cart
if (items.Any())
{
//update the first item
var item = items.FirstOrDefault() as ShoppingCarreplacedem;
item.Quanreplacedy = item.Quanreplacedy + 1;
item.UpdateItemPrice(priceListName);
//Other items are bugs; there should be no others
return;
}
//else we create a new shopping cart item
var portal = PortalCrmConfigurationManager.CreatePortalContext();
var website = portal.Website;
var priceLisreplacedem = _context.GetPriceLisreplacedemByPriceListNameAndUom(product, uom.Id, (!(string.IsNullOrEmpty(priceListName))
? priceListName : _context.GetDefaultPriceListName(website))) ??
_context.GetPriceLisreplacedemByPriceListName(product, _context.GetDefaultPriceListName(website));
//var quotedPrice = _context.GetProductPriceByPriceListNameAndUom(product, uom.Id, (!(string.IsNullOrEmpty(priceListName))
// ? priceListName : _context.GetDefaultPriceListName(website))) ??
// _context.GetProductPriceByPriceListName(product, _context.GetDefaultPriceListName(website));
var shoppingCarreplacedem = new Enreplacedy("adx_shoppingcarreplacedem");
shoppingCarreplacedem["adx_quanreplacedy"] = (decimal)1;
shoppingCarreplacedem["adx_name"] = "{0}-{1}-{2}".FormatWith(Enreplacedy.GetAttributeValue<string>("adx_name"), product.GetAttributeValue<string>("name"), DateTime.UtcNow);
shoppingCarreplacedem["adx_shoppingcartid"] = Enreplacedy.ToEnreplacedyReference();
shoppingCarreplacedem["adx_productid"] = product.ToEnreplacedyReference();
shoppingCarreplacedem["adx_uomid"] = uom.ToEnreplacedyReference();
if (priceLisreplacedem != null)
{
shoppingCarreplacedem["adx_productpricelevelid"] = priceLisreplacedem.GetAttributeValue<EnreplacedyReference>("pricelevelid");
shoppingCarreplacedem["adx_quotedprice"] = priceLisreplacedem.GetAttributeValue<Money>("amount");
}
_context.AddObject(shoppingCarreplacedem);
if (!_context.IsAttached(Enreplacedy)) _context.Attach(Enreplacedy);
_context.UpdateObject(Enreplacedy);
_context.SaveChanges();
}
19
Source : WebFormPurchaseDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual IPurchasable SelectFromLineItemEnreplacedies(OrganizationServiceContext serviceContext, Enreplacedy purchaseEnreplacedy, string lineItemRelationship,
Enreplacedy purchaseMetadata, IEnumerable<IPurchasableItemOptions> options)
{
TraceMethodInfo("Start: purchaseEnreplacedy={0}:{1}, lineItemRelationship={2}", purchaseEnreplacedy.LogicalName, purchaseEnreplacedy.Id, lineItemRelationship);
var productAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemProduct);
if (string.IsNullOrEmpty(productAttribute))
{
TraceMethodError("Unable to retrieve products from line item enreplacedies. {0} not defined in web form step metadata. Returning null.", PurchaseMetadataAttributes.LineItemProduct);
return null;
}
var descriptionAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemDescription);
var instructionsAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemInstructions);
var orderAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemOrder);
var requiredAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemRequired);
var quanreplacedyAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemQuanreplacedy);
var uomAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemUom);
var enreplacedies = purchaseEnreplacedy.GetRelatedEnreplacedies(serviceContext, lineItemRelationship).ToArray();
if (!enreplacedies.Any())
{
TraceMethodError("Unable to retrieve any line item enreplacedies. Returning null.");
return null;
}
var productIds = enreplacedies
.Select(e => e.GetAttributeValue<EnreplacedyReference>(productAttribute))
.Where(product => product != null)
.Select(product => product.Id)
.ToArray();
if (!productIds.Any())
{
TraceMethodError("Unable to retrieve any products from line item enreplacedies. Returning null.");
return null;
}
var products = serviceContext.CreateQuery("product")
.WhereIn(e => e.GetAttributeValue<Guid>("productid"), productIds)
.ToDictionary(e => e.Id, e => e);
var lineItems = enreplacedies
.Select(e => LineItem.GetLineItemFromLineItemEnreplacedy(e, productAttribute, descriptionAttribute, instructionsAttribute, orderAttribute, requiredAttribute, quanreplacedyAttribute, uomAttribute, products))
.Where(lineItem => lineItem != null);
var quote = QuoteFunctions.CreateQuote(lineItems, purchaseEnreplacedy.ToEnreplacedyReference(), serviceContext, Dependencies.GetServiceContextForWrite(), Dependencies.GetPortalUser(),
Dependencies.GetPriceList(), WebFormSession.AnonymousIdentification, Target, purchaseMetadata);
var purchasable = quote == null
? null
: SelectFromQuote(quote, purchaseMetadata, options);
TraceMethodInfo("End");
return purchasable;
}
19
Source : WebFormPurchaseDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual IPurchasable SelectFromProductsDirectlyRelatedToPurchaseEnreplacedy(OrganizationServiceContext serviceContext, Enreplacedy purchaseEnreplacedy, string requiredProductsRelationship, Enreplacedy purchaseMetadata, IEnumerable<IPurchasableItemOptions> options)
{
TraceMethodInfo("Start: purchaseEnreplacedy={0}:{1}, requiredProductsRelationship={2}", purchaseEnreplacedy.LogicalName, purchaseEnreplacedy.Id, requiredProductsRelationship);
var requiredProducts = purchaseEnreplacedy.GetRelatedEnreplacedies(serviceContext, requiredProductsRelationship);
var optionalProductsRelationship = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.OptionalProductsRelationship);
var optionalProducts = string.IsNullOrEmpty(optionalProductsRelationship)
? Enumerable.Empty<Enreplacedy>()
: purchaseEnreplacedy.GetRelatedEnreplacedies(serviceContext, optionalProductsRelationship);
var requiredLineItems = requiredProducts.Select(e => new LineItem(e, null, 1, false, e.GetAttributeValue<string>("description"), null, 1));
var optionalLineItems = optionalProducts.Select(e => new LineItem(e, null, 0, true, e.GetAttributeValue<string>("description"), null, 2));
var lineItems = requiredLineItems.Union(optionalLineItems);
var quote = QuoteFunctions.CreateQuote(lineItems, purchaseEnreplacedy.ToEnreplacedyReference(), serviceContext, Dependencies.GetServiceContextForWrite(), Dependencies.GetPortalUser(),
Dependencies.GetPriceList(), WebFormSession.AnonymousIdentification, Target, purchaseMetadata);
var purchasable = quote == null
? null
: SelectFromQuote(quote, purchaseMetadata, options);
TraceMethodInfo("End");
return purchasable;
}
19
Source : ConferenceEventDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override IEnumerable<Enreplacedy> SelectEvents()
{
var serviceContext = Dependencies.GetServiceContext();
//var website = Dependencies.GetWebsite();
var conference = _conference.ToEnreplacedyReference();
var security = Dependencies.GetSecurityProvider();
return serviceContext.CreateQuery("adx_event")
.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_conferenceid") == conference)
.ToArray()
.Where(e => security.Tryreplacedert(serviceContext, e, CrmEnreplacedyRight.Read))
.ToArray();
}
19
Source : WebFormPurchaseDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override IPurchasable Select(IEnumerable<IPurchasableItemOptions> options)
{
if (options == null) throw new ArgumentNullException("options");
TraceMethodInfo("Start");
var purchaseMetadata = WebFormMetadata.FirstOrDefault(IsPurchaseMetadata) ?? new Enreplacedy();
if (WebFormSession.QuoteId != Guid.Empty)
{
TraceMethodInfo("Web form session has quote {0}. Creating purchasable from quote.", WebFormSession.QuoteId);
return SelectFromQuote(new EnreplacedyReference("quote", WebFormSession.QuoteId), purchaseMetadata, options);
}
var serviceContext = Dependencies.GetServiceContext();
Enreplacedy purchaseEnreplacedy;
if (!TryGetPurchaseEnreplacedy(serviceContext, purchaseMetadata, out purchaseEnreplacedy))
{
TraceMethodError("Failed to retrieve purchase enreplacedy from web form step. Returning null.");
return null;
}
TraceMethodInfo("Found purchase enreplacedy: {0}:{1}", purchaseEnreplacedy.LogicalName, purchaseEnreplacedy.Id);
var requiredProductsRelationship = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.RequiredProductsRelationship);
if (!string.IsNullOrEmpty(requiredProductsRelationship))
{
return SelectFromProductsDirectlyRelatedToPurchaseEnreplacedy(serviceContext, purchaseEnreplacedy, requiredProductsRelationship, purchaseMetadata, options);
}
var lineItemRelationship = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemRelationship);
if (!string.IsNullOrEmpty(lineItemRelationship))
{
return SelectFromLineItemEnreplacedies(serviceContext, purchaseEnreplacedy, lineItemRelationship, purchaseMetadata, options);
}
if (purchaseEnreplacedy.LogicalName == "product")
{
return SelectFromProduct(purchaseEnreplacedy, purchaseMetadata, options);
}
if (purchaseEnreplacedy.LogicalName == "quote")
{
return SelectFromQuote(purchaseEnreplacedy.ToEnreplacedyReference(), purchaseMetadata, options);
}
TraceMethodError("Failed to retrieve purchasable using web form step metadata. Returning null.");
return null;
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static Enreplacedy GetPortalConference(this OrganizationServiceContext context, Enreplacedy website)
{
var conferenceName = context.GetSiteSettingValueByName(website, "conference-name");
return context.CreateQuery("adx_conference").FirstOrDefault(c => c.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website.ToEnreplacedyReference()
&& c.GetAttributeValue<string>("adx_name") == conferenceName);
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
[DataObjectMethod(DataObjectMethodType.Select)]
public static IEnumerable<Enreplacedy> GetPublishedEvents(this OrganizationServiceContext context, Enreplacedy site, string portalName = null)
{
site.replacedertEnreplacedyName("adx_website");
var findEvents =
from e in context.CreateQuery("adx_event")
where e.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == site.ToEnreplacedyReference()
select e;
var securityProvider = PortalCrmConfigurationManager.CreateCrmEnreplacedySecurityProvider(portalName);
return findEvents.ToList().Where(e => securityProvider.Tryreplacedert(context, e, CrmEnreplacedyRight.Read));
}
19
Source : ForumDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public IForumThread CreateThread(IForumThread forumThread, IForumPostSubmission forumPost)
{
if (forumThread == null) throw new ArgumentNullException("forumThread");
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Forum={0}: Start", Forum.Id));
var serviceContext = Dependencies.GetServiceContextForWrite();
var enreplacedy = new Enreplacedy("adx_communityforumthread");
enreplacedy["adx_forumid"] = Forum;
enreplacedy["adx_name"] = Truncate(forumThread.Name, 100);
enreplacedy["adx_sticky"] = forumThread.IsSticky;
enreplacedy["adx_isanswered"] = forumThread.IsAnswered;
enreplacedy["adx_locked"] = forumThread.Locked;
enreplacedy["adx_typeid"] = forumThread.ThreadType.EnreplacedyReference;
enreplacedy["adx_lastpostdate"] = forumPost.PostedOn;
serviceContext.AddObject(enreplacedy);
serviceContext.SaveChanges();
var threadDataAdapter = new ForumThreadDataAdapter(enreplacedy.ToEnreplacedyReference(), Dependencies);
threadDataAdapter.CreatePost(forumPost, true);
var createdThread = threadDataAdapter.Select();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Forum={0}: End", Forum.Id));
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Forum, HttpContext.Current, "create_forum_thread", 1, enreplacedy.ToEnreplacedyReference(), "create");
}
return createdThread;
}
19
Source : ForumThreadDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public IForumPost CreatePost(IForumPostSubmission forumPost, bool incrementForumThreadCount = false)
{
if (forumPost == null) throw new ArgumentNullException("forumPost");
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start");
var serviceContext = Dependencies.GetServiceContextForWrite();
var thread = Select();
var locked = thread.Locked;
if (locked) throw new InvalidOperationException("You can't create a new post because the forum is locked.");
var enreplacedy = new Enreplacedy("adx_communityforumpost");
enreplacedy["adx_forumthreadid"] = ForumThread;
enreplacedy["adx_name"] = Truncate(forumPost.Name, 100);
enreplacedy["adx_isanswer"] = forumPost.IsAnswer;
enreplacedy["adx_authorid"] = forumPost.Author.EnreplacedyReference;
enreplacedy["adx_date"] = forumPost.PostedOn;
enreplacedy["adx_content"] = forumPost.Content;
enreplacedy["adx_helpfulvotecount"] = forumPost.HelpfulVoteCount;
serviceContext.AddObject(enreplacedy);
serviceContext.SaveChanges();
var threadEnreplacedy = SelectEnreplacedy(serviceContext);
var threadUpdate = new Enreplacedy(threadEnreplacedy.LogicalName) { Id = threadEnreplacedy.Id };
threadUpdate["adx_lastpostdate"] = forumPost.PostedOn;
threadUpdate["adx_lastpostid"] = enreplacedy.ToEnreplacedyReference();
threadUpdate["adx_postcount"] = threadEnreplacedy.GetAttributeValue<int?>("adx_postcount").GetValueOrDefault() + 1;
if (threadEnreplacedy.GetAttributeValue<EnreplacedyReference>("adx_firstpostid") == null)
{
threadUpdate["adx_firstpostid"] = enreplacedy.ToEnreplacedyReference();
}
serviceContext.Detach(threadEnreplacedy);
serviceContext.Attach(threadUpdate);
serviceContext.UpdateObject(threadUpdate);
serviceContext.SaveChanges();
var enreplacedyReference = enreplacedy.ToEnreplacedyReference();
var forumDataAdapter = new ForumDataAdapter(threadEnreplacedy.GetAttributeValue<EnreplacedyReference>("adx_forumid"), Dependencies);
forumDataAdapter.UpdateLatestPost(enreplacedyReference, incrementForumThreadCount);
foreach (var attachment in forumPost.Attachments)
{
IAnnotationDataAdapter da = new AnnotationDataAdapter(Dependencies);
da.CreateAnnotation(enreplacedyReference, string.Empty, string.Empty, attachment.Name, attachment.ContentType,
attachment.Content);
}
var post = SelectPost(enreplacedyReference.Id);
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Forum, HttpContext.Current, "create_forum_post", 1, post.Enreplacedy.ToEnreplacedyReference(), "create");
}
return post;
}
See More Examples