public void When_doing_a_crm_linq_query_with_an_equals_operator_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid1, FirstName = "Jordi" },
                new Contact() { Id = guid2, FirstName = "Other" }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName.Equals("Jordi")
                               select c).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName.Equals("Jordi"));

                matches = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName == "Jordi" //Using now equality operator
                               select c).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName.Equals("Jordi"));
            }
            
        }
        public void When_doing_a_crm_linq_query_and_proxy_types_and_a_selected_attribute_returned_projected_entity_is_thesubclass()
        {
            var fakedContext = new XrmFakedContext();
            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid1, FirstName = "Jordi" },
                new Contact() { Id = guid2, FirstName = "Other" }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName.Equals("Jordi")
                               select new
                               {
                                   FirstName = c.FirstName,
                                   CrmRecord = c
                               }).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName.Equals("Jordi"));
                Assert.IsAssignableFrom(typeof(Contact), matches[0].CrmRecord);
                Assert.True(matches[0].CrmRecord.GetType() == typeof(Contact));

            }
        }
        public void UpdateBaselineProjection(CustomBaselineProjection bp)
        {
            using (var ctx = new XrmServiceContext("Xrm"))
            {
                var bps = (from s in ctx.new_baselineprojectionsSet
                            where s.Id == bp.Id
                            select s).FirstOrDefault();
                bps.new_name = bp.Name;

                bps.new_Year = bp.Year;
                bps.new_CA_Q1Actual = (int)bp.CA_Q1_A;
                bps.new_Q1_ca = (decimal)bp.CA_Q1_P;
                bps.new_CA_Q2Actual = (int)bp.CA_Q2_A;
                bps.new_Q2_ca = (decimal)bp.CA_Q2_P;
                bps.new_CA_Q3Actual = (int)bp.CA_Q3_A;
                bps.new_Q3_ca = (decimal)bp.CA_Q3_P;
                bps.new_CA_Q4Actual = (int)bp.CA_Q4_A;
                bps.new_Q4_ca = (decimal)bp.CA_Q4_P;

                bps.new_DB_Q1Actual = (int)bp.DB_Q1_A;
                bps.new_Q1_db = (decimal)bp.DB_Q1_P;
                bps.new_DB_Q2Actual = (int)bp.DB_Q2_A;
                bps.new_Q2_db = (decimal)bp.DB_Q2_P;
                bps.new_DB_Q3Actual = (int)bp.DB_Q3_A;
                bps.new_Q3_db = (decimal)bp.DB_Q3_P;
                bps.new_DB_Q4Actual = (int)bp.DB_Q4_A;
                bps.new_Q4_db = (decimal)bp.DB_Q4_P;

                ctx.UpdateObject(bps);
                ctx.SaveChanges();
            }
        }
        public static void When_using_proxy_types_assembly_the_attribute_metadata_is_inferred_from_the_proxy_types_assembly()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contact1 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact1["fullname"] = "Contact 1"; contact1["firstname"] = "First 1";
            var contact2 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact2["fullname"] = "Contact 2"; contact2["firstname"] = "First 2";

            fakedContext.Initialize(new List <Entity>()
            {
                contact1, contact2
            });

            var guid = Guid.NewGuid();

            //Empty contecxt (no Initialize), but we should be able to query any typed entity without an entity not found exception

            var service = fakedContext.GetOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Contact>()
                               where c.FirstName.Equals("First 1")
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public static void When_using_proxy_types_assembly_the_finding_attribute_metadata_fails_if_neither_proxy_type_or_injected_metadata_exist()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contact1 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact1["injectedAttribute"] = "Contact 1";
            var contact2 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact2["injectedAttribute"] = "Contact 2";

            fakedContext.Initialize(new List <Entity>()
            {
                contact1, contact2
            });

            var guid = Guid.NewGuid();

            var service = fakedContext.GetOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                Assert.Throws <Exception>(() => (from c in ctx.CreateQuery <Contact>()
                                                 where c["injectedAttribute"].Equals("Contact 1")
                                                 select c).ToList());
            }
        }
