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();
        }
        public void When_updating_an_entity_using_organization_context_changes_should_be_saved()
        {
            var context = new XrmFakedContext();

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

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

            context.Initialize(new List <Entity>()
            {
                existingAccount
            });

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                existingAccount.Name = "Super Great Customer Name Updated!";

                ctx.Attach(existingAccount);
                ctx.UpdateObject(existingAccount);
                ctx.SaveChanges();
            }

            //Make other account wasn't updated
            var account = context.CreateQuery <Account>().Where(e => e.Id == existingAccount.Id).FirstOrDefault();

            Assert.Equal(account.Name, "Super Great Customer Name Updated!");
        }
예제 #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);
            }
        }
예제 #4
0
        public void UpdateServiceEndpoint(string primaryKey, string namespaceAddress, string sharedAccessKey, string serviceNamespace)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(primaryKey))
            {
                throw new ArgumentNullException(nameof(primaryKey));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Primary key: {0}.", primaryKey);

            bool isValidGuid = Guid.TryParse(primaryKey, out Guid key);

            if (!isValidGuid)
            {
                throw new ArgumentException("Primary key argument is invalid.");
            }

            if (string.IsNullOrWhiteSpace(namespaceAddress))
            {
                throw new ArgumentNullException(nameof(namespaceAddress));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Namespace address: {0}.", namespaceAddress);

            if (string.IsNullOrWhiteSpace(sharedAccessKey))
            {
                throw new ArgumentNullException(nameof(sharedAccessKey));
            }

            if (string.IsNullOrWhiteSpace(serviceNamespace))
            {
                throw new ArgumentNullException(nameof(serviceNamespace));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Service namespace: {0}.", serviceNamespace);

            ServiceEndpoint serviceEndpoint = CrmService.GetServiceEndpoint(key);

            if (serviceEndpoint == null)
            {
                throw new EntityNotFoundException("Service endpoint not found.");
            }

            OrganizationServiceContext.ClearChanges();

            ServiceEndpoint se = new ServiceEndpoint
            {
                ServiceEndpointId       = serviceEndpoint.Id,
                ContentTypeOfTheMessage = ServiceEndpointMessageFormat.Json,
                NamespaceAddress        = namespaceAddress,
                //SASKey = sharedAccessKey, //TO-DO
                ServiceNamespace = serviceNamespace
            };

            OrganizationServiceContext.Attach(se);

            OrganizationServiceContext.UpdateObject(se);

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
예제 #5
0
        public Entity BlankExistingEntity(string entityName, Guid id, OrganizationServiceContext context)
        {
            var existingEntity = new Entity(entityName, id);

            context.Attach(existingEntity);
            context.UpdateObject(existingEntity);
            return(existingEntity);
        }
        /// <summary>
        /// Clones an arbitrary source entity and attaches it to the context.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="entity"></param>
        /// <param name="includeRelatedEntities"></param>
        public static T AttachClone <T>(this OrganizationServiceContext context, T entity, bool includeRelatedEntities = false)
            where T : Entity
        {
            entity.ThrowOnNull("entity");

            var clone = entity.Clone(includeRelatedEntities);

            context.Attach(clone);
            return(clone as T);
        }
예제 #7
0
        public void UpdateSolutionVersion(string solutionName, string timeZone, string version)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(solutionName))
            {
                throw new ArgumentNullException(nameof(solutionName));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Solution name: {0}.", solutionName);

            if (string.IsNullOrWhiteSpace(timeZone))
            {
                throw new ArgumentNullException(nameof(timeZone));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Time zone: {0}.", timeZone);

            if (solutionName.ToUpperInvariant().Equals("DEFAULT"))
            {
                Logger.Warn(CultureInfo.InvariantCulture, "Version update of the default solution is not allowed.");
                Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
                return;
            }

            IList <Solution> solutions = CrmService.GetSolutions(solutionName);

            OrganizationServiceContext.ClearChanges();

            foreach (Solution solution in solutions)
            {
                Logger.Info(CultureInfo.InvariantCulture, "Processing solution '{0} {1}'.", solution.DisplayName, solution.Version);

                if (solution.PackageType.GetValueOrDefault())
                {
                    throw new PlatformException("Version update of managed solutions is not allowed.");
                }

                Solution updatedSolution = new Solution
                {
                    SolutionId = solution.Id,
                    Version    = string.IsNullOrWhiteSpace(version) ? CalculateVersion(timeZone) : version
                };

                OrganizationServiceContext.Attach(updatedSolution);
                OrganizationServiceContext.UpdateObject(updatedSolution);

                Logger.Info(CultureInfo.InvariantCulture, "Solution {0} version set to {1}.", solution.DisplayName, updatedSolution.Version);
            }

            if (OrganizationServiceContext.GetAttachedEntities().OfType <Solution>().Any())
            {
                CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);
            }

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
예제 #8
0
        private void Update()
        {
            var user = GetUserEntity(UserId, _context);

            user.SetAttributeValue(AttributeMapApproved, Approved);
            user.SetAttributeValue(AttributeMapLastLogin, LastLogin.ToUniversalTime());

            _context.Attach(user);
            _context.UpdateObject(user);
            _context.SaveChanges();
            _context.Detach(user);
        }
예제 #9
0
        /// <summary>
        /// Updates an existing entity, attaching to the context if required
        /// </summary>
        /// <param name="entity"></param>
        public void Update(Entity entity)
        {
            using (var ctx = new OrganizationServiceContext(Svc))
            {
                if (!ctx.IsAttached(entity))
                {
                    ctx.Attach(entity);
                }

                ctx.UpdateObject(entity);
                ctx.SaveChanges();
            }
        }
예제 #10
0
        private void UpdateRating(int rating, int maxRating, int minRating, OrganizationServiceContext serviceContext, Entity existingRating)
        {
            existingRating.Attributes[FeedbackMetadataAttributes.RatingValueAttributeName] = rating;
            existingRating.Attributes[FeedbackMetadataAttributes.MaxRatingAttributeName]   = maxRating;
            existingRating.Attributes[FeedbackMetadataAttributes.MinRatingAttributeName]   = minRating;

            if (!serviceContext.IsAttached(existingRating))
            {
                serviceContext.Attach(existingRating);
            }

            serviceContext.UpdateObject(existingRating);

            serviceContext.SaveChanges();
        }
예제 #11
0
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                var context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.MessageName.ToLower() != "create")
                {
                    return;
                }

                using (var orgContext = new OrganizationServiceContext(service))
                {
                    var supp = (Entity)context.InputParameters["Target"];

                    if (supp.GetAttributeValue <EntityReference>("new_contractorder") == null ||
                        supp.GetAttributeValue <EntityReference>("new_contractorder").Id == null)
                    {
                        return;
                    }

                    var count = service.Retrieve("salesorder", supp.GetAttributeValue <EntityReference>("new_contractorder").Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new[] { "new_agreemnumber" }));
                    if (count != null)
                    {
                        var number = count.GetAttributeValue <string>("new_agreemnumber") ?? "1";
                        supp["new_name"] = number;
                        orgContext.ClearChanges();
                        orgContext.Attach(supp);
                        orgContext.UpdateObject(supp);

                        Entity upOrder = new Entity();
                        upOrder.Id          = supp.GetAttributeValue <EntityReference>("new_contractorder").Id;
                        upOrder.LogicalName = supp.GetAttributeValue <EntityReference>("new_contractorder").LogicalName;
                        upOrder.Attributes.Add("new_agreemnumber", (Convert.ToInt32(number) + 1).ToString());

                        service.Update(upOrder);
                        orgContext.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
        /// <summary>
        /// Resets the EntityState of an entity before attaching it to the context.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="entity"></param>
        public static void ReAttach(this OrganizationServiceContext context, Entity entity)
        {
            entity.ThrowOnNull("entity");

            if (context.IsAttached(entity))
            {
                return;
            }

            if (entity.EntityState != null && entity.EntityState != EntityState.Unchanged)
            {
                entity.EntityState = null;
            }

            context.Attach(entity);
        }
예제 #13
0
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.MessageName.ToLower() != "create")
                    return;

                using (var orgContext = new OrganizationServiceContext(service))
                {
                    var supp = (Entity)context.InputParameters["Target"];

                    if (supp.GetAttributeValue<EntityReference>("new_contractorder") == null ||
                        supp.GetAttributeValue<EntityReference>("new_contractorder").Id == null)
                        return;

                    var count = service.Retrieve("salesorder", supp.GetAttributeValue<EntityReference>("new_contractorder").Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new[] { "new_agreemnumber" }));
                    if (count != null)
                    {
                        var number = count.GetAttributeValue<string>("new_agreemnumber") ?? "1";
                        supp["new_name"] = number;
                        orgContext.ClearChanges();
                        orgContext.Attach(supp);
                        orgContext.UpdateObject(supp);

                        Entity upOrder = new Entity();
                        upOrder.Id = supp.GetAttributeValue<EntityReference>("new_contractorder").Id;
                        upOrder.LogicalName = supp.GetAttributeValue<EntityReference>("new_contractorder").LogicalName;
                        upOrder.Attributes.Add("new_agreemnumber", (Convert.ToInt32(number) + 1).ToString());

                        service.Update(upOrder);
                        orgContext.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
예제 #14
0
        public void When_updating_a_not_existing_entity_using_organization_context_exception_should_be_thrown()
        {
            var context = new XrmFakedContext();

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

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

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                existingAccount.Name = "Super Great Customer Name Updated!";

                ctx.Attach(existingAccount);
                ctx.UpdateObject(existingAccount);
                Assert.Throws <SaveChangesException>(() => ctx.SaveChanges());
            }
        }
예제 #15
0
        private void UpdateOrganizationSettings(string replaceString, string blockedAttachments)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(blockedAttachments))
            {
                throw new ArgumentNullException(nameof(blockedAttachments));
            }

            Logger.Info(CultureInfo.InvariantCulture, "Updating blocked attachments.");

            Organization organizationSettings = CrmService.GetOrganizationSettings();

            if (organizationSettings == null)
            {
                throw new EntityNotFoundException("No organization record can be found in the system.");
            }

            OrganizationServiceContext.ClearChanges();

            Organization updatedOrganizationSettings = new Organization
            {
                Id = organizationSettings.Id,
                BlockAttachments = blockedAttachments.Replace(replaceString, string.Empty),
            };

            OrganizationServiceContext.Attach(updatedOrganizationSettings);

            OrganizationServiceContext.UpdateObject(updatedOrganizationSettings);

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            Thread.Sleep(60000);

            Logger.Info(CultureInfo.InvariantCulture, "Blocked attachments updated to: {0}.", updatedOrganizationSettings.BlockAttachments);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
        private static T CreateDocumentLocation <T>(this OrganizationServiceContext context, string name, string relativeUrl, Entity parentLocation, string parentRelationship, EntityReference regarding = null) where T : Entity, new()
        {
            var location = new T {
                LogicalName = _sharepointdocumentlocation
            };

            location.SetAttributeValue("name", name);
            location.SetAttributeValue("relativeurl", relativeUrl);

            if (regarding != null)
            {
                location.SetAttributeValue("regardingobjectid", regarding);
            }

            if (!context.IsAttached(parentLocation))
            {
                context.Attach(parentLocation);
            }

            context.AddRelatedObject(parentLocation, parentRelationship, location, EntityRole.Referenced);

            return(location);
        }
예제 #17
0
        public void UpdateOrganizationSettings(Organization organization)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (organization == null)
            {
                throw new ArgumentNullException(nameof(organization));
            }

            Organization organizationSettings = CrmService.GetOrganizationSettings();

            if (organizationSettings == null)
            {
                throw new EntityNotFoundException("No organization record can be found in the system.");
            }

            OrganizationServiceContext.ClearChanges();

            //TO-DO: this is in experimental mode

            Organization updatedOrganizationSettings = new Organization
            {
                Id = organizationSettings.Id,
                //BlockAttachments = organization.BlockAttachments,
                OrganizationName = organization.OrganizationName
            };

            OrganizationServiceContext.Attach(updatedOrganizationSettings);

            OrganizationServiceContext.UpdateObject(updatedOrganizationSettings);

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            //Logger.Info(CultureInfo.InvariantCulture, "Blocked attachments updated to: {0}.", updatedOrganizationSettings.BlockAttachments);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
        private void Select(int offset, int limit, int itemLimit, ICollection <Entity> items)
        {
            _fetchXml.Root.SetAttributeValue("page", (offset / limit) + 1);
            _fetchXml.Root.SetAttributeValue("count", limit);

            var response = (RetrieveMultipleResponse)_serviceContext.Execute(new RetrieveMultipleRequest
            {
                Query = new FetchExpression(_fetchXml.ToString())
            });

            var selected = response.EntityCollection.Entities.ToArray();

            foreach (var entity in selected)
            {
                _serviceContext.Attach(entity);
            }

            foreach (var item in selected.Where(item => _filter(item)))
            {
                items.Add(item);

                if (items.Count >= itemLimit)
                {
                    return;
                }
            }

            // If there are fewer items than what were asked for, there must be no further items
            // to select, and so we should quit after processing the items we did get.
            if (selected.Length < limit)
            {
                return;
            }

            // We still don't have enough items, so select the next page.
            Select(offset + limit, limit, itemLimit, items);
        }
예제 #19
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);
        }
