public void AddProductToCart(Entity product, Entity uom, string priceListName, int quantity)
        {
            product.AssertEntityName("product");

            var items = GetCartItems().Where(i => product.ToEntityReference().Equals(i.GetAttributeValue <EntityReference>("adx_productid")));

            // Check if this product is already in the cart
            if (items.Any())
            {
                //update the first item
                var item = items.FirstOrDefault() as ShoppingCartItem;

                item.Quantity = item.Quantity + (quantity == 0 ? 1 : quantity);
                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 priceListItem = _context.GetPriceListItemByPriceListNameAndUom(product, uom.Id, (!(string.IsNullOrEmpty(priceListName))
                                ? priceListName : _context.GetDefaultPriceListName(website))) ??
                                _context.GetPriceListItemByPriceListName(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 shoppingCartItem = new Entity("adx_shoppingcartitem");

            shoppingCartItem["adx_quantity"]       = (decimal)quantity;
            shoppingCartItem["adx_name"]           = "{0}-{1}-{2}".FormatWith(Entity.GetAttributeValue <string>("adx_name"), product.GetAttributeValue <string>("name"), DateTime.UtcNow);
            shoppingCartItem["adx_shoppingcartid"] = Entity.ToEntityReference();
            shoppingCartItem["adx_productid"]      = product.ToEntityReference();
            shoppingCartItem["adx_uomid"]          = uom.ToEntityReference();
            if (priceListItem != null)
            {
                shoppingCartItem["adx_productpricelevelid"] = priceListItem.GetAttributeValue <EntityReference>("pricelevelid");
                shoppingCartItem["adx_quotedprice"]         = priceListItem.GetAttributeValue <Money>("amount");
            }

            _context.AddObject(shoppingCartItem);

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

            _context.UpdateObject(Entity);

            _context.SaveChanges();
        }
Exemple #2
0
        /// <summary>
        /// Called by the plugin and disassociates the descendants of the account.
        /// </summary>
        public void DisassociateDescendants()
        {
            Trace(string.Format(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, UnderlyingSystemTypeName, MethodBase.GetCurrentMethod().Name));

            IList <Account> descendants = CrmService.GetAccountDescendants(PreBusinessEntity.Id).ToList();

            foreach (Account account in descendants)
            {
                account.ParentAccount = null;

                if (OrganizationServiceContext.IsAttached(account))
                {
                    OrganizationServiceContext.UpdateObject(account);
                }
                else
                {
                    OrganizationServiceContext.AddObject(account);
                }
            }

            if (descendants.Any())
            {
                // Save changes in a single call to include all in an atomic transaction
                Trace(string.Format(CultureInfo.InvariantCulture, "{0}: Saving the entity in CRM. at {1}", UnderlyingSystemTypeName, MethodBase.GetCurrentMethod().Name));
                CrmService.SaveChanges(SaveChangesOptions.None);
            }

            Trace(string.Format(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, UnderlyingSystemTypeName, MethodBase.GetCurrentMethod().Name));
        }
Exemple #3
0
        public void When_Deleting_Using_Organization_Context_Record_Should_Be_Deleted()
        {
            var context = new XrmFakedContext();

            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var account = new Account()
            {
                Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69"
            };

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                ctx.AddObject(account);
                ctx.SaveChanges();
            }

            Assert.NotNull(service.Retrieve(Account.EntityLogicalName, account.Id, new ColumnSet(true)));

            using (var ctx = new OrganizationServiceContext(service))
            {
                ctx.Attach(account);
                ctx.DeleteObject(account);
                ctx.SaveChanges();

                var retrievedAccount = ctx.CreateQuery <Account>().SingleOrDefault(acc => acc.Id == account.Id);
                Assert.Null(retrievedAccount);
            }
        }
Exemple #4
0
        /// <summary>
        /// Add a note to an entity.
        /// </summary>
        /// <param name="context">The service context</param>
        /// <param name="entity">The entity to which a note will be attached.</param>
        /// <param name="noteTitle"></param>
        /// <param name="noteText">The text of the note.</param>
        /// <param name="fileName">The name of the file to attach to this note.</param>
        /// <param name="contentType">The MIME type of the file to attach to this note.</param>
        /// <param name="fileContent">The raw byte data of the file to attach to this note.</param>
        /// <returns>True if successful; otherwise, false.</returns>
        /// <remarks>
        /// <para>The provided <paramref name="entity"/> must already be persisted to the CRM for this operation to succeed.</para>
        /// <para>It it not necessary to SaveChanges after this operation--this operation fully persists this note to CRM.</para>
        /// </remarks>
        public static bool AddNoteAndSave(this OrganizationServiceContext context, Entity entity, string noteTitle, string noteText, string fileName, string contentType, byte[] fileContent)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

            var entityName = entity.LogicalName;

            var note = new Entity("annotation");

            note.SetAttributeValue("subject", noteTitle);
            note.SetAttributeValue("notetext", noteText);
            note.SetAttributeValue("isdocument", false);
            note.SetAttributeValue("objectid", entity.ToEntityReference());
            note.SetAttributeValue("objecttypecode", entityName);

            if (fileContent != null && fileContent.Length > 0 && !string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(contentType))
            {
                note.SetAttributeValue("documentbody", Convert.ToBase64String(fileContent));
                note.SetAttributeValue("filename", EnsureValidFileName(fileName));
                note.SetAttributeValue("mimetype", contentType);
            }

            context.AddObject(note);
            context.SaveChanges();

            return(true);
        }
Exemple #5
0
        public Entity NewEntity(string entityName, OrganizationServiceContext context)
        {
            var newEntity = new Entity(entityName);

            context.AddObject(newEntity);
            return(newEntity);
        }
Exemple #6
0
 /// <summary>
 /// Creates a new entity and returns the result
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 public Entity Create(Entity entity)
 {
     using (var ctx = new OrganizationServiceContext(Svc))
     {
         ctx.AddObject(entity);
         ctx.SaveChanges();
         return(entity);
     }
 }
Exemple #7
0
        private static void SetOrderProducts(Entity shoppingCart, OrganizationServiceContext context, Guid salesOrderGuid, Money tax)
        {
            bool first = true;

            var cartItems = context.CreateQuery("adx_shoppingcartitem")
                            .Where(
                qp =>
                qp.GetAttributeValue <EntityReference>("adx_shoppingcartid").Id ==
                shoppingCart.GetAttributeValue <Guid>("adx_shoppingcartid")).ToList();

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

                var orderProduct = new Entity("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 <EntityReference>("adx_productid").Id);
                var unit = context.CreateQuery("uom")
                           .FirstOrDefault(
                    uom => uom.GetAttributeValue <Guid>("uomid") == item.GetAttributeValue <EntityReference>("adx_uomid").Id) ??
                           context.CreateQuery("uom").FirstOrDefault(uom => uom.GetAttributeValue <Guid>("uomid")
                                                                     == product.GetAttributeValue <EntityReference>("defaultuomid").Id);

                /*var unit = context.CreateQuery("uom")
                 *      .FirstOrDefault(
                 *              uom => uom.GetAttributeValue<Guid>("uomid") == item.GetAttributeValue<EntityReference>("adx_uomid").Id);*/

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

                //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);
            }
        }
Exemple #8
0
        static void CriacaoLinq(OrganizationServiceProxy serviceProxy)
        {
            OrganizationServiceContext context = new OrganizationServiceContext(serviceProxy);

            for (int i = 0; i < 5; i++)
            {
                Entity account = new Entity("account");
                account["name"] = String.Format("Conta Linq {0}", i.ToString());
                context.AddObject(account);
            }
            context.SaveChanges();
        }
Exemple #9
0
        public static void CreateEventRegistration(this OrganizationServiceContext serviceContext, EntityReference userReference,
                                                   EntityReference eventReference, EntityReference eventScheduleReference, DateTime registrationDate)
        {
            var registration = new Entity("adx_eventregistration");

            registration["adx_attendeeid"]            = userReference;
            registration["adx_eventid"]               = eventReference;
            registration["adx_eventscheduleid"]       = eventScheduleReference;
            registration["adx_registrationdate"]      = registrationDate;
            registration["adx_registrationconfirmed"] = true;

            serviceContext.AddObject(registration);
            serviceContext.SaveChanges();
        }
        private static Entity EarlyBoundCreateApplication(OrganizationServiceContext service, defra_ApplicationType applicationType = defra_ApplicationType.NewApplication, Guid?permitId = null)
        {
            defra_application newApplicationEntity =
                new defra_application
            {
                defra_name            = "Integration Test " + DateTime.Now,
                defra_applicationtype = new OptionSetValue((int)applicationType),
                defra_permitId        = permitId.HasValue ? new EntityReference(Permit.EntityLogicalName, permitId.Value) : null
            };

            service.AddObject(newApplicationEntity);
            service.SaveChanges();
            return(newApplicationEntity);
        }
Exemple #11
0
        private void Create()
        {
            var user = new Entity(MemberEntityName);

            CreatedAt = LastLogin = DateTime.UtcNow;

            user.SetAttributeValue(AttributeMapUsername, UserId);
            user.SetAttributeValue(AttributeMapCreatedAt, CreatedAt.Value);
            user.SetAttributeValue(AttributeMapLastLogin, LastLogin);
            user.SetAttributeValue(AttributeMapApproved, Approved);

            _context.AddObject(user);

            _context.SaveChanges();
        }