Exemple #6
0
        public void When_execute_is_called_with_reversed_target_and_Related()
        {
            var context = new XrmFakedContext();

            var userId  = Guid.NewGuid();
            var teamId  = Guid.NewGuid();
            var user2Id = Guid.NewGuid();

            context.Initialize(new List <Entity> {
                new SystemUser
                {
                    Id = userId
                },
                new SystemUser
                {
                    Id = user2Id
                },
                new Team
                {
                    Id = teamId
                }
            });

            context.AddRelationship("teammembership", new XrmFakedRelationship()
            {
                RelationshipType   = XrmFakedRelationship.enmFakeRelationshipType.ManyToMany,
                IntersectEntity    = "teammembership",
                Entity1Attribute   = "systemuserid",
                Entity1LogicalName = "systemuser",
                Entity2Attribute   = "teamid",
                Entity2LogicalName = "team"
            });

            var orgSvc = context.GetFakedOrganizationService();

            orgSvc.Associate("team", teamId, new Relationship("teammembership"),
                             new EntityReferenceCollection(new List <EntityReference> {
                new EntityReference("systemuser", userId)
            }));

            orgSvc.Associate("systemuser", user2Id, new Relationship("teammembership"),
                             new EntityReferenceCollection(new List <EntityReference> {
                new EntityReference("team", teamId)
            }));

            using (Crm.XrmServiceContext ctx = new XrmServiceContext(orgSvc))
            {
                var firstAssociation = (from tu in ctx.TeamMembershipSet
                                        where tu.TeamId == teamId &&
                                        tu.SystemUserId == userId
                                        select tu).FirstOrDefault();
                Assert.NotNull(firstAssociation);

                var secondAssociation = (from tu in ctx.TeamMembershipSet
                                         where tu.TeamId == teamId &&
                                         tu.SystemUserId == user2Id
                                         select tu).FirstOrDefault();
                Assert.NotNull(secondAssociation);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_booleans_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid, IsBackofficeCustomer = true
                },
                new Contact()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Contact>()
                               where c.IsBackofficeCustomer != null && c.IsBackofficeCustomer.Value == true
                               where c.IsBackofficeCustomer.Value
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        /// <summary>
        /// Удаляет сущность с именем entityName из кеша
        /// </summary>
        /// <param name="xrmServiceContext"></param>
        /// <param name="entityName"></param>
        public static void ClearXrmCache(this XrmServiceContext xrmServiceContext, string entityName)
        {
            var dependency = String.Format("xrm:dependency:entity:{0}", entityName).ToLower();
            var cache      = ObjectCacheManager.GetInstance(null);

            cache.Remove(dependency);
        }
        public void When_executing_a_linq_query_with_equals_between_2_moneys_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new SalesOrderDetail()
                {
                    Id = guid, BaseAmount = new Money(1.1M)
                },
                new SalesOrderDetail()
                {
                    Id = Guid.NewGuid()
                }                                              //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <SalesOrderDetail>()
                               where c.BaseAmount == new Money(1.1M)
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_doubles_result_is_returned()
        {
            var fakedContext      = new XrmFakedContext();
            var guid              = Guid.NewGuid();
            var barcelonaLatitude = 41.387128;

            fakedContext.Initialize(new List <Entity>()
            {
                new Account()
                {
                    Id = guid, Address1_Latitude = barcelonaLatitude
                },
                new Account()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from a in ctx.CreateQuery <Account>()
                               where a.Address1_Latitude == barcelonaLatitude
                               select a).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_date_times_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid, BirthDate = new DateTime(2015, 02, 26, 3, 42, 59)
                },
                new Contact()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Contact>()
                               where c.BirthDate != null && c.BirthDate == new DateTime(2015, 02, 26, 3, 42, 59)
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_longs_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid
                },
                new Contact()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            fakedContext.Data["contact"][guid]["versionnumber"] = long.MaxValue; //Couldn´t be set by the Proxy types but set here just for testing long data types

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Contact>()
                               where c.VersionNumber == long.MaxValue
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_boolean_managed_properties_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Report()
                {
                    Id = guid, IsCustomizable = new BooleanManagedProperty(true)
                },
                new Report()
                {
                    Id = Guid.NewGuid()
                }                                    //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Report>()
                               where c.IsCustomizable.Value == true
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        internal static List <ComboUser> GetUsers(XrmServiceContext context, bool cached = true)
        {
            if (UserList.Any() && cached)
            {
                return(UserList);
            }

            lock (UserList)
            {
                UserList = new List <ComboUser>
                {
                    new ComboUser
                    {
                        Id   = Guid.Empty,
                        Name = "Calling User"
                    }
                };

                UserList.AddRange((from user in context.SystemUserSet
                                   where user.IsDisabled == false
                                   select new ComboUser
                {
                    Id = user.Id,
                    Name = user.FirstName + " " + user.LastName
                }).ToList().OrderBy(user => user.Name));
            }

            return(UserList);
        }
        internal static List <string> GetEntityFieldNames(string entityName, XrmServiceContext context, bool cached = true)
        {
            if (entityName == "none")
            {
                return(new List <string>());
            }

            if (AttributeList.ContainsKey(entityName) && cached)
            {
                return(AttributeList[entityName]);
            }

            lock (AttributeList)
            {
                var entityFilter = new MetadataFilterExpression(LogicalOperator.And);
                entityFilter.Conditions.Add(
                    new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityName));

                var entityProperties = new MetadataPropertiesExpression
                {
                    AllProperties = false
                };
                entityProperties.PropertyNames.AddRange("Attributes");

                var attributesFilter = new MetadataFilterExpression(LogicalOperator.And);
                attributesFilter.Conditions.Add(
                    new MetadataConditionExpression("AttributeOf", MetadataConditionOperator.Equals, null));

                var attributeProperties = new MetadataPropertiesExpression
                {
                    AllProperties = false
                };
                attributeProperties.PropertyNames.AddRange("LogicalName");

                var entityQueryExpression = new EntityQueryExpression
                {
                    Criteria       = entityFilter,
                    Properties     = entityProperties,
                    AttributeQuery = new AttributeQueryExpression
                    {
                        Criteria   = attributesFilter,
                        Properties = attributeProperties
                    }
                };

                var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
                {
                    Query = entityQueryExpression,
                    ClientVersionStamp = null
                };

                var attributeNames = ((RetrieveMetadataChangesResponse)context.Execute(retrieveMetadataChangesRequest))
                                     .EntityMetadata.First().Attributes
                                     .Select(attribute => attribute.LogicalName).OrderBy(name => name).ToList();

                AttributeList[entityName] = attributeNames;
            }

            return(AttributeList[entityName]);
        }