예제 #20
0
        public void Update(T entity)
        {
            // service.Detach(entity);
            try
            {
                if (!service.IsAttached(entity))
                {
                    service.Attach(entity);
                }
                service.UpdateObject(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;
            }
        }
        public void When_updating_an_entity_using_organization_context_changes_should_be_saved()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

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

            context.Initialize(new List<Entity>()
            {
                existingAccount
            });

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                existingAccount.Name = "Super Great Customer Name Updated!";

                ctx.Attach(existingAccount);
                ctx.UpdateObject(existingAccount);
                ctx.SaveChanges();
            }

            //Make other account wasn't updated
            var account = context.CreateQuery<Account>().Where(e => e.Id == existingAccount.Id).FirstOrDefault();
            Assert.Equal(account.Name, "Super Great Customer Name Updated!");
        }
예제 #22
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;
            }
        }
        private void UpdateReceiptAmountForThisTransaction(Guid receiptRecordID, LocalPluginContext localContext, IOrganizationService service, IPluginExecutionContext context)
        {
            localContext.TracingService.Trace("Entering UpdateReceiptAmountForThisTransaction()");
            OrganizationServiceContext organizationServiceContext = new OrganizationServiceContext(service);
            ColumnSet columnSet = new ColumnSet("msnfp_receiptid", "createdon", "msnfp_customerid", "msnfp_expectedtaxcredit", "msnfp_generatedorprinted", "msnfp_lastdonationdate", "msnfp_amount_nonreceiptable", "msnfp_transactioncount", "msnfp_preferredlanguagecode", "msnfp_receiptnumber", "msnfp_receiptgeneration", "msnfp_receiptissuedate", "msnfp_receiptstackid", "msnfp_receiptstatus", "msnfp_amount_receipted", "msnfp_paymentscheduleid", "msnfp_replacesreceiptid", "msnfp_identifier", "msnfp_amount");
            Entity    entity    = service.Retrieve("msnfp_receipt", receiptRecordID, columnSet);

            localContext.TracingService.Trace("Old msnfp_amount_receipted: " + ((Money)entity["msnfp_amount_receipted"]).Value);
            entity["msnfp_amount_receipted"] = new Money(0m);
            localContext.TracingService.Trace("Old msnfp_amount_nonreceiptable: " + ((Money)entity["msnfp_amount_nonreceiptable"]).Value);
            entity["msnfp_amount_nonreceiptable"] = new Money(0m);
            localContext.TracingService.Trace("Old msnfp_amount: " + ((Money)entity["msnfp_amount"]).Value);
            entity["msnfp_amount"]           = new Money(0m);
            entity["msnfp_transactioncount"] = 0;
            List <Entity> list = (from t in organizationServiceContext.CreateQuery("msnfp_transaction")
                                  where ((EntityReference)t["msnfp_taxreceiptid"]).Id == receiptRecordID
                                  select t).ToList();

            foreach (Entity item in list)
            {
                decimal num  = default(decimal);
                decimal num2 = default(decimal);
                decimal num3 = default(decimal);
                decimal num4 = default(decimal);
                localContext.TracingService.Trace("------------------");
                localContext.TracingService.Trace("Processing Transaction ID: " + ((Guid)item["msnfp_transactionid"]).ToString());
                num  = (item.Contains("msnfp_amount") ? ((Money)item["msnfp_amount"]).Value : 0m);
                num2 = (item.Contains("msnfp_amount_receipted") ? ((Money)item["msnfp_amount_receipted"]).Value : 0m);
                num3 = (item.Contains("msnfp_amount_membership") ? ((Money)item["msnfp_amount_membership"]).Value : 0m);
                num4 = (item.Contains("msnfp_amount_nonreceiptable") ? ((Money)item["msnfp_amount_nonreceiptable"]).Value : 0m);
                localContext.TracingService.Trace("Got membership amount and non-receiptable amount.");
                localContext.TracingService.Trace("Amount Receipted " + num2 + " Membership Amount: " + num3 + " Non-receiptable : " + num4);
                localContext.TracingService.Trace("Old msnfp_amount_receipted: " + ((Money)entity["msnfp_amount_receipted"]).Value);
                entity["msnfp_amount_receipted"] = new Money(((Money)entity["msnfp_amount_receipted"]).Value + new Money(num2).Value);
                localContext.TracingService.Trace("New msnfp_amount_receipted: " + ((Money)entity["msnfp_amount_receipted"]).Value);
                localContext.TracingService.Trace("Old msnfp_amount_nonreceiptable: " + ((Money)entity["msnfp_amount_nonreceiptable"]).Value);
                entity["msnfp_amount_nonreceiptable"] = new Money(((Money)entity["msnfp_amount_nonreceiptable"]).Value + new Money(num3 + num4).Value);
                localContext.TracingService.Trace("New msnfp_amount_nonreceiptable: " + ((Money)entity["msnfp_amount_nonreceiptable"]).Value);
                localContext.TracingService.Trace("Old msnfp_amount: " + ((Money)entity["msnfp_amount"]).Value);
                entity["msnfp_amount"] = new Money(((Money)entity["msnfp_amount"]).Value + new Money(num).Value);
                localContext.TracingService.Trace("New msnfp_amount: " + ((Money)entity["msnfp_amount"]).Value);
                entity["msnfp_generatedorprinted"] = Convert.ToDouble(1);
                entity["msnfp_receiptgeneration"]  = new OptionSetValue(844060000);
                entity["msnfp_receiptissuedate"]   = DateTime.Now;
                localContext.TracingService.Trace("Getting transaction count.");
                localContext.TracingService.Trace("Old msnfp_transactioncount: " + (int)entity["msnfp_transactioncount"]);
                entity["msnfp_transactioncount"] = (int)entity["msnfp_transactioncount"] + 1;
                localContext.TracingService.Trace("New msnfp_transactioncount: " + (int)entity["msnfp_transactioncount"]);
                if (item.Contains("transactioncurrencyid"))
                {
                    entity["transactioncurrencyid"] = new EntityReference("transactioncurrency", ((EntityReference)item["transactioncurrencyid"]).Id);
                }
                if (item.Contains("msnfp_customerid"))
                {
                    string logicalName = ((EntityReference)item["msnfp_customerid"]).LogicalName;
                    Guid   id          = ((EntityReference)item["msnfp_customerid"]).Id;
                    entity["msnfp_customerid"] = new EntityReference(logicalName, id);
                }
                string logicalName2 = ((EntityReference)item["ownerid"]).LogicalName;
                Guid   id2          = ((EntityReference)item["ownerid"]).Id;
                entity["ownerid"]    = new EntityReference(logicalName2, id2);
                entity["statuscode"] = new OptionSetValue(1);
                if (item.Contains("msnfp_taxreceiptid"))
                {
                    localContext.TracingService.Trace("Replace old receipt with this one.");
                    if (item.Contains("msnfp_previousreceiptid"))
                    {
                        localContext.TracingService.Trace("Old Previous Receipt ID: " + ((EntityReference)item["msnfp_previousreceiptid"]).Id.ToString());
                    }
                    item["msnfp_previousreceiptid"] = new EntityReference("msnfp_receipt", ((EntityReference)item["msnfp_taxreceiptid"]).Id);
                    localContext.TracingService.Trace("Updated Previous Receipt ID: " + ((EntityReference)item["msnfp_previousreceiptid"]).Id.ToString());
                    localContext.TracingService.Trace("Saving Transaction.");
                    if (!organizationServiceContext.IsAttached(item))
                    {
                        organizationServiceContext.Attach(item);
                    }
                    organizationServiceContext.UpdateObject(item);
                    organizationServiceContext.SaveChanges();
                    localContext.TracingService.Trace("Transaction Updated.");
                }
                localContext.TracingService.Trace("------------------");
            }
            localContext.TracingService.Trace("Saving Receipt.");
            service.Update(entity);
            localContext.TracingService.Trace("Receipt updated.");
            localContext.TracingService.Trace("Exiting UpdateReceiptAmountForThisTransaction()");
        }