Exemple #12
0
        public Guid CreateAccount(string name)
        {
            var entity = new Entity("account")
            {
                Attributes = new Microsoft.Xrm.Sdk.AttributeCollection
                {
                    { "name", name }
                }
            };

            _context.AddObject(entity);

            var results = _context.SaveChanges();

            return(entity.Id);
        }
Exemple #13
0
        private static Entity GetOrderCustomer(Dictionary <string, string> values, OrganizationServiceContext context, Entity shoppingCart)
        {
            Guid customerID;

            Entity customer;

            if (shoppingCart.GetAttributeValue <EntityReference>("adx_contactid") != null)
            {
                customerID = shoppingCart.GetAttributeValue <EntityReference>("adx_contactid").Id;
            }
            else
            {
                customerID = Guid.NewGuid();
                customer   = new Entity("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);
        }
Exemple #14
0
        public void Create(T entity)
        {
            try
            {
                service.AddObject(entity);

                service.SaveChanges(SaveChangesOptions.None);
            }
            catch (Exception)
            {
                // if entity was attached to service, but error occured while creating this entity, we must deattach entity from service to be able to create entities with this service
                if (service.IsAttached(entity))
                {
                    service.Detach(entity);
                }

                throw;
            }
        }
        /// <summary>
        /// Adds a Forum Thread Tag tag association by name to a Forum Thread.
        /// </summary>
        /// <param name="threadId">The ID of the Forum Thread whose tags will be affected.</param>
        /// <param name="tagName">
        /// The name of the tag to be associated with the thread (will be created if necessary).
        /// </param>
        /// <remarks>
        /// <para>
        /// This operation may call SaveChanges on this context--please ensure any queued
        /// changes are mananged accordingly.
        /// </para>
        /// </remarks>
        public static void AddTagToForumThreadAndSave(this OrganizationServiceContext context, Guid threadId, string tagName)
        {
            if (context.MergeOption == MergeOption.NoTracking)
            {
                throw new ArgumentException("The OrganizationServiceContext.MergeOption cannot be MergeOption.NoTracking.", "context");
            }

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

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

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

            var tag = GetForumThreadTagByName(context, tagName);

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

                tag["adx_name"] = tagName;

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

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

                context.SaveChanges();
            }
        }
Exemple #16
0
        public void When_Creating_Using_Organization_Context_Without_Saving_Changes_Record_Should_Not_Be_Created()
        {
            var context = new XrmFakedContext();

            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var account = new Account()
            {
                Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69"
            };

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                ctx.AddObject(account);

                var retrievedAccount = ctx.CreateQuery <Account>().SingleOrDefault(acc => acc.Id == account.Id);
                Assert.Null(retrievedAccount);
            }
        }
        /// <summary>
        /// Adds a Page Tagtag association by name to a Web Page.
        /// </summary>
        /// <param name="pageId">The ID of the Web Page whose tags will be affected.</param>
        /// <param name="tagName">
        /// The name of the tag to be associated with the page (will be created if necessary).
        /// </param>
        /// <remarks>
        /// <para>
        /// This operation may call SaveChanges on this context--please ensure any queued
        /// changes are mananged accordingly.
        /// </para>
        /// </remarks>
        public static void AddTagToWebPageAndSave(this OrganizationServiceContext context, Guid pageId, string tagName)
        {
            if (context.MergeOption == MergeOption.NoTracking)
            {
                throw new ArgumentException("The OrganizationServiceContext.MergeOption cannot be MergeOption.NoTracking.", "context");
            }

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

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

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

            var tag = context.GetPageTagByName(tagName);

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

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

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

                context.SaveChanges();
            }
        }
        public static void AddThreadAlertAndSave(this OrganizationServiceContext context, Entity thread, Entity contact)
        {
            thread.AssertEntityName("adx_communityforumthread");
            contact.AssertEntityName("contact");

            var forumAlerts = thread.GetRelatedEntities(context, "adx_communityforumthread_communityforumaalert");

            var alert = (
                from e in forumAlerts
                where e.GetAttributeValue <EntityReference>("adx_subscriberid") == contact.ToEntityReference()
                select e).FirstOrDefault();

            if (alert == null)
            {
                alert = new Entity("adx_communityforumalert");
                alert["adx_subscriberid"] = contact.ToEntityReference();
                alert["adx_threadid"]     = thread.ToEntityReference();

                context.AddObject(alert);
            }
            context.SaveChanges();
        }
Exemple #19
0
        /// <summary>
        /// Creates a new record in the ExecutionContext entity and populates all the needed fields
        /// including a serialized version of the PluginExecutioncontext.
        /// </summary>
        /// <returns>void()</returns>
        public void StoreExecutionContext()
        {
            Trace(string.Format(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, UnderlyingSystemTypeName, MethodBase.GetCurrentMethod().Name));

            // System.Threading.Thread.Sleep(5000); // intentional delay for testing purposes - to be removed

            if (PluginExecutionContext.MessageName.Equals(PlatformMessageHelper.Update))
            {
                System.Threading.Thread.Sleep(100 * PluginExecutionContext.Depth);
            }

            DateTimeNow = DateTime.UtcNow;

            string content = SerializationHelper.SerializeJson(ExecutionContext); // does not serialize nested object ParentContext and therefore it will be NULL

            ExecutionContext ec = new ExecutionContext
            {
                ContainsParentContext = PluginExecutionContext.ParentContext != null,
                Content               = content,
                ContentLength         = content.Length,
                CorrelationId         = PluginExecutionContext.CorrelationId.ToString(),
                Depth                 = PluginExecutionContext.Depth,
                EntityId              = PluginExecutionContext.PrimaryEntityId.ToString(),
                EntityName            = PluginExecutionContext.PrimaryEntityName,
                InitiatingUser        = new EntityReference(SystemUserEntityLogicalName, PluginExecutionContext.InitiatingUserId),
                MessageName           = PluginExecutionContext.MessageName,
                OperationId           = PluginExecutionContext.OperationId.ToString(),
                ParentIsMainOperation = PluginExecutionContext.ParentContext != null && PluginExecutionContext.ParentContext.Stage == (int)SdkMessageProcessingStepStage.MainOperation,
                Stage                 = PluginExecutionContext.Stage,
                Subject               = DateTimeNow.ToString(DateTimeFormat, CultureInfo.InvariantCulture),
                User = new EntityReference(SystemUserEntityLogicalName, PluginExecutionContext.UserId),
            };

            OrganizationServiceContext.AddObject(ec);

            CrmService.SaveChanges(SaveChangesOptions.None);

            Trace(string.Format(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, UnderlyingSystemTypeName, MethodBase.GetCurrentMethod().Name));
        }
Exemple #20
0
        public static EntityReference GetQuoteCustomer(OrganizationServiceContext serviceContext, EntityReference 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 Entity("contact");

            visitor["firstname"]    = "Anonymous Portal User";
            visitor["lastname"]     = visitorId;
            visitor["adx_username"] = "******".FormatWith(visitorId);

            serviceContext.AddObject(visitor);
            serviceContext.SaveChanges();

            return(visitor.ToEntityReference());
        }