Exemple #16
0
        public void ManageLists(XrmServiceContext context, Contact contact)
        {
            foreach (RepeaterItem item in MarketingList.Items)
            {
                if (item != null)
                {
                    RepeaterItem repeaterItem = item;

                    var ml = context.ListSet.First(m => m.ListId == new Guid(((HiddenField)(repeaterItem.FindControl("ListID"))).Value));

                    var listCheckBox = (CheckBox)item.FindControl("ListCheckbox");

                    var contactLists = contact.listcontact_association.ToList();

                    var inList = contactLists.Any(list => list.ListId == ml.ListId);

                    if (listCheckBox.Checked && !inList)
                    {
                        context.AddMemberList(ml.ListId.Value, contact.ContactId.Value);
                    }
                    else if (!listCheckBox.Checked && inList)
                    {
                        context.RemoveMemberList(ml.ListId.Value, contact.ContactId.Value);
                    }
                }
            }
        }
        protected override GenericResult ConcreteExecute(IOrganizationService service)
        {
            var contact     = PhoneCall.RegardingObjectId;
            var phoneNumber = PhoneCall.PhoneNumber;

            //query to create a phone history only if the pair [phonenumber, contact] doesn't exist
            using (var ctx = new XrmServiceContext(service))
            {
                var exists = (from ph in ctx.CreateQuery <ultra_phonecallhistory>()
                              where ph.ultra_contactid.Id == contact.Id
                              where ph.ultra_phonenumber == phoneNumber
                              select ph).FirstOrDefault() != null;

                if (!exists)
                {
                    //Create phone history record
                    var phoneHistory = new ultra_phonecallhistory()
                    {
                        ultra_contactid    = contact,
                        ultra_phonenumber  = phoneNumber,
                        ultra_lastcalldate = DateTime.Now
                    };
                    phoneHistory.Id = service.Create(phoneHistory);

                    //Phonecall then assigned to the created phonecall history
                    PhoneCall.ultra_phonecallhistoryid = phoneHistory.ToEntityReference();
                }
            }

            return(GenericResult.Succeed());
        }
        public void When_executing_a_linq_query_with_equals_between_2_guids_result_is_returned()
        {
            var fakedContext       = new XrmFakedContext();
            var productId          = Guid.NewGuid();
            var salesOrderDetailId = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new SalesOrderDetail()
                {
                    Id = salesOrderDetailId, ProductId = new EntityReference(Product.EntityLogicalName, productId)
                },
                new SalesOrderDetail()
                {
                    Id = Guid.NewGuid()
                }                                              //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from s in ctx.CreateQuery <SalesOrderDetail>()
                               where s.SalesOrderDetailId == salesOrderDetailId
                               select s).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_optionsets_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var productId    = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Account()
                {
                    Id = Guid.NewGuid(), StatusCode = new OptionSetValue(1)
                },
                new Account()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from a in ctx.CreateQuery <Account>()
                               where a.StatusCode == new OptionSetValue(1)
                               select a).ToList();

                Assert.True(contact.Count == 1);
            }
        }