예제 #24
0
        private void CreateQuotePayPal(Dictionary <string, string> values, IPortalContext xrm)
        {
            _context = xrm.ServiceContext;

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

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

            var quote = new Entity("quote");

            var orderGuid = Guid.NewGuid();

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

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

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

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

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

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

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

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

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

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

            quote.Attributes["pricelevelid"] = priceLevelReference;

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

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

            _context.AddObject(quote);

            _context.UpdateObject(shoppingCart);

            _context.SaveChanges();

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


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

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

            Entity = _context.CreateQuery("quote").FirstOrDefault(o => o.GetAttributeValue <Guid>("quoteid") == orderGuid);
            Id     = Entity.Id;
        }
예제 #25
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_isosetup")
                    return;

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

                if (entity.Attributes.Contains("statuscode"))
                {
                    try
                    {

                        QueryExpression countries = new QueryExpression
                        {
                            EntityName = "gcbase_isocountry",
                            ColumnSet = new ColumnSet("gcbase_name", "gcbase_iso316612lettercode"),
                        };

                        QueryExpression subDivisions = new QueryExpression
                        {
                            EntityName = "gcbase_isosubdivision",
                            ColumnSet = new ColumnSet("gcbase_name", "gcbase_countrycode"),
                        };

                        DataCollection<Entity> allCountries = service.RetrieveMultiple(countries).Entities;
                        DataCollection<Entity> allSubDivisions = service.RetrieveMultiple(subDivisions).Entities;
                        foreach (Entity sd in allSubDivisions) {
                            var countryCode = sd.GetAttributeValue<string>("gcbase_countrycode").ToString();
                            tracingService.Trace("ios plugin: {0}", countryCode);
                            QueryExpression countryRef = new QueryExpression
                            {
                                EntityName = "gcbase_isocountry",
                                ColumnSet = new ColumnSet("gcbase_name", "gcbase_iso316612lettercode"),
                                Criteria = new FilterExpression
                                {
                                    Conditions = {
                                        new ConditionExpression {
                                        AttributeName = "gcbase_iso316612lettercode",
                                        Operator = ConditionOperator.Equal,
                                        Values = { countryCode }
                                        }
                                    }
                                }
                            };
                            EntityCollection countryData = service.RetrieveMultiple(countryRef);
                            if (countryData.Entities.Count() > 0)
                            {
                                Entity country = (Entity)countryData.Entities.FirstOrDefault();
                                EntityReference isoCountry = new EntityReference("gcbase_isocountry", country.Id);
                                sd["gcbase_isocountry"] = isoCountry;
                                ctx.Attach(sd);
                                ctx.UpdateObject(sd);
                                ctx.SaveChanges();
                            }

                        };

                    }

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

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

                }

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

            _context = xrm.ServiceContext;

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

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

            var order = new Entity("salesorder");

            var orderGuid = Guid.NewGuid();

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

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

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

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

            var supportRequest = _context.CreateQuery("adx_supportrequest")
                                 .FirstOrDefault(sr => sr.GetAttributeValue <EntityReference>("adx_shoppingcartid").Id == shoppingCart.Id);

            if (supportRequest != null)
            {
                System.Diagnostics.Debug.Write(string.Format("Support Request ID:{0}", supportRequest.Id.ToString()));

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

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

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

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

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

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

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

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

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

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

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

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

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

            order.Attributes["pricelevelid"] = priceLevelReference;

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

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

            _context.AddObject(order);

            _context.UpdateObject(shoppingCart);

            _context.SaveChanges();

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


            //Time to associate order with support plan

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


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


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

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

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

            Entity = _context.CreateQuery("salesorder").FirstOrDefault(o => o.GetAttributeValue <Guid>("salesorderid") == orderGuid);
            Id     = Entity.Id;
        }