Exemple #21
0
        public EntityReferenceCollection CreateAContact(Guid _accountId, Entity account)
        {
            Contact contact = new Contact()
            {
                FirstName                = fName,
                LastName                 = lName,
                Address1_Line1           = "23 Market St.",
                Address1_City            = "Sammamish",
                Address1_StateOrProvince = "MT",
                Address1_PostalCode      = "99999",
                Telephone1               = "12345678",
                EMailAddress1            = fName + "." + lName + "@" + accountName + ".com",
                Id = Guid.NewGuid()
            };

            _contactId = contact.Id;
            _orgContext.AddObject(contact);

            Console.WriteLine("Service created with First Name {0} and Last Name {1}", contact.FirstName, contact.LastName);

            //Create a collection of the entity id(s) that will be associated to the contact.
            EntityReferenceCollection relatedEntities = new EntityReferenceCollection();

            relatedEntities.Add(new EntityReference("account", _accountId));

            _orgContext.Attach(account);
            //_orgContext.Attach(contact);
            _orgContext.AddLink(
                account,
                new Relationship("contact_customer_accounts"),
                contact);
            //SaveChangesHelper(contact, account);
            Console.WriteLine("and adding contact to account's contact list.");

            return(relatedEntities);
        }
        protected override void ProcessRequest(HttpContext context, ICmsEntityServiceProvider serviceProvider, Guid portalScopeId, IPortalContext portal, OrganizationServiceContext serviceContext, Entity entity, CmsEntityMetadata entityMetadata, ICrmEntitySecurityProvider security)
        {
            var relationshipSchemaName = string.IsNullOrWhiteSpace(RelationshipSchemaName) ? context.Request.Params["relationshipSchemaName"] : RelationshipSchemaName;

            if (string.IsNullOrWhiteSpace(relationshipSchemaName))
            {
                throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request.");
            }

            var match = _relationshipSchemaNameRegex.Match(relationshipSchemaName);

            if (!match.Success)
            {
                throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request.");
            }

            var schemaName = match.Groups["schemaName"].Value;

            if (string.IsNullOrWhiteSpace(schemaName))
            {
                throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request.");
            }

            var entityRole = match.Groups["entityRole"].Value;

            EntityRole parsedRole;

            var relationship = new Relationship(schemaName)
            {
                PrimaryEntityRole = Enum.TryParse(entityRole, true, out parsedRole) ? new EntityRole?(parsedRole) : null
            };

            CmsEntityRelationshipInfo relationshipInfo;

            if (!entityMetadata.TryGetRelationshipInfo(relationship, out relationshipInfo))
            {
                throw new CmsEntityServiceException(HttpStatusCode.NotFound, "Entity relationship not found.");
            }

            // If the current request entity is the current website, do security handling here, since we skipped it earlier.
            if (entity.ToEntityReference().Equals(portal.Website.ToEntityReference()))
            {
                AssertRequestEntitySecurity(portal, serviceContext, entity, security, CreateWebsiteAccessPermissionProvider(portal), relationshipInfo);
            }

            if (IsRequestMethod(context.Request, "GET"))
            {
                if (relationshipInfo.IsCollection)
                {
                    var readableRelatedEntities = entity.GetRelatedEntities(serviceContext, relationship)
                                                  .Where(e => security.TryAssert(serviceContext, e, CrmEntityRight.Read));

                    var entityMetadataLookup = new Dictionary <string, CmsEntityMetadata>();

                    var entityJsonObjects = readableRelatedEntities.Select(e =>
                    {
                        CmsEntityMetadata relatedEntityMetadata;

                        if (!entityMetadataLookup.TryGetValue(e.LogicalName, out relatedEntityMetadata))
                        {
                            relatedEntityMetadata = new CmsEntityMetadata(serviceContext, e.LogicalName);

                            entityMetadataLookup[e.LogicalName] = relatedEntityMetadata;
                        }

                        return(GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, e, relatedEntityMetadata));
                    });

                    WriteResponse(context.Response, new JObject
                    {
                        { "d", new JArray(entityJsonObjects) }
                    });
                }
                else
                {
                    var relatedEntity = entity.GetRelatedEntity(serviceContext, relationship);

                    if (relatedEntity == null)
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.NotFound, "Related entity not found.");
                    }

                    if (!security.TryAssert(serviceContext, relatedEntity, CrmEntityRight.Read))
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.Forbidden, "Related entity access denied.");
                    }

                    WriteResponse(context.Response, new JObject
                    {
                        { "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, relatedEntity, new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName)) }
                    });
                }

                return;
            }

            if (IsRequestMethod(context.Request, "POST"))
            {
                if (relationshipInfo.IsCollection)
                {
                    OneToManyRelationshipMetadata relationshipMetadata;

                    if (!entityMetadata.TryGetOneToManyRelationshipMetadata(relationship, out relationshipMetadata))
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the one-to-many relationship metadata for relationship {0} on entity type".FormatWith(relationship.ToSchemaName("."), entity.LogicalName));
                    }

                    var relatedEntity         = CreateEntityOfType(serviceContext, relationshipMetadata.ReferencingEntity);
                    var relatedEntityMetadata = new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName);

                    var extensions = UpdateEntityFromJsonRequestBody(context.Request, serviceContext, relatedEntity, relatedEntityMetadata);

                    var preImage = relatedEntity.Clone(false);

                    // Ensure the reference to the target entity is set.
                    relatedEntity.SetAttributeValue(relationshipMetadata.ReferencingAttribute, new EntityReference(entity.LogicalName, entity.GetAttributeValue <Guid>(relationshipMetadata.ReferencedAttribute)));

                    serviceProvider.InterceptChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, CmsEntityOperation.Create, preImage);

                    serviceContext.AddObject(relatedEntity);

                    serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, extensions, CmsEntityOperation.Create);

                    serviceContext.SaveChanges();

                    var refetchedEntity = serviceContext.CreateQuery(relatedEntity.LogicalName)
                                          .FirstOrDefault(e => e.GetAttributeValue <Guid>(relatedEntityMetadata.PrimaryIdAttribute) == relatedEntity.Id);

                    if (refetchedEntity == null)
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created entity.");
                    }

                    WriteResponse(context.Response, new JObject
                    {
                        { "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEntity, relatedEntityMetadata) }
                    }, HttpStatusCode.Created);
                }
                else
                {
                    OneToManyRelationshipMetadata relationshipMetadata;

                    if (!entityMetadata.TryGetManyToOneRelationshipMetadata(relationship, out relationshipMetadata))
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the many-to-one relationship metadata for relationship {0} on entity type".FormatWith(relationship.ToSchemaName("."), entity.LogicalName));
                    }

                    var relatedEntity         = CreateEntityOfType(serviceContext, relationshipMetadata.ReferencedEntity);
                    var relatedEntityMetadata = new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName);

                    var extensions = UpdateEntityFromJsonRequestBody(context.Request, serviceContext, relatedEntity, relatedEntityMetadata);

                    serviceProvider.InterceptChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, CmsEntityOperation.Create);

                    serviceContext.AddObject(relatedEntity);
                    serviceContext.AddLink(relatedEntity, relationship, entity);

                    serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, extensions, CmsEntityOperation.Create);

                    serviceContext.SaveChanges();

                    var refetchedEntity = serviceContext.CreateQuery(relatedEntity.LogicalName)
                                          .FirstOrDefault(e => e.GetAttributeValue <Guid>(relatedEntityMetadata.PrimaryIdAttribute) == relatedEntity.Id);

                    if (refetchedEntity == null)
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created entity.");
                    }

                    WriteResponse(context.Response, new JObject
                    {
                        { "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEntity, relatedEntityMetadata) }
                    }, HttpStatusCode.Created);
                }

                return;
            }

            throw new CmsEntityServiceException(HttpStatusCode.MethodNotAllowed, "Request method {0} not allowed for this resource.".FormatWith(context.Request.HttpMethod));
        }
        /// <summary>
        /// A plug-in that creates a follow-up task activity when a new account is created.
        /// </summary>
        /// <remarks>Register this plug-in on the Create message, account entity,
        /// and asynchronous mode.
        /// </remarks>
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext ctx = new OrganizationServiceContext(service);
            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {

                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != "gcbase_fundcentre")
                    return;

                FaultException ex1 = new FaultException();
                //throw new InvalidPluginExecutionException("test", ex1);

                if (entity.Attributes.Contains("gcbase_estimatedannualbudget") && entity.Attributes.Contains("gcbase_startdate") && entity.Attributes.Contains("gcbase_enddate"))
                {
                    try
                    {
                        //create budget lines
                         //throw new InvalidPluginExecutionException("testing", ex1);
                        int[] fiscalYears = new FiscalYear(entity.GetAttributeValue<DateTime>("gcbase_startdate"), entity.GetAttributeValue<DateTime>("gcbase_enddate")).getFiscalYears();

                        QueryExpression existingFundCentreBudgets = new QueryExpression
                        {
                            EntityName = "gcbase_fundcentrebudget",
                            ColumnSet = new ColumnSet("gcbase_fundcentre", "gcbase_fiscalyear"),
                            Criteria = new FilterExpression
                            {
                                Conditions = {
                                    new ConditionExpression {
                                    AttributeName = "gcbase_fundcentre",
                                    Operator = ConditionOperator.Equal,
                                    Values = { entity.Id }
                                    }
                                }
                            }
                        };

                        DataCollection<Entity> fundCentreBudgetsToDelete = service.RetrieveMultiple(existingFundCentreBudgets).Entities;

                        if (fundCentreBudgetsToDelete.Count > 0)
                        {
                            // here we should validate if we have projects pending instead of deleting budgets

                            var currentYears = fundCentreBudgetsToDelete.Select(s => (int)s.GetAttributeValue<OptionSetValue>("gcbase_fiscalyear").Value).ToArray();
                            var newYears = fiscalYears.ToArray();
                            //newYears.Except(currentYears);

                            var illegalYears = currentYears.Except(newYears);

                            if (illegalYears.Count() > 0)
                            {
                                throw new InvalidPluginExecutionException(@"Cannot save your new start and end dates because there are budgets entered in
                                        fiscal years that fall outside of those dates. If you want to revise the dates please first delete the budgets in
                                        fiscal years: " + string.Join("-", illegalYears) + " and try again!", ex1);
                            }
                            else
                            {
                                foreach (Entity fcb in fundCentreBudgetsToDelete)
                                {
                                    service.Delete("gcbase_fundcentrebudget", fcb.Id);
                                }
                            }
                        }

                        Array values = Enum.GetValues(typeof(goal_fiscalyear));
                        string[] fys = new string[fiscalYears.Count()];
                        int index = 0;

                        //throw new InvalidPluginExecutionException("testing", ex1);

                        //EntityReference fundRef = new EntityReference("gcbase_fund", preEntity.GetAttributeValue<EntityReference>("gcbase_fund").Id);
                        var fundEntity = service.Retrieve("gcbase_fund", entity.GetAttributeValue<EntityReference>("gcbase_fund").Id, new ColumnSet("gcbase_name", "gcbase_fundid", "gcbase_fundtype"));
                        var fundTypeEntity = service.Retrieve("gcbase_fundtype", fundEntity.GetAttributeValue<EntityReference>("gcbase_fundtype").Id, new ColumnSet("gcbase_name"));
                        var budgetEntryName = entity.GetAttributeValue<string>("gcbase_name") + "-" + fundEntity.GetAttributeValue<string>("gcbase_name") + "-" + fundTypeEntity.GetAttributeValue<string>("gcbase_name");
                      //  throw new InvalidPluginExecutionException(fiscalYears.Count().ToString(), ex1);
                        foreach (int year in fiscalYears)
                        {
                            var amount = entity.GetAttributeValue<Money>("gcbase_estimatedannualbudget");

                            if (amount.Value > 0)
                            {
                                Entity fundCentreBudget = new Entity("gcbase_fundcentrebudget");
                                // fundCentreBudget.Id = Guid.NewGuid();
                                fundCentreBudget["gcbase_amount"] = amount;
                                fys[index] = (string)Enum.GetName(typeof(goal_fiscalyear), year);
                                OptionSetValue fy = new OptionSetValue();
                                fy.Value = year;
                                fundCentreBudget["gcbase_fiscalyear"] = fy;

                                EntityReference fundCentre = new EntityReference("gcbase_fundcentre", entity.Id);
                                fundCentreBudget["gcbase_fundcentre"] = fundCentre;
                                fundCentreBudget["gcbase_name"] = budgetEntryName + "-" + fy.Value;
                                // ctx.Attach(fundCentreBudget)
                                ctx.AddObject(fundCentreBudget);
                                ctx.SaveChanges();
                            }

                            index++;
                        }

                    }

                    catch (FaultException<OrganizationServiceFault> ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the PostFundCentreCreate plug-in.", ex);
                    }

                    catch (Exception ex)
                    {
                        tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
                        throw;
                    }

                }

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

            var supportPlan = new Entity("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.ToEntityReference();
                supportPlan.Attributes["adx_billtocustomer"] = account.ToEntityReference();
                accountName = account.GetAttributeValue <string>("name");
            }
            else if (contact != null)
            {
                supportPlan.Attributes["adx_customercontact"] = contact.ToEntityReference();
                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.ToEntityReference();
            }

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

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

            try
            {
                context.AddObject(supportPlan);

                context.SaveChanges();
            }
            catch
            {
            }

            supportPlan = context.CreateQuery("adx_supportplan")
                          .FirstOrDefault(sr => sr.GetAttributeValue <Guid>("adx_supportplanid") == supportPlanId);
            return(supportPlan);
        }