Exemple #20
0
        protected override void ExecuteLogic()
        {
            xrmContext = new XrmServiceContext(Service)
            {
                MergeOption = MergeOption.NoTracking
            };

            Log.Log("Getting target ...");
            var target = (Entity)Context.InputParameters["Target"];


            var autoNumberConfig = Helper.GetAutoNumberingConfig(target, config,
                                                                 Context as IPluginExecutionContext, Service, Log, out var isBackLogged);

            if (autoNumberConfig == null)
            {
                Log.Log($"Exiting.", LogLevel.Warning);
                return;
            }

            if (autoNumberConfig.FieldLogicalName == null)
            {
                throw new InvalidPluginExecutionException(
                          "Target field must be specified in the config record for plugin execution.");
            }

            var image = target;

            var autoNumbering = new AutoNumberingEngine(Service, Log, autoNumberConfig, target, image,
                                                        Context.OrganizationId.ToString());

            autoNumbering.GenerateAndUpdateRecord(false, false, isBackLogged);
        }
Exemple #21
0
        public void CreateRequiredRecords()
        {
            var orgFactory = new OrganizationServiceFactory();
            var orgSrv     = orgFactory.GetNewOrganizationService();
            var context    = new XrmServiceContext(orgSrv);

            var accFac = new AccountFactory();

            context.AddObject(accFac.CurrentEntity);

            var conFac = new ContactFactory();

            context.AddRelatedObject(accFac.CurrentEntity, new Relationship("contact_customer_accounts"), conFac.CurrentEntity);

            context.SaveChanges();

            var incFac = new IncidentFactory();

            incFac.CurrentEntity.CustomerId = accFac.CurrentEntity.ToEntityReference();
            context.AddObject(incFac.CurrentEntity);
            context.Attach(accFac.CurrentEntity);

            var wpFac = new WorkPackageFactory();

            context.AddRelatedObject(accFac.CurrentEntity, new Relationship("a24_account_workpackage_customer_ref"), wpFac.CurrentEntity);
            wpFac.CurrentEntity.a24_customer_ref = accFac.CurrentEntity.ToEntityReference();

            context.SaveChanges();
        }
Exemple #22
0
        public void When_querying_early_bound_entities_attribute_not_initialised_returns_null_in_joins()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var role = new Role()
            {
                Id = Guid.NewGuid()
            };
            var parentRole = new Role()
            {
                Id = Guid.NewGuid()
            };

            context.Initialize(new[] { role, parentRole });

            using (var ctx = new XrmServiceContext(service))
            {
                var roleResult = (from r in ctx.CreateQuery <Role>()
                                  join parent in ctx.CreateQuery <Role>() on r.ParentRoleId.Id equals parent.RoleId.Value
                                  select r).FirstOrDefault();

                Assert.Equal(roleResult, null);
            }
        }
Exemple #23
0
		static void Main(string[] args)
		{
			var xrm = new XrmServiceContext("Xrm");
			
			WriteExampleContacts(xrm);

			//create a new contact called Allison Brown
			var allisonBrown = new Xrm.Contact
			{
				FirstName = "Allison",
				LastName = "Brown",
				Address1_Line1 = "23 Market St.",
				Address1_City = "Sammamish",
				Address1_StateOrProvince = "MT",
				Address1_PostalCode = "99999",
				Telephone1 = "12345678",
				EMailAddress1 = "*****@*****.**"
			};

			xrm.AddObject(allisonBrown);
			xrm.SaveChanges();

			WriteExampleContacts(xrm);

			Console.WriteLine("Press any key to exit.");
			Console.ReadKey();
		}
        public void When_doing_a_crm_linq_query_and_proxy_types_projection_must_be_applied_after_where_clause()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid1, FirstName = "Jordi", LastName = "Montana" },
                new Contact() { Id = guid2, FirstName = "Other" }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.LastName == "Montana"  //Should be able to filter by a non-selected attribute
                               select new
                               {
                                   FirstName = c.FirstName
                               }).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName.Equals("Jordi"));
            }
        }
 public ProxyAccount GetOneAccount(Guid id)
 {
     CacheHelper.ClearCache();
     var xrm = new XrmServiceContext("Xrm");
     Account ac = xrm.AccountSet.Where(x => x.Id == id).FirstOrDefault();
     return ObjectConverter.SingleConvertToProxyAccount(ac);
 }