예제 #27
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;
            }
        }
        protected void ApplyDiscount_OnClick(object sender, EventArgs e)
        {
            if (Purchasable == null)
            {
                return;
            }

            var discountCode = DiscountCode.Value;

            var discountCodeValidationResult = DiscountCodeValidationResult.ValidateDiscountCode(ServiceContext, Purchasable.Quote.Id, discountCode);

            if (!discountCodeValidationResult.IsValid)
            {
                DiscountErrorAlreadyApplied.Visible = discountCodeValidationResult.ErrorCode ==
                                                      DiscountCodeValidationResult.DiscountErrorCode.AlreadyApplied ||
                                                      discountCodeValidationResult.DiscountErrors.Any(
                    o => o.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.AlreadyApplied);
                DiscountErrorCodeNotSpecified.Visible = discountCodeValidationResult.ErrorCode ==
                                                        DiscountCodeValidationResult.DiscountErrorCode.CodeNotSpecified ||
                                                        discountCodeValidationResult.DiscountErrors.Any(
                    o => o.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.CodeNotSpecified);
                DiscountErrorDoesNotExist.Visible = discountCodeValidationResult.ErrorCode ==
                                                    DiscountCodeValidationResult.DiscountErrorCode.DoesNotExist ||
                                                    discountCodeValidationResult.DiscountErrors.Any(
                    o => o.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.DoesNotExist);
                DiscountErrorInvalidDiscount.Visible = discountCodeValidationResult.ErrorCode ==
                                                       DiscountCodeValidationResult.DiscountErrorCode.InvalidDiscountConfiguration ||
                                                       discountCodeValidationResult.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.QuoteNotFound ||
                                                       discountCodeValidationResult.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.UpdateFailed ||
                                                       discountCodeValidationResult.DiscountErrors.Any(
                    o => o.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.InvalidDiscountConfiguration);
                DiscountErrorMaximumRedemptions.Visible = discountCodeValidationResult.ErrorCode ==
                                                          DiscountCodeValidationResult.DiscountErrorCode.MaximumRedemptions ||
                                                          discountCodeValidationResult.DiscountErrors.Any(
                    o => o.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.MaximumRedemptions);
                DiscountErrorMinimumAmountNotMet.Visible = discountCodeValidationResult.ErrorCode ==
                                                           DiscountCodeValidationResult.DiscountErrorCode.MinimumAmountNotMet ||
                                                           discountCodeValidationResult.DiscountErrors.Any(
                    o => o.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.MinimumAmountNotMet);
                DiscountErrorUnknown.Visible    = discountCodeValidationResult.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.Unknown || (discountCodeValidationResult.ErrorCode == 0 && !discountCodeValidationResult.DiscountErrors.Any());
                DiscountErrorZeroAmount.Visible = discountCodeValidationResult.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.ZeroAmount ||
                                                  discountCodeValidationResult.DiscountErrors.Any(
                    o => o.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.ZeroAmount);
                DiscountErrorNotApplicable.Visible = discountCodeValidationResult.ErrorCode ==
                                                     DiscountCodeValidationResult.DiscountErrorCode.NotApplicable ||
                                                     discountCodeValidationResult.DiscountErrors.Any(
                    o =>
                    o.ErrorCode == DiscountCodeValidationResult.DiscountErrorCode.NotApplicable);

                return;
            }

            DiscountErrorAlreadyApplied.Visible      = false;
            DiscountErrorCodeNotSpecified.Visible    = false;
            DiscountErrorDoesNotExist.Visible        = false;
            DiscountErrorInvalidDiscount.Visible     = false;
            DiscountErrorMaximumRedemptions.Visible  = false;
            DiscountErrorMinimumAmountNotMet.Visible = false;
            DiscountErrorUnknown.Visible             = false;
            DiscountErrorZeroAmount.Visible          = false;

            try
            {
                // Add new discount code to existing discount codes and update quote, plugins will process the code.
                var updateContext = new OrganizationServiceContext(new OrganizationService("Xrm"));
                var quoteUpdate   = new Entity("quote")
                {
                    Id = Purchasable.Quote.Id
                };
                var updateDiscountCodes = string.IsNullOrWhiteSpace(discountCodeValidationResult.ExistingDiscountCodes) ? discountCode : string.Format("{0},{1}", discountCodeValidationResult.ExistingDiscountCodes, discountCode);
                quoteUpdate["adx_discountcodes"] = updateDiscountCodes;
                updateContext.Attach(quoteUpdate);
                updateContext.UpdateObject(quoteUpdate);
                updateContext.SaveChanges();
            }
            catch (Exception ex)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, ex.ToString());
            }

            Target = GetTargetEntityReference();

            if (Target == null)
            {
                return;
            }

            var options = IsPostBack
                                ? GetPostedOptions()
                                : Enumerable.Empty <IPurchasableItemOptions>();

            Guid quoteId;

            if (IsPostBack && Guid.TryParse(QuoteId.Value, out quoteId))
            {
                WebForm.CurrentSessionHistory.QuoteId = quoteId;
            }

            var dataAdapter = CreatePurchaseDataAdapter(Target, CurrentStepEntityPrimaryKeyLogicalName);

            var quoteProducts = ServiceContext.CreateQuery("quotedetail").Where(q => q.GetAttributeValue <EntityReference>("quoteid") == Purchasable.Quote).ToArray();

            foreach (var quoteProduct in quoteProducts)
            {
                ServiceContext.TryRemoveFromCache(quoteProduct);
            }

            Purchasable = dataAdapter.Select(options);

            PurchaseDiscounts.DataSource = Purchasable.Discounts;
            PurchaseDiscounts.DataBind();

            PurchaseItems.DataSource = Purchasable.Items;
            PurchaseItems.DataBind();

            DiscountCode.Value = string.Empty;
        }