Exemple #25
0
        /// <summary>
        /// This method first connects to the Organization service and creates the
        /// OrganizationServiceContext. Then, several entity creation and relationship
        /// operations are performed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetBasicContextExamples1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
                                                                    serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    CreateRequiredRecords();

                    // The OrganizationServiceContext is an object that wraps the service
                    // proxy and allows creating/updating multiple records simultaneously.
                    _orgContext = new OrganizationServiceContext(_service);

                    // Create a new contact called Mary Kay Andersen.
                    var contact = new Contact()
                    {
                        FirstName                = "Mary Kay",
                        LastName                 = "Andersen",
                        Address1_Line1           = "23 Market St.",
                        Address1_City            = "Sammamish",
                        Address1_StateOrProvince = "MT",
                        Address1_PostalCode      = "99999",
                        Telephone1               = "12345678",
                        EMailAddress1            = "*****@*****.**",
                        Id = Guid.NewGuid()
                    };
                    _contactId = contact.Id;
                    _orgContext.AddObject(contact);
                    Console.Write("Instantiating contact, ");

                    // Create an account called Contoso.
                    var account = new Account()
                    {
                        Name          = "Contoso",
                        Address1_City = "Redmond",
                        // set the account category to 'Preferred Customer'
                        AccountCategoryCode = new OptionSetValue(1),
                        LastUsedInCampaign  = DateTime.Now,
                        MarketCap           = new Money(120000),
                        DoNotEMail          = true,
                        Description         = "Contoso is a fictional company!",
                        Id = Guid.NewGuid(),
                    };
                    _accountId = account.Id;
                    Console.Write("instantiating account, ");

                    // Set Mary Kay Andersen as the primary contact
                    _orgContext.AddRelatedObject(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and creating both records in CRM.");

                    // Remove the primary contact value from Mary Kay Andersen
                    _orgContext.Attach(contact);
                    _orgContext.DeleteLink(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.Write("Removing primary contact status, ");

                    // Add Mary Kay Andersen to the contact list for the account Contoso.
                    _orgContext.Attach(account);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        account,
                        new Relationship("contact_customer_accounts"),
                        contact);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and adding contact to account's contact list.");

                    // Add a note with a document attachment to the contact's record.
                    var attachment = File.OpenRead("sample.txt");
                    var data       = new byte[attachment.Length];
                    attachment.Read(data, 0, (int)attachment.Length);

                    var note = new Annotation()
                    {
                        Subject      = "Note subject...",
                        NoteText     = "Note Details....",
                        DocumentBody = Convert.ToBase64String(data),
                        FileName     = Path.GetFileName(attachment.Name),
                        MimeType     = "text/plain",
                        Id           = Guid.NewGuid(),
                        // Associate the note to the contact.
                        ObjectId       = contact.ToEntityReference(),
                        ObjectTypeCode = Contact.EntityLogicalName
                    };
                    _annotationId = note.Id;
                    Console.Write("Instantiating a note, ");
                    _orgContext.AddObject(note);
                    _orgContext.Attach(contact);
                    // Set the contact as the Regarding attribute of the note.
                    _orgContext.AddLink(
                        contact,
                        new Relationship("Contact_Annotation"),
                        note);
                    SaveChangesHelper(note, contact);
                    Console.WriteLine("creating the note in CRM and linking to contact.");

                    // Change the owning user of the contact Mary Kay Andersen
                    // Find a user with an email address of "*****@*****.**"
                    var newOwner = (from u in _orgContext.CreateQuery <SystemUser>()
                                    where u.InternalEMailAddress == "*****@*****.**"
                                    select u).Single();
                    AssignRequest assignRequest = new AssignRequest()
                    {
                        Target   = contact.ToEntityReference(),
                        Assignee = newOwner.ToEntityReference()
                    };
                    _orgContext.Execute(assignRequest);
                    Console.WriteLine("Changing ownership of contact record.");

                    // Create a new price list called Retail Price List.
                    var priceList = new PriceLevel()
                    {
                        Name        = "Retail Price List",
                        BeginDate   = DateTime.Now,
                        EndDate     = DateTime.Now,
                        Description = "Contoso's primary pricelist.",
                        Id          = Guid.NewGuid()
                    };
                    _priceLevelId = priceList.Id;
                    _orgContext.AddObject(priceList);
                    Console.Write("Instantiating price list ");

                    // Create a new product called Widget A.
                    var newProduct = new Product()
                    {
                        Name             = "Widget A",
                        Description      = "Industrial widget for hi-tech industries",
                        ProductStructure = new OptionSetValue(1), // 1 = Product
                        QuantityOnHand   = 2,
                        ProductNumber    = "WIDG-A",
                        Price            = new Money(decimal.Parse("12.50")),
                        QuantityDecimal  = 2, // Sets the Decimals Supported value
                        Id = Guid.NewGuid(),
                        DefaultUoMScheduleId = new EntityReference(
                            UoMSchedule.EntityLogicalName,
                            _orgContext.CreateQuery <UoMSchedule>().First().Id),
                        DefaultUoMId = new EntityReference(
                            UoM.EntityLogicalName,
                            _orgContext.CreateQuery <UoM>().First().Id)
                    };
                    _productId = newProduct.Id;
                    _orgContext.AddObject(newProduct);
                    Console.WriteLine("and product.");
                    SaveChangesHelper(priceList, newProduct);

                    // Add Widget A to the Retail Price List.
                    var priceLevelProduct = new ProductPriceLevel()
                    {
                        ProductId    = newProduct.ToEntityReference(),
                        UoMId        = newProduct.DefaultUoMId,
                        Amount       = new Money(decimal.Parse("12.50")),
                        PriceLevelId = priceList.ToEntityReference(),
                        Id           = Guid.NewGuid()
                    };
                    _productPriceLevelId = priceLevelProduct.Id;
                    _orgContext.AddObject(priceLevelProduct);
                    Console.Write("Associating product to price list, ");

                    // Publish the product
                    SetStateRequest publishRequest = new SetStateRequest
                    {
                        EntityMoniker = newProduct.ToEntityReference(),
                        State         = new OptionSetValue((int)ProductState.Active),
                        Status        = new OptionSetValue(1)
                    };
                    _serviceProxy.Execute(publishRequest);
                    Console.WriteLine("and publishing the product.");


                    // Create a new quote for Contoso.
                    var newQuote = new Quote()
                    {
                        Name = "Quotation for Contoso",
                        // Sets the pricelist to the one we've just created
                        PriceLevelId = priceList.ToEntityReference(),
                        Id           = Guid.NewGuid(),
                        CustomerId   = account.ToEntityReference()
                    };
                    _quoteId = newQuote.Id;
                    _orgContext.AddObject(newQuote);
                    _orgContext.Attach(account);
                    _orgContext.AddLink(
                        newQuote,
                        new Relationship("quote_customer_accounts"),
                        account);
                    Console.Write("Instantiating a quote, ");

                    // Add a quote product to this quote.
                    var quoteProduct = new QuoteDetail()
                    {
                        ProductId = newProduct.ToEntityReference(),
                        Quantity  = 1,
                        QuoteId   = newQuote.ToEntityReference(),
                        UoMId     = newProduct.DefaultUoMId,
                        Id        = Guid.NewGuid()
                    };
                    _quoteDetailId = quoteProduct.Id;
                    _orgContext.AddObject(quoteProduct);
                    Console.WriteLine("and adding product to quote.");

                    // Create a sales opportunity with Contoso.
                    var oppty = new Opportunity()
                    {
                        Name = "Interested in Widget A",
                        EstimatedCloseDate        = DateTime.Now.AddDays(30.0),
                        EstimatedValue            = new Money(decimal.Parse("300000.00")),
                        CloseProbability          = 25,                    // 25% probability of closing this deal
                        IsRevenueSystemCalculated = false,                 // user-calculated revenue
                        OpportunityRatingCode     = new OptionSetValue(2), // warm
                        CustomerId = account.ToEntityReference(),
                        Id         = Guid.NewGuid()
                    };
                    _opportunityId = oppty.Id;
                    _orgContext.AddObject(oppty);
                    Console.Write("Instantiating opportunity, ");
                    //_orgContext.AddLink(
                    //    oppty,
                    //    new Relationship("opportunity_customer_accounts"),
                    //    account);
                    SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct,
                                      quoteProduct, oppty, account);
                    Console.WriteLine("and creating all records in CRM.");

                    // Associate quote to contact, which adds the Contact record in the
                    // "Other Contacts" section of a Quote record.
                    _orgContext.Attach(contact);
                    _orgContext.Attach(newQuote);
                    _orgContext.AddLink(
                        contact,
                        new Relationship("contactquotes_association"),
                        newQuote);
                    SaveChangesHelper(contact, newQuote);
                    Console.WriteLine("Associating contact and quote.");

                    // Create a case for Mary Kay Andersen.
                    var serviceRequest = new Incident()
                    {
                        Title          = "Problem with Widget B",
                        PriorityCode   = new OptionSetValue(1), // 1 = High
                        CaseOriginCode = new OptionSetValue(1), // 1 = Phone
                        CaseTypeCode   = new OptionSetValue(2), // 2 = Problem
                        SubjectId      =
                            new EntityReference(
                                Subject.EntityLogicalName,
                                _orgContext.CreateQuery <Subject>()
                                .First().Id),                     // use the default subject
                        Description = "Customer can't switch the product on.",
                        FollowupBy  = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
                        CustomerId  = contact.ToEntityReference(),
                        Id          = Guid.NewGuid()
                    };
                    _incidentId = serviceRequest.Id;
                    _orgContext.AddObject(serviceRequest);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        serviceRequest,
                        new Relationship("incident_customer_contacts"),
                        contact);
                    SaveChangesHelper(serviceRequest, contact);
                    Console.WriteLine("Creating service case for contact.");

                    // Deactivate the Mary Kay Andersen contact record.
                    SetStateRequest setInactiveRequest = new SetStateRequest
                    {
                        EntityMoniker = contact.ToEntityReference(),
                        State         = new OptionSetValue((int)ContactState.Inactive),
                        Status        = new OptionSetValue(2)
                    };
                    _orgContext.Execute(setInactiveRequest);
                    Console.WriteLine("Deactivating the contact record.");

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetBasicContextExamples1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemple #26
0
 public void Create <T>(T entity) where T : BaseEntity
 {
     context.AddObject(entity);
 }