Exemple #26
0
        static void Main(string[] args)
        {
            var xrm = new XrmServiceContext("Xrm");

            WriteExampleContacts(xrm);

            //create a new contact called Allison Brown
            var allisonBrown = new Xrm.Contact
            {
                FirstName                = "Allison",
                LastName                 = "Brown",
                Address1_Line1           = "23 Market St.",
                Address1_City            = "Sammamish",
                Address1_StateOrProvince = "MT",
                Address1_PostalCode      = "99999",
                Telephone1               = "12345678",
                EMailAddress1            = "*****@*****.**"
            };

            xrm.AddObject(allisonBrown);
            xrm.SaveChanges();

            WriteExampleContacts(xrm);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
        public StepImage(CrmStepImage crmImage, XrmServiceContext context)
        {
            Context  = context;
            CrmImage = crmImage;

            InitializeComponent();
        }
        protected XrmServiceContext CreateXrmServiceContext(MergeOption? mergeOption = null)
        {
            //string organizationUri = ConfigurationManager.AppSettings["CRM_OrganisationUri"];

            string organizationUri = "https://existornest2.api.crm4.dynamics.com/XRMServices/2011/Organization.svc";

            IServiceManagement<IOrganizationService> OrganizationServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(organizationUri));
            AuthenticationProviderType OrgAuthType = OrganizationServiceManagement.AuthenticationType;
            AuthenticationCredentials authCredentials = GetCredentials(OrgAuthType);
            AuthenticationCredentials tokenCredentials = OrganizationServiceManagement.Authenticate(authCredentials);
            OrganizationServiceProxy organizationProxy = null;
            SecurityTokenResponse responseToken = tokenCredentials.SecurityTokenResponse;

            if (ConfigurationManager.AppSettings["CRM_AuthenticationType"] == "ActiveDirectory")
            {
                using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, authCredentials.ClientCredentials))
                {
                    organizationProxy.EnableProxyTypes();
                }
            }
            else
            {
                using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, responseToken))
                {
                    organizationProxy.EnableProxyTypes();
                }
            }

            IOrganizationService service = (IOrganizationService)organizationProxy;

            var context = new XrmServiceContext(service);
            if (context != null && mergeOption != null) context.MergeOption = mergeOption.Value;
            return context;
        }
        public void When_an_optionset_is_retrieved_where_its_value_is_an_enum_formatted_value_is_returned()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var account = new Account()
            {
                Id = Guid.NewGuid()
            };

            account["statecode"] = AccountState.Active;

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

            using (var ctx = new XrmServiceContext(service))
            {
                var a = (from acc in ctx.CreateQuery <Account>()
                         select acc).FirstOrDefault();

                Assert.True(a.FormattedValues != null);
                Assert.True(a.FormattedValues.Contains("statecode"));
                Assert.Equal("Active", a.FormattedValues["statecode"]);
            }
        }
        public void When_an_entity_is_returned_formatted_values_are_also_cloned()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var account = new Account()
            {
                Id = Guid.NewGuid()
            };

            account["statecode"] = new OptionSetValue(0);


            var formattedValues = new FormattedValueCollection();

            formattedValues.Add("statecode", "Active");
            account.Inject("FormattedValues", formattedValues);

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

            using (var ctx = new XrmServiceContext(service))
            {
                var a = (from acc in ctx.CreateQuery <Account>()
                         select acc).FirstOrDefault();

                Assert.True(a.FormattedValues != null);
                Assert.True(a.FormattedValues.Contains("statecode"));
                Assert.Equal("Active", a.FormattedValues["statecode"]);
            }
        }
        public List <ProxyAccount> GetAllConfirmingBanks()
        {
            CacheHelper.ClearCache();
            var xrm = new XrmServiceContext("Xrm");

            return(ObjectConverter.ConvertToProxyAccount(xrm.AccountSet.ToList().Where(c => c.new_AgencyRole == 100000013)));
        }
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";

        public List <ProxyAccount> GetAllAccounts()
        {
            CacheHelper.ClearCache();
            var xrm = new XrmServiceContext("Xrm");

            return(ObjectConverter.ConvertToProxyAccount(xrm.AccountSet.ToList()));
        }
        public static void When_using_proxy_types_assembly_the_attribute_metadata_is_inferred_from_the_proxy_types_assembly()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contact1 = new Entity("contact") { Id = Guid.NewGuid() }; contact1["fullname"] = "Contact 1"; contact1["firstname"] = "First 1";
            var contact2 = new Entity("contact") { Id = Guid.NewGuid() }; contact2["fullname"] = "Contact 2"; contact2["firstname"] = "First 2";

            fakedContext.Initialize(new List<Entity>() { contact1, contact2 });

            var guid = Guid.NewGuid();

            //Empty contecxt (no Initialize), but we should be able to query any typed entity without an entity not found exception

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName.Equals("First 1")
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        When_querying_by_an_attribute_which_wasnt_initialised_null_value_is_returned_for_early_bound_and_not_an_exception
            ()
        {
            var ctx = new XrmFakedContext();

            ctx.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Contact));

            var service = ctx.GetFakedOrganizationService();

            ctx.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id       = Guid.NewGuid(),
                    LastName = "Mcdonald"
                }
            });

            var name = "Mcdonald";

            using (var context = new XrmServiceContext(service))
            {
                var contacts = (from c in context.ContactSet
                                where c.FirstName == name || c.LastName == name
                                select new Contact {
                    Id = c.Id, FirstName = c.FirstName, LastName = c.LastName
                }).ToList();

                Assert.Equal(1, contacts.Count);
                Assert.Null(contacts[0].FirstName);
            }
        }
Exemple #35
0
        public void When_using_typed_entities_ProxyTypesAssembly_is_not_mandatory()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var c = new Contact()
            {
                Id = Guid.NewGuid(), FirstName = "Jordi"
            };

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

            //Linq 2 Query Expression
            using (var ctx = new XrmServiceContext(service))
            {
                var contacts = (from con in ctx.CreateQuery <Contact>()
                                select con).ToList();

                Assert.Equal(contacts.Count, 1);
            }

            //Query faked context directly
            var ex = Record.Exception(() => context.CreateQuery <Contact>());

            Assert.Null(ex);
        }
Exemple #36
0
        public TypeStep(CrmTypeStep crmStep, XrmServiceContext context)
        {
            Context = context;
            CrmStep = crmStep;

            InitializeComponent();
        }
        public void When_sorting_by_an_attribute_which_wasnt_initialised_an_exception_is_not_thrown()
        {
            var ctx = new XrmFakedContext();

            ctx.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Contact));

            var service = ctx.GetFakedOrganizationService();

            ctx.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = Guid.NewGuid(), FirstName = "Ronald", LastName = "Mcdonald"
                },
                new Contact()
                {
                    Id = Guid.NewGuid(), LastName = "Jordan"
                }
            });

            using (var context = new XrmServiceContext(service))
            {
                var contacts = (from c in context.ContactSet
                                orderby c.FirstName
                                select new Contact {
                    Id = c.Id, FirstName = c.FirstName, LastName = c.LastName
                }).ToList();

                Assert.Equal(2, contacts.Count);
                Assert.Null(contacts[0].FirstName);
            }
        }
 private DSAutoNumber GetEntityByName(string entityName)
 {
     using (XrmServiceContext context = new XrmServiceContext(OrganizationService))
     {
         var autoNumberDetail = context.dots_autonumberSet.FirstOrDefault(w => w.TargetEntityLogicalName == entityName);
         return(autoNumberDetail);
     }
 }
        public XrmSavedQueryDefinition EntityViewDefinitionGet(Guid id)
        {
            var xrmService = new XrmServiceContext(_organizationService);

            var query = xrmService.SavedQuerySet.Single(x => x.SavedQueryId == id);

            var savedQueryDefinition = MapSavedQueryToDefinition(query);

            return savedQueryDefinition;
        }
        public List<XrmSavedQueryDefinition> EntityViewDefinitionsGet(string entityName)
        {
            var xrmContext = new XrmServiceContext(_organizationService);

            var savedQueries = xrmContext.SavedQuerySet.Where(x => x.ReturnedTypeCode == entityName).ToList();

            var list = savedQueries.Select(MapSavedQueryToDefinition).ToList();

            return list;
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            var xrm = new XrmServiceContext("Xrm");

            //grab all contacts where the email address ends in @example.com
            var exampleContacts = xrm.OpportunitySet.ToList();

            ContactsGridView.DataSource = exampleContacts;
            ContactsGridView.DataBind();
        }
Exemple #42
0
		/// <summary>
		/// Grab all contacts where the email address ends in @example.com
		/// </summary>
		private static void WriteExampleContacts(XrmServiceContext xrm)
		{
			var exampleContacts = xrm.ContactSet
				.Where(c => c.EMailAddress1.EndsWith("@example.com"));

			//write the example Contacts
			foreach (var contact in exampleContacts)
			{
				Console.WriteLine(contact.FullName);
			}
		}
		protected void Page_Load(object sender, EventArgs e)
		{
			var xrm = new XrmServiceContext("Xrm");

			//grab all contacts where the email address ends in @example.com
			var exampleContacts = xrm.ContactSet
				.Where(c => c.EMailAddress1.EndsWith("@example.com"));

			ContactsGridView.DataSource = exampleContacts;
			ContactsGridView.DataBind();
		}
Exemple #44
0
 public RegisterController()
     : base()
 {
     try
     {
         context = new ConnectionContext().XrmContext;
     }
     catch(Exception ex)
     {
         throw;
     }
 }
Exemple #45
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var xrm = new XrmServiceContext("Xrm");

                //grab all contacts where the email address ends in @example.com
                var opps = xrm.OpportunitySet.ToList();
                this.OpportunityDropdown.DataSource = opps;
                this.OpportunityDropdown.DataBind();
            }
        }
Exemple #46
0
 public HomeController()
     : base()
 {
     try
     {
         context = new ConnectionContext().XrmContext;
     }
     catch
     {
         Session.RemoveAll();
         TempData["loginError"] = "Wystąpiły problemy z połaczeniem do CRM. Proszę spróbować później.";
         RedirectToAction("Index", "Login");
     }
 }
Exemple #47
0
 public ABaseController()
     : base()
 {
     try
     {
         context = new ConnectionContext().XrmContext;
     }
     catch (Exception e)
     {
         TempData["loginError"] = "Serwis chwilowo niedostępny.";
         Session["loggedUser"] = null;
         Session.RemoveAll();
         RedirectToAction("Index", "Login");
     }
 }
Exemple #48
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            XrmServiceContext xrm;

            xrm = new XrmServiceContext("Xrm");

            foreach (MyLead objLead in Leads)
            {
                //xrm.AddObject(objLead);
                Guid objLeadGuid = xrm.Create(objLead);//Using this method as opposed to xrm.AddObject results in getting the GUID required to add a note to the lead.
                                                        //This method also adds the Lead Object to the Db.
                objLead.Note.ObjectId = new Microsoft.Xrm.Client.CrmEntityReference("lead", objLeadGuid); //Creates the xref between the Annotation object (the note) and the lead
                xrm.AddObject(objLead.Note); //adds the note to the CRM Database..
            }

            xrm.SaveChanges();//this saves all the notes to the database.  The leads are automatically saved by calling the Create() method...
        }
        public void When_calling_context_add_and_save_changes_entity_is_added_to_the_faked_context()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            using(var ctx = new XrmServiceContext(service))
            {
                ctx.AddObject(new Account() { Name = "Test account" });
                ctx.SaveChanges();

                var account = ctx.CreateQuery<Account>()
                            .ToList()
                            .FirstOrDefault();

                Assert.Equal("Test account", account.Name);
            }
        }
        public void When_calling_context_add_addrelated_and_save_changes_entities_are_added_to_the_faked_context()
        {
            var context = new XrmFakedContext();

            var relationship = new XrmFakedRelationship()
            {
                IntersectEntity = "accountleads",
                Entity1Attribute = "accountid",
                Entity2Attribute = "leadid",
                Entity1LogicalName = "account",
                Entity2LogicalName = "lead"
            };
            context.AddRelationship("accountleads", relationship);

            var service = context.GetFakedOrganizationService();

            using (var ctx = new XrmServiceContext(service))
            {
                var account = new Account() { Name = "Test account" };
                ctx.AddObject(account);

                var contact = new Lead() { FirstName = "Jane", LastName = "Doe" };
                ctx.AddRelatedObject(account, new Relationship("accountleads"), contact);
                var result = ctx.SaveChanges();

                var resultaccount = ctx.CreateQuery<Account>()
                                       .ToList()
                                       .FirstOrDefault();

                Assert.NotNull(resultaccount);
                Assert.Equal("Test account", resultaccount.Name);

                var reaultlead = ctx.CreateQuery<Lead>()
                                    .ToList()
                                    .FirstOrDefault();

                Assert.NotNull(reaultlead);
                Assert.Equal("Jane", reaultlead.FirstName);
                Assert.Equal("Doe", reaultlead.LastName);

                var relationshipRecords = ctx.CreateQuery("accountleads")
                                             .ToList();
                Assert.NotEmpty(relationshipRecords);
            }
        }
        public static void When_using_proxy_types_assembly_the_entity_metadata_is_inferred_from_the_proxy_types_assembly()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
           
            //Empty contecxt (no Initialize), but we should be able to query any typed entity without an entity not found exception

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName.Equals("Anything!")
                               select c).ToList();

                Assert.True(contact.Count == 0);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_strings_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid, FirstName = "Jordi" }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName == "Jordi"
                               select c).FirstOrDefault();

                Assert.True(contact != null);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_boolean_managed_properties_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new Report() { Id = guid, IsCustomizable = new BooleanManagedProperty(true) },
                new Report() { Id = Guid.NewGuid()}  //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery<Report>()
                               where c.IsCustomizable.Value == true
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_doing_a_crm_linq_query_a_retrievemultiple_with_a_queryexpression_is_called()
        {
            var fakedContext = new XrmFakedContext();
            var guid = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid, FirstName = "Jordi" }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName.Equals("Jordi")
                               select c).FirstOrDefault();


            }
            A.CallTo(() => service.Execute(A<OrganizationRequest>.That.Matches(x => x is RetrieveMultipleRequest && ((RetrieveMultipleRequest)x).Query is QueryExpression))).MustHaveHappened();
        }
        public void When_executing_a_linq_query_with_equals_between_2_booleans_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid, IsBackofficeCustomer = true},
                new Contact() { Id = Guid.NewGuid()}  //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery<Contact>()
                               where c.IsBackofficeCustomer != null && c.IsBackofficeCustomer.Value == true
                               where c.IsBackofficeCustomer.Value
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
Exemple #56
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            var xrm = new XrmServiceContext("Xrm");

            var op = xrm.OpportunitySet.Where(c => c.Id == Guid.Parse(this.OpportunityDropdown.SelectedItem.Value));

            this.DetailsView1.DataSource = op;
            this.DetailsView1.DataBind();

            var single = op.FirstOrDefault();

            if (single.new_CategoryType == 100000001)
            {
                this.GridView1.DataSource = single.new_opportunity_new_nsocovenant.ToList();
            }
            else
            {
                this.GridView1.DataSource = single.new_opportunity_new_covenants.ToList();
            }
            this.GridView1.DataBind();
        }
        public void When_an_optionset_is_retrieved_where_its_value_is_an_enum_formatted_value_doesnt_contain_key_if_value_was_null()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var account = new Account() { Id = Guid.NewGuid() };
            account["statecode"] = null;

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

            using (var ctx = new XrmServiceContext(service))
            {
                var a = (from acc in ctx.CreateQuery<Account>()
                         select acc).FirstOrDefault();

                Assert.Equal(0, a.FormattedValues.Count);
                Assert.False(a.FormattedValues.Contains("statecode"));
            }
        }
        public void Should_Not_Change_Context_Objects_Without_Update_And_Retrieve_Multiple()
        {
            var entityId = Guid.NewGuid();
            var context = new XrmFakedContext();
            var service = context.GetOrganizationService();

            context.Initialize(new[] {
                new Account
                {
                    Id = entityId,
                    Name = "Adventure Works"
                }
            });

            Account firstRetrieve, secondRetrieve = null;
            using (var ctx = new XrmServiceContext(service))
            {
                firstRetrieve = ctx.CreateQuery<Account>()
                                    .Where(a => a.AccountId == entityId)
                                    .FirstOrDefault();

            }

            using (var ctx = new XrmServiceContext(service))
            {
                secondRetrieve = ctx.CreateQuery<Account>()
                                    .Where(a => a.AccountId == entityId)
                                    .FirstOrDefault();

            }

            firstRetrieve.Name = "Updated locally";

            Assert.False(firstRetrieve == secondRetrieve);
            Assert.Equal("Updated locally", firstRetrieve.Name);
            Assert.Equal("Adventure Works", secondRetrieve.Name);
        }
 public static List<ProxyConnection> ConvertToProxyConnection(IEnumerable<Xrm.Connection> connections, XrmServiceContext context)
 {
     List<ProxyConnection> result = new List<ProxyConnection>();
     foreach (Xrm.Connection c in connections)
     {
         ProxyConnection pc = SingleConvertToProxyConnection(c, context);
         result.Add(pc);
     }
     return result;
 }
        public static ProxyConnection SingleConvertToProxyConnection(Xrm.Connection connection, XrmServiceContext context)
        {
            ProxyConnection pc = null;
            if (connection != null)
            {
                pc = new ProxyConnection();
                pc.Name = connection.Name;
                pc.ID = connection.Id;
                pc.Role = connection.Record2RoleId != null ? connection.Record2RoleId.Name : string.Empty;
                pc.OpportunityId = connection.Record1Id != null ? connection.Record1Id.Id.ToString() : Guid.Empty.ToString();

                if ((connection.Record2Id != null) && (!string.IsNullOrEmpty(connection.Record2Id.LogicalName)))
                {
                    if (connection.Record2Id.LogicalName.Equals("contact", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //using (Xrm.XrmServiceContext context = new XrmServiceContext("Xrm"))
                        //{
                            var contact = context.ContactSet.Where(c => c.Id == connection.Record2Id.Id).FirstOrDefault();
                            if (contact != null)
                            {
                                pc.Fullname = contact.FullName;
                                pc.JobTitle = contact.JobTitle;
                                pc.AccountName = contact.contact_customer_accounts != null ? contact.contact_customer_accounts.Name : string.Empty;
                                pc.Email = contact.EMailAddress1;
                                pc.BusinessPhone = contact.Telephone1;
                                pc.MobilePhone = contact.MobilePhone;
                                pc.Fax = contact.Fax;
                                pc.PreferedMethodofContact = EnsureValueFromOptionSet(contact, "preferredcontactmethodcode"); // contact.PreferredContactMethodCode
                                pc.Address1_Street1 = contact.Address1_Line1;
                                pc.Address1_Street2 = contact.Address1_Line2;
                                pc.Address1_Street3 = contact.Address1_Line3;
                                pc.Address1_City = contact.Address1_City;
                                pc.Address1_StateProvince = contact.Address1_StateOrProvince;
                                pc.Address1_ZipCode = contact.Address1_PostalCode;
                                pc.Address1_CountryRegion = contact.Address1_Country;
                            }
                        //}
                    }
                }

            }
            return pc;
        }