예제 #29
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);
        }
예제 #30
0
        public void CaseDeletion(IOrganizationService _orgServ)
        {
            Console.WriteLine("Starting Case Deletion");
            OrganizationServiceContext _orgContext = new OrganizationServiceContext(_orgServ);
            Incident myCase     = null;
            int      pageNo     = 1;
            int      record     = 0;
            string   casTickNum = "";
            string   casType;
            Guid     last  = new Guid();
            Guid     first = new Guid();

start:
            EntityCollection retrievedCases = GetCases(_orgServ, pageNo, casTickNum, first, last);

            if (retrievedCases.Entities.Count > 1)
            {
                Console.WriteLine("Cases Retrieved");

                for (int r = 0; r < retrievedCases.Entities.Count; r++)
                {
                    record++;
                    Console.WriteLine("record number = " + record);
                    myCase = retrievedCases[r].ToEntity <Incident>();
                    var casId = myCase.IncidentId;

                    if (myCase.gcs_CaseTypes == null)
                    {
                        _orgContext.Attach(myCase);
                        _orgContext.DeleteObject(myCase);
                        _orgContext.Dispose();
                        continue;
                    }
                    casType = myCase.gcs_CaseTypes.Name.ToString();

                    CaseSaveList((Guid)casId, casType);

                    int idExist = safeList.FindIndex(s => s.caseGuid == casId);

                    try
                    {
                        if (idExist >= 0)
                        {
                            Entity updateCase = new Entity();
                            updateCase.LogicalName = myCase.LogicalName;
                            updateCase.Attributes["shg_casesavefield"] = true;
                            updateCase.Id = myCase.Id;
                            if (myCase.StateCode != 0)
                            {
                                SetStateRequest setStateRequest = new SetStateRequest()
                                {
                                    EntityMoniker = new EntityReference
                                    {
                                        Id          = myCase.Id,
                                        LogicalName = myCase.LogicalName,
                                    },
                                    Status = new OptionSetValue(1),
                                    State  = new OptionSetValue(0)
                                };
                                _orgServ.Execute(setStateRequest);
                            }
                            _orgServ.Update(updateCase);
                            continue;
                        }
                    }
                    catch (FaultException <OrganizationServiceFault> e)
                    {
                        Console.WriteLine(e + "case which failed = " + myCase.TicketNumber + " case type = " + myCase.gcs_CaseTypes);
                        continue;
                    }
                }
                pageNo++;
                first = (Guid)retrievedCases.Entities.Select(s => s.Attributes["incidentid"]).First();
                last  = (Guid)retrievedCases.Entities.Select(s => s.Attributes["incidentid"]).Last();
                goto start;
            }
            else
            {
                BulkCaseDeletion(_orgServ);
                BulkActivityDeletion(_orgServ);
            }
        }
예제 #31
0
        public void UpdateWebTemplates(string inputPath, string websitePrimaryKey)
        {
            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);

            IList <WebTemplate> webTemplates = CrmService.GetWebTemplates(websiteId);

            OrganizationServiceContext.ClearChanges();

            foreach (FileInfo file in files)
            {
                Logger.Info(CultureInfo.InvariantCulture, "Processing file {0}.", file.FullName);

                string fileName = file.Name.ToUpperInvariant().Replace(".HTML", string.Empty);

                WebTemplate webTemplate = webTemplates.SingleOrDefault(x => x.Name.ToUpperInvariant().Equals(fileName));

                if (webTemplate == null)
                {
                    Logger.Warn(CultureInfo.InvariantCulture, "There is no portal web template entity for the file {0}.", file.Name);
                    continue;
                }

                string source = File.ReadAllText(file.FullName);
                if (source.Equals(webTemplate.Source))
                {
                    continue;
                }

                var updatedWebTemplate = new WebTemplate
                {
                    Id     = webTemplate.Id,
                    Source = source
                };

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

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
        public void When_updating_a_not_existing_entity_using_organization_context_exception_should_be_thrown()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

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

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                existingAccount.Name = "Super Great Customer Name Updated!";

                ctx.Attach(existingAccount);
                ctx.UpdateObject(existingAccount);
                Assert.Throws<SaveChangesException>(() => ctx.SaveChanges());
            }
        }
예제 #33
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);
            }
        }
예제 #34
0
        private void CreateOrderAuthorizeNet(Dictionary <string, string> values,
                                             IPortalContext xrm,
                                             bool getCreateInvoiceSettingValue,
                                             Entity account = null,
                                             string tombstoneEntityLogicalName    = null,
                                             string tombstoneEntityPrimaryKeyName = null)
        {
            _context = xrm.ServiceContext;

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

            var orderId = values["order_id"];

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

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

            Entity tombstoneEntity = null; Entity shoppingCart = null; Entity supportPlan = null;



            if (tombstoneEntityLogicalName != null)
            {
                tombstoneEntity = _context.CreateQuery(tombstoneEntityLogicalName)
                                  .FirstOrDefault(sr => sr.GetAttributeValue <Guid>(tombstoneEntityPrimaryKeyName) == tombstoneEntityId);

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

            if (tombstoneEntityLogicalName == "adx_supportrequest")
            {
                supportPlan = _context.CreateQuery("adx_supportplan").FirstOrDefault(sc => sc.GetAttributeValue <Guid>("adx_supportplanid")
                                                                                     == tombstoneEntity.GetAttributeValue <EntityReference>("adx_supportplan").Id);
            }


            var orderGuid = Guid.NewGuid();

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

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

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

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

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

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

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

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

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

                Entity parentCustomerEntity = null;

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

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

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

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

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

            order.Attributes["pricelevelid"] = priceLevelReference;

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

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

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

            _context.AddObject(order);

            _context.UpdateObject(shoppingCart);

            _context.SaveChanges();

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

            tombstoneEntity = _context.CreateQuery(tombstoneEntityLogicalName)
                              .FirstOrDefault(sr => sr.GetAttributeValue <Guid>(tombstoneEntityPrimaryKeyName) == tombstoneEntityId);

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

            //Deactivate the shopping Cart

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

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

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

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

            //writer.Close();
        }
예제 #35
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_isosetup")
                {
                    return;
                }

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

                if (entity.Attributes.Contains("statuscode"))
                {
                    try
                    {
                        QueryExpression countries = new QueryExpression
                        {
                            EntityName = "gcbase_isocountry",
                            ColumnSet  = new ColumnSet("gcbase_name", "gcbase_iso316612lettercode"),
                        };


                        QueryExpression subDivisions = new QueryExpression
                        {
                            EntityName = "gcbase_isosubdivision",
                            ColumnSet  = new ColumnSet("gcbase_name", "gcbase_countrycode"),
                        };

                        DataCollection <Entity> allCountries    = service.RetrieveMultiple(countries).Entities;
                        DataCollection <Entity> allSubDivisions = service.RetrieveMultiple(subDivisions).Entities;
                        foreach (Entity sd in allSubDivisions)
                        {
                            var countryCode = sd.GetAttributeValue <string>("gcbase_countrycode").ToString();
                            tracingService.Trace("ios plugin: {0}", countryCode);
                            QueryExpression countryRef = new QueryExpression
                            {
                                EntityName = "gcbase_isocountry",
                                ColumnSet  = new ColumnSet("gcbase_name", "gcbase_iso316612lettercode"),
                                Criteria   = new FilterExpression
                                {
                                    Conditions =
                                    {
                                        new ConditionExpression {
                                            AttributeName = "gcbase_iso316612lettercode",
                                            Operator      = ConditionOperator.Equal,
                                            Values        =     { countryCode}
                                        }
                                    }
                                }
                            };
                            EntityCollection countryData = service.RetrieveMultiple(countryRef);
                            if (countryData.Entities.Count() > 0)
                            {
                                Entity          country    = (Entity)countryData.Entities.FirstOrDefault();
                                EntityReference isoCountry = new EntityReference("gcbase_isocountry", country.Id);
                                sd["gcbase_isocountry"] = isoCountry;
                                ctx.Attach(sd);
                                ctx.UpdateObject(sd);
                                ctx.SaveChanges();
                            }
                        }
                        ;
                    }

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

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