Exemple #27
0
        /// <summary>
        /// A plug-in that creates a follow-up task activity when a new account is created.
        /// </summary>
        /// <remarks>Register this plug-in on the Create message, account entity,
        /// and asynchronous mode.
        /// </remarks>
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext ctx = new OrganizationServiceContext(service);

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != "gcbase_fundcentre")
                {
                    return;
                }

                FaultException ex1 = new FaultException();
                //throw new InvalidPluginExecutionException("test", ex1);

                if (entity.Attributes.Contains("gcbase_estimatedannualbudget") && entity.Attributes.Contains("gcbase_startdate") && entity.Attributes.Contains("gcbase_enddate"))
                {
                    try
                    {
                        //create budget lines
                        //throw new InvalidPluginExecutionException("testing", ex1);
                        int[] fiscalYears = new FiscalYear(entity.GetAttributeValue <DateTime>("gcbase_startdate"), entity.GetAttributeValue <DateTime>("gcbase_enddate")).getFiscalYears();

                        QueryExpression existingFundCentreBudgets = new QueryExpression
                        {
                            EntityName = "gcbase_fundcentrebudget",
                            ColumnSet  = new ColumnSet("gcbase_fundcentre", "gcbase_fiscalyear"),
                            Criteria   = new FilterExpression
                            {
                                Conditions =
                                {
                                    new ConditionExpression {
                                        AttributeName = "gcbase_fundcentre",
                                        Operator      = ConditionOperator.Equal,
                                        Values        =     { entity.Id}
                                    }
                                }
                            }
                        };

                        DataCollection <Entity> fundCentreBudgetsToDelete = service.RetrieveMultiple(existingFundCentreBudgets).Entities;

                        if (fundCentreBudgetsToDelete.Count > 0)
                        {
                            // here we should validate if we have projects pending instead of deleting budgets

                            var currentYears = fundCentreBudgetsToDelete.Select(s => (int)s.GetAttributeValue <OptionSetValue>("gcbase_fiscalyear").Value).ToArray();
                            var newYears     = fiscalYears.ToArray();
                            //newYears.Except(currentYears);

                            var illegalYears = currentYears.Except(newYears);

                            if (illegalYears.Count() > 0)
                            {
                                throw new InvalidPluginExecutionException(@"Cannot save your new start and end dates because there are budgets entered in
                                        fiscal years that fall outside of those dates. If you want to revise the dates please first delete the budgets in 
                                        fiscal years: " + string.Join("-", illegalYears) + " and try again!", ex1);
                            }
                            else
                            {
                                foreach (Entity fcb in fundCentreBudgetsToDelete)
                                {
                                    service.Delete("gcbase_fundcentrebudget", fcb.Id);
                                }
                            }
                        }

                        Array    values = Enum.GetValues(typeof(goal_fiscalyear));
                        string[] fys    = new string[fiscalYears.Count()];
                        int      index  = 0;

                        //throw new InvalidPluginExecutionException("testing", ex1);

                        //EntityReference fundRef = new EntityReference("gcbase_fund", preEntity.GetAttributeValue<EntityReference>("gcbase_fund").Id);
                        var fundEntity      = service.Retrieve("gcbase_fund", entity.GetAttributeValue <EntityReference>("gcbase_fund").Id, new ColumnSet("gcbase_name", "gcbase_fundid", "gcbase_fundtype"));
                        var fundTypeEntity  = service.Retrieve("gcbase_fundtype", fundEntity.GetAttributeValue <EntityReference>("gcbase_fundtype").Id, new ColumnSet("gcbase_name"));
                        var budgetEntryName = entity.GetAttributeValue <string>("gcbase_name") + "-" + fundEntity.GetAttributeValue <string>("gcbase_name") + "-" + fundTypeEntity.GetAttributeValue <string>("gcbase_name");
                        //  throw new InvalidPluginExecutionException(fiscalYears.Count().ToString(), ex1);
                        foreach (int year in fiscalYears)
                        {
                            var amount = entity.GetAttributeValue <Money>("gcbase_estimatedannualbudget");

                            if (amount.Value > 0)
                            {
                                Entity fundCentreBudget = new Entity("gcbase_fundcentrebudget");
                                // fundCentreBudget.Id = Guid.NewGuid();
                                fundCentreBudget["gcbase_amount"] = amount;
                                fys[index] = (string)Enum.GetName(typeof(goal_fiscalyear), year);
                                OptionSetValue fy = new OptionSetValue();
                                fy.Value = year;
                                fundCentreBudget["gcbase_fiscalyear"] = fy;

                                EntityReference fundCentre = new EntityReference("gcbase_fundcentre", entity.Id);
                                fundCentreBudget["gcbase_fundcentre"] = fundCentre;
                                fundCentreBudget["gcbase_name"]       = budgetEntryName + "-" + fy.Value;
                                // ctx.Attach(fundCentreBudget)
                                ctx.AddObject(fundCentreBudget);
                                ctx.SaveChanges();
                            }

                            index++;
                        }
                    }

                    catch (FaultException <OrganizationServiceFault> ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the PostFundCentreCreate plug-in.", ex);
                    }

                    catch (Exception ex)
                    {
                        tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
                        throw;
                    }
                }
            }
        }
Exemple #28
0
        public void UpdateWebFiles(string inputPath, string websitePrimaryKey, string blockedAttachments)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException(nameof(inputPath));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Input path: {0}.", inputPath);

            if (!Directory.Exists(Path.GetDirectoryName(inputPath)))
            {
                throw new FileNotFoundException("The input file path does not exist.");
            }

            if (string.IsNullOrWhiteSpace(websitePrimaryKey))
            {
                throw new ArgumentNullException(nameof(websitePrimaryKey));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Web site primary key: {0}.", websitePrimaryKey);

            bool isValid = Guid.TryParse(websitePrimaryKey, out Guid websiteId);

            if (!isValid)
            {
                throw new ArgumentException("The web site primary key is not valid");
            }

            IList <FileInfo> files = new List <FileInfo>();

            EnumerateFiles(inputPath, files);

            UpdateOrganizationSettings("js;", blockedAttachments);

            IList <WebFile> webFiles = CrmService.GetWebsiteFiles(websiteId);

            OrganizationServiceContext.ClearChanges();

            foreach (FileInfo file in files)
            {
                Logger.Info(CultureInfo.InvariantCulture, "Processing file {0}.", file.FullName);
                WebFile webFile = webFiles.SingleOrDefault(x => x.Name.ToUpperInvariant().Equals(file.Name.ToUpperInvariant()));
                if (webFile == null)
                {
                    Logger.Warn(CultureInfo.InvariantCulture, "There is no portal web file entity for the file {0}.", file.Name);
                    continue;
                }

                Note annotation = CrmService.GetAnnotations(webFile.Id).OrderByDescending(x => x.CreatedOn).FirstOrDefault();

                if (annotation == null)
                {
                    Logger.Info(CultureInfo.InvariantCulture, "A new annotation {0} will be created.", file.Name);

                    annotation = new Note {
                        Document   = Convert.ToBase64String(File.ReadAllBytes(file.FullName)),
                        FileName   = file.Name,
                        IsDocument = true,
                        MimeType   = MimeMapping.GetMimeMapping(file.Name),
                        ObjectType = webFile.LogicalName,
                        Regarding  = new EntityReference(webFile.LogicalName, webFile.Id),
                    };

                    OrganizationServiceContext.AddObject(annotation);
                }
                else if (!annotation.Document.Equals(Convert.ToBase64String(File.ReadAllBytes(file.FullName))))
                {
                    Logger.Info(CultureInfo.InvariantCulture, "The annotation {0} will be updated.", file.Name);

                    annotation = new Note
                    {
                        AnnotationId = annotation.Id,
                        Document     = Convert.ToBase64String(File.ReadAllBytes(file.FullName))
                    };

                    OrganizationServiceContext.Attach(annotation);
                    OrganizationServiceContext.UpdateObject(annotation);
                }
            }

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            UpdateOrganizationSettings("nothing really", blockedAttachments);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    ////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    var orgContext = new OrganizationServiceContext(service);
                    // Retrieve the Contact records that we created previously.
                    List <Contact> contacts = (from c in orgContext.CreateQuery <Contact>()
                                               where c.Address1_City == "Sammamish"
                                               select new Contact
                    {
                        ContactId = c.ContactId,
                        FirstName = c.FirstName,
                        LastName = c.LastName
                    }).ToList <Contact>();
                    Console.Write("Contacts retrieved, ");

                    // Create an Activity Party record for each Contact.
                    var activityParty1 = new ActivityParty
                    {
                        PartyId = new EntityReference(Contact.EntityLogicalName,
                                                      contacts[0].ContactId.Value),
                    };

                    var activityParty2 = new ActivityParty
                    {
                        PartyId = new EntityReference(Contact.EntityLogicalName,
                                                      contacts[1].ContactId.Value),
                    };

                    var activityParty3 = new ActivityParty
                    {
                        PartyId = new EntityReference(Contact.EntityLogicalName,
                                                      contacts[2].ContactId.Value),
                    };

                    Console.Write("ActivityParty instances created, ");

                    // Create Letter Activity and set From and To fields to the
                    // respective Activity Party entities.
                    var letter = new Letter
                    {
                        RegardingObjectId = new EntityReference(Contact.EntityLogicalName,
                                                                contacts[2].ContactId.Value),
                        Subject      = "Sample Letter Activity",
                        ScheduledEnd = DateTime.Now + TimeSpan.FromDays(5),
                        Description  = @"Greetings, Mr. Andreshak,

This is a sample letter activity as part of the SDK Samples.

Sincerely,
Mary Kay Andersen

cc: Denise Smith",
                        From         = new ActivityParty[] { activityParty1 },
                        To           = new ActivityParty[] { activityParty3, activityParty2 }
                    };
                    orgContext.AddObject(letter);
                    orgContext.SaveChanges();

                    Console.WriteLine("and Letter Activity created.");

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                #endregion Sample Code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }

            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        public void When_Creating_Using_Organization_Context_Record_Should_Be_Created()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var account = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" };

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                ctx.AddObject(account);
                ctx.SaveChanges();
            }

            Assert.NotNull(service.Retrieve(Account.EntityLogicalName, account.Id, new ColumnSet(true)));
        }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// activity party records are created and associated with an activity.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete
        /// all created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetWorkingWithActivityParties1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    OrganizationServiceContext orgContext =
                        new OrganizationServiceContext(_serviceProxy);

                    // Retrieve the Contact records that we created previously.
                    List<Contact> contacts = (from c in orgContext.CreateQuery<Contact>()
                                              where c.Address1_City == "Sammamish"
                                              select new Contact
                                              {
                                                  ContactId = c.ContactId,
                                                  FirstName = c.FirstName,
                                                  LastName = c.LastName
                                              }).ToList<Contact>();
                    Console.Write("Contacts retrieved, ");

                    // Create an Activity Party record for each Contact.
                    var activityParty1 = new ActivityParty
                    {
                        PartyId = new EntityReference(Contact.EntityLogicalName,
                            contacts[0].ContactId.Value),
                    };

                    var activityParty2 = new ActivityParty
                    {
                        PartyId = new EntityReference(Contact.EntityLogicalName,
                            contacts[1].ContactId.Value),
                    };

                    var activityParty3 = new ActivityParty
                    {
                        PartyId = new EntityReference(Contact.EntityLogicalName,
                            contacts[2].ContactId.Value),
                    };

                    Console.Write("ActivityParty instances created, ");

                    // Create Letter Activity and set From and To fields to the
                    // respective Activity Party entities.
                    var letter = new Letter
                    {
                        RegardingObjectId = new EntityReference(Contact.EntityLogicalName,
                            contacts[2].ContactId.Value),
                        Subject = "Sample Letter Activity",
                        ScheduledEnd = DateTime.Now + TimeSpan.FromDays(5),
                        Description = @"Greetings, Mr. Andreshak,

This is a sample letter activity as part of the Microsoft Dynamics CRM SDK.

Sincerely,
Mary Kay Andersen

cc: Denise Smith",
                        From = new ActivityParty[] { activityParty1 },
                        To = new ActivityParty[] { activityParty3, activityParty2 }
                    };
                    orgContext.AddObject(letter);
                    orgContext.SaveChanges();

                    Console.WriteLine("and Letter Activity created.");

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetWorkingWithActivityParties1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemple #32
0
        /// <summary>
        /// Persists the Session History
        /// </summary>
        /// <param name="context">Context used to save the session history</param>
        /// <param name="sessionHistory">Session History object</param>
        public Guid PersistSessionHistory(OrganizationServiceContext context, SessionHistory sessionHistory)
        {
            if (sessionHistory == null)
            {
                return(Guid.Empty);
            }

            var webFormSession = sessionHistory.Id != Guid.Empty ? context.CreateQuery("adx_webformsession").FirstOrDefault(s => s.GetAttributeValue <OptionSetValue>("statecode") != null && s.GetAttributeValue <OptionSetValue>("statecode").Value == 0 && s.GetAttributeValue <Guid>("adx_webformsessionid") == sessionHistory.Id) : null;

            var addNew = webFormSession == null;

            if (addNew)
            {
                webFormSession = new Entity("adx_webformsession");

                if (sessionHistory.WebFormId != Guid.Empty)
                {
                    webFormSession.Attributes["adx_webform"] = new EntityReference("adx_webform", sessionHistory.WebFormId);
                }
            }

            if (sessionHistory.PrimaryRecord != null && sessionHistory.PrimaryRecord.ID != Guid.Empty)
            {
                webFormSession.Attributes["adx_primaryrecordid"] = sessionHistory.PrimaryRecord.ID.ToString();
            }

            if (sessionHistory.CurrentStepId != Guid.Empty)
            {
                webFormSession.Attributes["adx_currentwebformstep"] = new EntityReference("adx_webformstep", sessionHistory.CurrentStepId);
            }

            if (sessionHistory.PrimaryRecord != null && !string.IsNullOrWhiteSpace(sessionHistory.PrimaryRecord.LogicalName))
            {
                webFormSession.Attributes["adx_primaryrecordentitylogicalname"] = sessionHistory.PrimaryRecord.LogicalName;
            }

            if (sessionHistory.PrimaryRecord != null && !string.IsNullOrWhiteSpace(sessionHistory.PrimaryRecord.PrimaryKeyLogicalName))
            {
                webFormSession.Attributes["adx_primaryrecordentitykeyname"] = sessionHistory.PrimaryRecord.PrimaryKeyLogicalName;
            }

            webFormSession.Attributes["adx_currentstepindex"] = sessionHistory.CurrentStepIndex;

            if (sessionHistory.ContactId != Guid.Empty)
            {
                webFormSession.Attributes["adx_contact"] = new EntityReference("contact", sessionHistory.ContactId);
            }

            if (sessionHistory.QuoteId != Guid.Empty)
            {
                webFormSession.Attributes["adx_quoteid"] = new EntityReference("quote", sessionHistory.QuoteId);
            }

            if (sessionHistory.SystemUserId != Guid.Empty)
            {
                webFormSession.Attributes["adx_systemuser"] = new EntityReference("systemuser", sessionHistory.SystemUserId);
            }

            if (!string.IsNullOrWhiteSpace(sessionHistory.AnonymousIdentification))
            {
                webFormSession.Attributes["adx_anonymousidentification"] = sessionHistory.AnonymousIdentification;
            }

            webFormSession.Attributes["adx_stephistory"] = ConvertListToJsonString(sessionHistory.StepHistory);

            if (!string.IsNullOrWhiteSpace(sessionHistory.UserHostAddress))
            {
                webFormSession.Attributes["adx_userhostaddress"] = sessionHistory.UserHostAddress;
            }

            if (!string.IsNullOrWhiteSpace(sessionHistory.UserIdentityName))
            {
                webFormSession.Attributes["adx_useridentityname"] = sessionHistory.UserIdentityName;
            }

            if (addNew)
            {
                context.AddObject(webFormSession);
            }
            else
            {
                context.UpdateObject(webFormSession);
            }

            context.SaveChanges();

            return(webFormSession.Id);
        }
        public void When_Creating_Using_Organization_Context_Without_Saving_Changes_Record_Should_Not_Be_Created()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var account = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" };

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                ctx.AddObject(account);

                var retrievedAccount = ctx.CreateQuery<Account>().SingleOrDefault(acc => acc.Id == account.Id);
                Assert.Null(retrievedAccount);
            }
        }
        /// <summary>
        /// This method first connects to the Organization service and creates the
        /// OrganizationServiceContext. Then, several entity creation and relationship
        /// operations are performed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetBasicContextExamples1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
                                                                     serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;
                    
                    CreateRequiredRecords();

                    // The OrganizationServiceContext is an object that wraps the service
                    // proxy and allows creating/updating multiple records simultaneously.
                    _orgContext = new OrganizationServiceContext(_service);

                    // Create a new contact called Mary Kay Andersen.
                    var contact = new Contact()
                    {
                        FirstName = "Mary Kay",
                        LastName = "Andersen",
                        Address1_Line1 = "23 Market St.",
                        Address1_City = "Sammamish",
                        Address1_StateOrProvince = "MT",
                        Address1_PostalCode = "99999",
                        Telephone1 = "12345678",
                        EMailAddress1 = "*****@*****.**",
                        Id = Guid.NewGuid()
                    };
                    _contactId = contact.Id;
                    _orgContext.AddObject(contact);
                    Console.Write("Instantiating contact, ");

                    // Create an account called Contoso.
                    var account = new Account()
                    {
                        Name = "Contoso",
                        Address1_City = "Redmond",
                        // set the account category to 'Preferred Customer'
                        AccountCategoryCode = new OptionSetValue(1), 
                        LastUsedInCampaign = DateTime.Now,
                        MarketCap = new Money(120000),
                        DoNotEMail = true,
                        Description = "Contoso is a fictional company!",
                        Id = Guid.NewGuid(),
                    };
                    _accountId = account.Id;
                    Console.Write("instantiating account, ");

                    // Set Mary Kay Andersen as the primary contact
                    _orgContext.AddRelatedObject(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and creating both records in CRM.");

                    // Remove the primary contact value from Mary Kay Andersen
                    _orgContext.Attach(contact);
                    _orgContext.DeleteLink(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.Write("Removing primary contact status, ");

                    // Add Mary Kay Andersen to the contact list for the account Contoso.
                    _orgContext.Attach(account);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        account,
                        new Relationship("contact_customer_accounts"),
                        contact);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and adding contact to account's contact list.");

                    // Add a note with a document attachment to the contact's record.
                    var attachment = File.OpenRead("sample.txt");
                    var data = new byte[attachment.Length];
                    attachment.Read(data, 0, (int)attachment.Length);

                    var note = new Annotation()
                    {
                        Subject = "Note subject...",
                        NoteText = "Note Details....",
                        DocumentBody = Convert.ToBase64String(data),
                        FileName = Path.GetFileName(attachment.Name),
                        MimeType = "text/plain",
                        Id = Guid.NewGuid(),
                        // Associate the note to the contact.
                        ObjectId = contact.ToEntityReference(),
                        ObjectTypeCode = Contact.EntityLogicalName
                    };
                    _annotationId = note.Id;
                    Console.Write("Instantiating a note, ");
                    _orgContext.AddObject(note);
                    _orgContext.Attach(contact);
                    // Set the contact as the Regarding attribute of the note.
                    _orgContext.AddLink(
                        contact,
                        new Relationship("Contact_Annotation"),
                        note);
                    SaveChangesHelper(note, contact);
                    Console.WriteLine("creating the note in CRM and linking to contact.");

                    // Change the owning user of the contact Mary Kay Andersen
                    // Find a user with an email address of "*****@*****.**"
                    var newOwner = (from u in _orgContext.CreateQuery<SystemUser>()
                                    where u.InternalEMailAddress == "*****@*****.**"
                                    select u).Single();
                    AssignRequest assignRequest = new AssignRequest()
                    {
                        Target = contact.ToEntityReference(),
                        Assignee = newOwner.ToEntityReference()
                    };
                    _orgContext.Execute(assignRequest);
                    Console.WriteLine("Changing ownership of contact record.");

                    // Create a new price list called Retail Price List.
                    var priceList = new PriceLevel()
                    {
                        Name = "Retail Price List",
                        BeginDate = DateTime.Now,
                        EndDate = DateTime.Now,
                        Description = "Contoso's primary pricelist.",
                        Id = Guid.NewGuid()
                    };
                    _priceLevelId = priceList.Id;
                    _orgContext.AddObject(priceList);
                    Console.Write("Instantiating price list ");
                    
                    // Create a new product called Widget A.
                    var newProduct = new Product()
                    {
                        Name = "Widget A",
                        Description = "Industrial widget for hi-tech industries",
                        ProductStructure = new OptionSetValue(1), // 1 = Product
                        QuantityOnHand = 2,
                        ProductNumber = "WIDG-A",
                        Price = new Money(decimal.Parse("12.50")),
                        QuantityDecimal = 2, // Sets the Decimals Supported value
                        Id = Guid.NewGuid(),
                        DefaultUoMScheduleId = new EntityReference(
                                UoMSchedule.EntityLogicalName,
                                _orgContext.CreateQuery<UoMSchedule>().First().Id),
                        DefaultUoMId = new EntityReference(
                                UoM.EntityLogicalName,
                                _orgContext.CreateQuery<UoM>().First().Id)
                    };
                    _productId = newProduct.Id;
                    _orgContext.AddObject(newProduct);
                    Console.WriteLine("and product.");
                    SaveChangesHelper(priceList, newProduct);

                    // Add Widget A to the Retail Price List.
                    var priceLevelProduct = new ProductPriceLevel()
                    {
                        ProductId = newProduct.ToEntityReference(),
                        UoMId = newProduct.DefaultUoMId,
                        Amount = new Money(decimal.Parse("12.50")),
                        PriceLevelId = priceList.ToEntityReference(),
                        Id = Guid.NewGuid()
                    };
                    _productPriceLevelId = priceLevelProduct.Id;
                    _orgContext.AddObject(priceLevelProduct);
                    Console.Write("Associating product to price list, ");

                    // Publish the product
                    SetStateRequest publishRequest = new SetStateRequest
                    {
                        EntityMoniker = newProduct.ToEntityReference(),
                        State = new OptionSetValue((int)ProductState.Active),
                        Status = new OptionSetValue(1)
                    };
                    _serviceProxy.Execute(publishRequest);
                    Console.WriteLine("and publishing the product.");
                    

                    // Create a new quote for Contoso.
                    var newQuote = new Quote()
                    {
                        Name = "Quotation for Contoso",
                        // Sets the pricelist to the one we've just created
                        PriceLevelId = priceList.ToEntityReference(),
                        Id = Guid.NewGuid(),
                        CustomerId = account.ToEntityReference()
                    };
                    _quoteId = newQuote.Id;
                    _orgContext.AddObject(newQuote);
                    _orgContext.Attach(account);
                    _orgContext.AddLink(
                        newQuote,
                        new Relationship("quote_customer_accounts"),
                        account);
                    Console.Write("Instantiating a quote, ");

                    // Add a quote product to this quote.
                    var quoteProduct = new QuoteDetail()
                    {
                        ProductId = newProduct.ToEntityReference(),
                        Quantity = 1,
                        QuoteId = newQuote.ToEntityReference(),
                        UoMId = newProduct.DefaultUoMId,
                        Id = Guid.NewGuid()
                    };
                    _quoteDetailId = quoteProduct.Id;
                    _orgContext.AddObject(quoteProduct);
                    Console.WriteLine("and adding product to quote.");

                    // Create a sales opportunity with Contoso.
                    var oppty = new Opportunity()
                    {
                        Name = "Interested in Widget A",
                        EstimatedCloseDate = DateTime.Now.AddDays(30.0),
                        EstimatedValue = new Money(decimal.Parse("300000.00")),
                        CloseProbability = 25, // 25% probability of closing this deal
                        IsRevenueSystemCalculated = false, // user-calculated revenue
                        OpportunityRatingCode = new OptionSetValue(2), // warm
                        CustomerId = account.ToEntityReference(),
                        Id = Guid.NewGuid()
                    };
                    _opportunityId = oppty.Id;
                    _orgContext.AddObject(oppty);
                    Console.Write("Instantiating opportunity, ");
                    //_orgContext.AddLink(
                    //    oppty,
                    //    new Relationship("opportunity_customer_accounts"),
                    //    account);
                    SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct,
                        quoteProduct, oppty, account);
                    Console.WriteLine("and creating all records in CRM.");

                    // Associate quote to contact, which adds the Contact record in the
                    // "Other Contacts" section of a Quote record.
                    _orgContext.Attach(contact);
                    _orgContext.Attach(newQuote);
                    _orgContext.AddLink(
                        contact,
                        new Relationship("contactquotes_association"),
                        newQuote);
                    SaveChangesHelper(contact, newQuote);
                    Console.WriteLine("Associating contact and quote.");

                    // Create a case for Mary Kay Andersen.                     
                    var serviceRequest = new Incident()
                    {
                        Title = "Problem with Widget B",
                        PriorityCode = new OptionSetValue(1), // 1 = High
                        CaseOriginCode = new OptionSetValue(1), // 1 = Phone
                        CaseTypeCode = new OptionSetValue(2), // 2 = Problem
                        SubjectId =
                            new EntityReference(
                                Subject.EntityLogicalName,
                                _orgContext.CreateQuery<Subject>()
                                    .First().Id),  // use the default subject
                        Description = "Customer can't switch the product on.",
                        FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
                        CustomerId = contact.ToEntityReference(),
                        Id = Guid.NewGuid()
                    };
                    _incidentId = serviceRequest.Id;
                    _orgContext.AddObject(serviceRequest);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        serviceRequest,
                        new Relationship("incident_customer_contacts"),
                        contact);
                    SaveChangesHelper(serviceRequest, contact);
                    Console.WriteLine("Creating service case for contact.");

                    // Deactivate the Mary Kay Andersen contact record.
                    SetStateRequest setInactiveRequest = new SetStateRequest
                    {
                        EntityMoniker = contact.ToEntityReference(),
                        State = new OptionSetValue((int)ContactState.Inactive),
                        Status = new OptionSetValue(2)
                    };
                    _orgContext.Execute(setInactiveRequest);
                    Console.WriteLine("Deactivating the contact record.");

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetBasicContextExamples1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        private void createOrUpdateBudgetLineItems(FundCentreParamaters param, IOrganizationService service, Entity preEntity, Entity entity)
        {
            //using (var ctx = new OrganizationServiceContext(service)) {
                OrganizationServiceContext ctx = new OrganizationServiceContext(service);
                FaultException ex1 = new FaultException();

             //DELETE existing budget lines
                QueryExpression existingFundCentreBudgets = new QueryExpression
                {
                    EntityName = "gcbase_fundcentrebudget",
                    ColumnSet = new ColumnSet("gcbase_fundcentre", "gcbase_fiscalyear"),
                    Criteria = new FilterExpression
                    {
                        Conditions = {
                     new ConditionExpression {
                        AttributeName = "gcbase_fundcentre",
                        Operator = ConditionOperator.Equal,
                        Values = { param.id }
                     }
                   }
                    }
                };

                if (param.startdate.HasValue && param.enddate.HasValue) {

                    int[] fiscalYears = new FiscalYear(param.startdate.Value, param.enddate.Value).getFiscalYears();

                    DataCollection<Entity> fundCentreBudgetsToDelete = service.RetrieveMultiple(existingFundCentreBudgets).Entities;
                    if (fundCentreBudgetsToDelete.Count > 0)
                    {
                        // here we should validate if we have projects pending instead of deleting budgets

                       var currentYears = fundCentreBudgetsToDelete.Select(s => (int)s.GetAttributeValue<OptionSetValue>("gcbase_fiscalyear").Value).ToArray();
                        var newYears = fiscalYears.ToArray();
                        //newYears.Except(currentYears);

                        var illegalYears = currentYears.Except(newYears);

                        if (illegalYears.Count() > 0)
                        {
                            throw new InvalidPluginExecutionException(@"Cannot save your new start and end dates because there are budgets entered in
                        fiscal years that fall outside of those dates. If you want to revise the dates please first delete the budgets in
                        fiscal years: " + string.Join("-", illegalYears) + " and try again!", ex1);
                        }
                        else
                        {
                            foreach (Entity fcb in fundCentreBudgetsToDelete)
                            {
                                service.Delete("gcbase_fundcentrebudget", fcb.Id);
                            }
                        }
                    }

                    Array values = Enum.GetValues(typeof(goal_fiscalyear));
                    string[] fys = new string[fiscalYears.Count()];
                    int index = 0;

                    //QueryExpression fundTypeQry = new QueryExpression
                    //{
                    //    EntityName = "gcbase_fundtype",
                    //    ColumnSet = new ColumnSet("gcbase_name"),
                    //    Criteria = new FilterExpression
                    //    {
                    //        Conditions = {
                    //            new ConditionExpression("gcbase_name", ConditionOperator.Equal, "Contribution")
                    //        }
                    //    }
                    //};
                    //DataCollection<Entity> fundTypes = service.RetrieveMultiple(fundTypeQry).Entities;
                    //Guid contribution = new Guid();

                    //foreach (var ft in fundTypes)
                    //{
                    //    if (ft.Attributes["gcbase_name"].ToString() != "Grant")
                    //    {
                    //        contribution = ft.Id;
                    //    }
                    //}

                    // throw new InvalidPluginExecutionException(grant.ToString() + contribution.ToString(), ex1);

                    foreach (int year in fiscalYears)
                    {
                        if (param.amount.Value > 0)
                        {
                            Entity fundCentreBudget = new Entity("gcbase_fundcentrebudget");
                            // fundCentreBudget.Id = Guid.NewGuid();
                            fundCentreBudget["gcbase_amount"] = (Money)param.amount;
                            fys[index] = (string)Enum.GetName(typeof(goal_fiscalyear), year);
                            OptionSetValue fy = new OptionSetValue();
                            fy.Value = year;
                            fundCentreBudget["gcbase_fiscalyear"] = fy;

                            EntityReference fundCentre = new EntityReference("gcbase_fundcentre", param.id);
                            fundCentreBudget["gcbase_fundcentre"] = fundCentre;
                            fundCentreBudget["gcbase_name"] = param.name + "-" + fy.Value;
                            // ctx.Attach(fundCentreBudget)
                            ctx.AddObject(fundCentreBudget);
                            ctx.SaveChanges();
                        }

                        index++;
                    }

                }
        }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// activity party records are created and associated with an activity.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete
        /// all created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetWorkingWithActivityParties1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    OrganizationServiceContext orgContext =
                        new OrganizationServiceContext(_serviceProxy);

                    // Retrieve the Contact records that we created previously.
                    List <Contact> contacts = (from c in orgContext.CreateQuery <Contact>()
                                               where c.Address1_City == "Sammamish"
                                               select new Contact
                    {
                        ContactId = c.ContactId,
                        FirstName = c.FirstName,
                        LastName = c.LastName
                    }).ToList <Contact>();
                    Console.Write("Contacts retrieved, ");

                    // Create an Activity Party record for each Contact.
                    var activityParty1 = new ActivityParty
                    {
                        PartyId = new EntityReference(Contact.EntityLogicalName,
                                                      contacts[0].ContactId.Value),
                    };

                    var activityParty2 = new ActivityParty
                    {
                        PartyId = new EntityReference(Contact.EntityLogicalName,
                                                      contacts[1].ContactId.Value),
                    };

                    var activityParty3 = new ActivityParty
                    {
                        PartyId = new EntityReference(Contact.EntityLogicalName,
                                                      contacts[2].ContactId.Value),
                    };

                    Console.Write("ActivityParty instances created, ");

                    // Create Letter Activity and set From and To fields to the
                    // respective Activity Party entities.
                    var letter = new Letter
                    {
                        RegardingObjectId = new EntityReference(Contact.EntityLogicalName,
                                                                contacts[2].ContactId.Value),
                        Subject      = "Sample Letter Activity",
                        ScheduledEnd = DateTime.Now + TimeSpan.FromDays(5),
                        Description  = @"Greetings, Mr. Andreshak,

This is a sample letter activity as part of the Microsoft Dynamics CRM SDK.

Sincerely,
Mary Kay Andersen

cc: Denise Smith",
                        From         = new ActivityParty[] { activityParty1 },
                        To           = new ActivityParty[] { activityParty3, activityParty2 }
                    };
                    orgContext.AddObject(letter);
                    orgContext.SaveChanges();

                    Console.WriteLine("and Letter Activity created.");

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetWorkingWithActivityParties1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }