/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // For this sample, all required entities are created in the Run() method. // Create/retrieve a user to get associated user details. SystemUser user = _serviceProxy.Retrieve(SystemUser.EntityLogicalName, SystemUserProvider.RetrieveAUserWithoutAnyRoleAssigned(_serviceProxy), new ColumnSet(new String[] { "domainname", "firstname", "lastname" })).ToEntity <SystemUser>(); // Extract the domain, username, firstname and lastname from the user record. String[] userPath = user.DomainName.Split(new char[] { '\\' }); if (userPath.Length > 1) { _domain = userPath[0] + "\\"; _userName = userPath[1]; } else { _domain = String.Empty; _userName = userPath[0]; } _firstName = user.FirstName; _lastName = user.LastName; }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Get the user from the Helper. _userId = SystemUserProvider.RetrieveMarketingManager(_serviceProxy); Console.Write("User retrieved, "); // Retrieve the security role needed to assign to the user. QueryExpression roleQuery = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = { Conditions = { new ConditionExpression("name", ConditionOperator.Equal, "Marketing Manager") } } }; Role role = (Role)_serviceProxy.RetrieveMultiple(roleQuery).Entities[0]; _roleId = role.Id; // Retrieve the default business unit needed to create the team. QueryExpression queryDefaultBusinessUnit = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; // Execute the query. BusinessUnit defaultBusinessUnit = (BusinessUnit)_serviceProxy.RetrieveMultiple( queryDefaultBusinessUnit).Entities[0]; // Instantiate a team entity record and set its property values. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Team setupTeam = new Team { Name = "ABC Management Team", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; // Create a team record. _teamId = _serviceProxy.Create(setupTeam); Console.Write("Created Team, "); }
/// <summary> /// This method creates any entity records that this sample requires. /// Create source queue and destination queue. /// Create a letter entity. /// Add letter entity to source queue. /// </summary> public void CreateRequiredRecords() { var QueueViewType = new { Public = 0, Private = 1 }; //Create new queues and store their returned GUIDs in variables for later use. Queue sourceQueue = new Queue { Name = "Source Queue", Description = "This is an example queue.", QueueViewType = new OptionSetValue(QueueViewType.Private) }; _sourceQueueId = _serviceProxy.Create(sourceQueue); Console.WriteLine("Created {0}", sourceQueue.Name); Queue destinationQueue = new Queue { Name = "Destination Queue", Description = "This is an example queue.", QueueViewType = new OptionSetValue(QueueViewType.Private) }; _destinationQueueId = _serviceProxy.Create(destinationQueue); Console.WriteLine("Created {0}", destinationQueue.Name); // Create a letter entity. Letter newLetter = new Letter { Description = "Example Letter" }; _letterId = _serviceProxy.Create(newLetter); Console.WriteLine("Created {0}", newLetter.Description); // Use AddToQueue message to add an entity into a queue, which will associate // the letter with the first queue. AddToQueueRequest addToSourceQueue = new AddToQueueRequest { DestinationQueueId = _sourceQueueId, Target = new EntityReference(Letter.EntityLogicalName, _letterId) }; _serviceProxy.Execute(addToSourceQueue); Console.WriteLine("Added letter record to {0}", sourceQueue.Name); // Retrieve/create a user record for assigning the queue item to the user's // queue. _userId = SystemUserProvider.RetrieveSalesManager(_serviceProxy); return; }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // For this sample, all required entities are created in the Run() method. // Create/Retrieve a user. _userId = SystemUserProvider.RetrieveAUserWithoutAnyRoleAssigned(_serviceProxy); if (_userId != Guid.Empty) { Console.WriteLine("{0} user retrieved.", _userId); } }
/// <summary> /// This method creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Get the current user's information. WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest); _currentUserId = userResponse.UserId; // Create another user, Kevin Cook. _otherUserId = SystemUserProvider.RetrieveSalesManager(_serviceProxy); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a second user that we will reference in our sample code. Guid userId = SystemUserProvider.RetrieveSalesManager(_serviceProxy); // Modify email address of user for sample. SystemUser systemUser = new SystemUser { Id = userId, InternalEMailAddress = "*****@*****.**" }; _service.Update(systemUser); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Retrieve a sales manager. _salesManagerId = SystemUserProvider.RetrieveMarketingManager(_serviceProxy); // Create an account. Account account = new Account() { Name = "Fourth Coffee", Address1_City = "Seattle" }; _accountId = _serviceProxy.Create(account); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Get the GUID of the Marketing Manager _userId = SystemUserProvider.RetrieveMarketingManager(_serviceProxy); // Instantiate an Account object. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Account setupAccount = new Account() { Name = "Fourth Coffee" }; _accountId = _service.Create(setupAccount); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // For this sample, all required entities are created in the Run() method. // Obtain the current user's information. WhoAmIRequest who = new WhoAmIRequest(); WhoAmIResponse whoResp = (WhoAmIResponse)_serviceProxy.Execute(who); Guid currentUserId = whoResp.UserId; SystemUser currentUser = _serviceProxy.Retrieve(SystemUser.EntityLogicalName, currentUserId, new ColumnSet("domainname")).ToEntity <SystemUser>(); // Extract the domain and create the LDAP object. String[] userPath = currentUser.DomainName.Split(new char[] { '\\' }); if (userPath.Length > 1) { _domain = userPath[0] + "\\"; } else { _domain = String.Empty; } SystemUser existingUser = SystemUserProvider.GetUserIdIfExist(_serviceProxy, _domain, _userName, _firstName, _lastName); if (existingUser != null) { throw new Exception("User already exist!"); } // Set up an Active Directory account in the current domain for this sample. String ldapPath = String.Empty; Boolean accountSetup = SystemUserProvider.CreateADAccount(_userName, _firstName, _lastName, _serviceProxy, ref ldapPath); if (accountSetup) { Console.WriteLine("An AD account created for '{0}, {1}'", _lastName, _firstName); } else { Console.WriteLine("AD account already exist for '{0}, {1}'", _lastName, _firstName); } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // For this sample, all required entities are created in the Run() method. // Create/retrieve a user and associate a role. _userId = SystemUserProvider.RetrieveAUserWithoutAnyRoleAssigned(_serviceProxy); // Find the role. QueryExpression query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection roles = _serviceProxy.RetrieveMultiple(query); if (roles.Entities.Count > 0) { Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity <Role>(); // Associate the user with the role for this sample. if (salesRole != null & amp; & _userId != Guid.Empty) { _serviceProxy.Associate( "systemuser", _userId, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, salesRole.Id) }); } } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve the ldapPath String ldapPath = String.Empty; // Retrieve the sales team - 1 sales manager and 2 sales representatives. _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath); _salesRepresentativeIds = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); #endregion #region Create records to support Opportunity records // Create a unit group UoMSchedule newUnitGroup = new UoMSchedule { Name = "Example Unit Group", BaseUoMName = "Example Primary Unit" }; _unitGroupId = _serviceProxy.Create(newUnitGroup); // Retrieve the default unit id that was automatically created // when we created the Unit Group QueryExpression unitQuery = new QueryExpression { EntityName = UoM.EntityLogicalName, ColumnSet = new ColumnSet("uomid", "name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "uomscheduleid", Operator = ConditionOperator.Equal, Values = { _unitGroupId } } } }, PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; // Retrieve the unit. UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0]; _defaultUnitId = unit.UoMId.Value; // Create a few products Product newProduct1 = new Product { ProductNumber = "1", Name = "Example Product 1", ProductStructure = new OptionSetValue(1), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _product1Id = _serviceProxy.Create(newProduct1); Console.WriteLine("Created {0}", newProduct1.Name); Product newProduct2 = new Product { ProductNumber = "2", Name = "Example Product 2", ProductStructure = new OptionSetValue(1), QuantityDecimal = 3, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _product2Id = _serviceProxy.Create(newProduct2); Console.WriteLine("Created {0}", newProduct2.Name); // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Example Price List" }; _priceListId = _serviceProxy.Create(newPriceList); // Create a price list item for the first product and apply volume discount ProductPriceLevel newPriceListItem1 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(20) }; _priceListItem1Id = _serviceProxy.Create(newPriceListItem1); // Create a price list item for the second product ProductPriceLevel newPriceListItem2 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product2Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(15) }; _priceListItem2Id = _serviceProxy.Create(newPriceListItem2); //Publish Product1 SetStateRequest publishRequest1 = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product1Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest1); //Publish Product2 SetStateRequest publishRequest2 = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest2); Console.WriteLine("Published both the products"); // Create an account record for the opportunity's potential customerid Account newAccount = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(newAccount)); #endregion Create records to support Opportunity records }
/// <summary> /// This method creates any entity records that this sample requires. /// Creates the visualization. /// </summary> public void CreateRequiredRecords() { // Create a sample account Account setupAccount = new Account { Name = "Sample Account" }; _accountId = _serviceProxy.Create(setupAccount); Console.WriteLine("Created {0}.", setupAccount.Name); // Create some oppotunity records for the visualization Opportunity[] setupOpportunities = new Opportunity[] { new Opportunity { Name = "Sample Opp 01", EstimatedValue = new Money(120000.00m), ActualValue = new Money(100000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" }, new Opportunity { Name = "Sample Opp 02", EstimatedValue = new Money(240000.00m), ActualValue = new Money(200000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" }, new Opportunity { Name = "Sample Opp 03", EstimatedValue = new Money(360000.00m), ActualValue = new Money(300000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" }, new Opportunity { Name = "Sample Opp 04", EstimatedValue = new Money(500000.00m), ActualValue = new Money(500000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" }, new Opportunity { Name = "Sample Opp 05", EstimatedValue = new Money(110000.00m), ActualValue = new Money(60000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" }, new Opportunity { Name = "Sample Opp 06", EstimatedValue = new Money(90000.00m), ActualValue = new Money(70000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" }, new Opportunity { Name = "Sample Opp 07", EstimatedValue = new Money(620000.00m), ActualValue = new Money(480000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" }, new Opportunity { Name = "Sample Opp 08", EstimatedValue = new Money(440000.00m), ActualValue = new Money(400000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" }, new Opportunity { Name = "Sample Opp 09", EstimatedValue = new Money(410000.00m), ActualValue = new Money(400000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" }, new Opportunity { Name = "Sample Opp 10", EstimatedValue = new Money(650000.00m), ActualValue = new Money(650000.00m), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), StepName = "Open" } }; _opportunitiyIds = (from opp in setupOpportunities select _serviceProxy.Create(opp)).ToArray(); Console.WriteLine("Created few opportunity records for {0}.", setupAccount.Name); // Create a visualization // Set The presentation XML string. string presentationXml = @" <Chart Palette='BrightPastel'> <Series> <Series _Template_='All' ShadowOffset='2' BorderColor='64, 64, 64' BorderDashStyle='Solid' BorderWidth='1' IsValueShownAsLabel='true' Font='Tahoma, 6.75pt, GdiCharSet=0' LabelForeColor='100, 100, 100' CustomProperties='FunnelLabelStyle=Outside' ChartType='Funnel'> <SmartLabelStyle Enabled='True' /> <Points /> </Series> </Series> <ChartAreas> <ChartArea _Template_='All' BackColor='Transparent' BorderColor='Transparent' BorderDashStyle='Solid'> <Area3DStyle Enable3D='True' IsClustered='True'/> </ChartArea> </ChartAreas> <Legends> <Legend _Template_='All' Alignment='Center' LegendStyle='Table' Docking='Bottom' IsEquallySpacedItems='True' BackColor='White' BorderColor='228, 228, 228' BorderWidth='0' Font='Tahoma, 8pt, GdiCharSet=0' ShadowColor='0, 0, 0, 0' ForeColor='100, 100, 100'> </Legend> </Legends> <Titles> <Title _Template_='All' Font='Tahoma, 9pt, style=Bold, GdiCharSet=0' ForeColor='102, 102, 102'> </Title> </Titles> <BorderSkin PageColor='Control' BackColor='CornflowerBlue' BackSecondaryColor='CornflowerBlue' /> </Chart> "; // Set the data XML string. string dataXml = @" <datadefinition> <fetchcollection> <fetch mapping='logical' count='10' aggregate='true'> <entity name='opportunity'> <attribute name='actualvalue_base' aggregate='sum' alias='sum_actualvalue_base' /> <attribute name='stepname' groupby='true' alias='stepname' /> <order alias='stepname' descending='false'/> </entity> </fetch> </fetchcollection> <categorycollection> <category> <measurecollection> <measure alias='sum_actualvalue_base'/> </measurecollection> </category> </categorycollection> </datadefinition> "; // Create the visualization entity instance. UserQueryVisualization newUserOwnedVisualization = new UserQueryVisualization { Name = "Sample User Visualization", Description = "Sample user-owned visualization.", PresentationDescription = presentationXml, DataDescription = dataXml, PrimaryEntityTypeCode = Opportunity.EntityLogicalName, }; _userOwnedVisualizationId = _serviceProxy.Create(newUserOwnedVisualization); Console.WriteLine("Created {0}.", newUserOwnedVisualization.Name); // Create another user to whom the visualization will be assigned. _otherUserId = SystemUserProvider.RetrieveSalesManager(_serviceProxy); }
public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // 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)) { String ldapPath = String.Empty; Guid businessUnitId; // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call this method to create any data that this sample requires. CreateRequiredRecords(); // Retrieve the sales people that will be added to the team. salesPersons = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); // Get the ID's of the current user and business unit. var who = new WhoAmIRequest(); var whoResponse = (WhoAmIResponse)_serviceProxy.Execute(who); _currentUserId = whoResponse.UserId; businessUnitId = whoResponse.BusinessUnitId; // Create a access team. var team = new Team { AdministratorId = new EntityReference( "systemuser", _currentUserId), Name = "UserAccess Test Team", BusinessUnitId = new EntityReference( "businessunit", businessUnitId), TeamType = new OptionSetValue((int)TeamTeamType.Access), }; _teamId = _serviceProxy.Create(team); Console.WriteLine("Created an access team named '{0}'.", team.Name); // Add two sales people to the access team. var addToTeamRequest = new AddMembersTeamRequest { TeamId = _teamId, MemberIds = new[] { salesPersons[0], salesPersons[1] } }; _serviceProxy.Execute(addToTeamRequest); Console.WriteLine("Added two sales people to the team."); // Grant the team read/write access to an account. var accountReference = new EntityReference(Account.EntityLogicalName, _accountId); var teamReference = new EntityReference(Team.EntityLogicalName, _teamId); var grantAccessRequest = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess, Principal = teamReference }, Target = accountReference }; _serviceProxy.Execute(grantAccessRequest); Console.WriteLine("Granted read/write access on the account record to the team."); // Retrieve and display access information for the account. RetrieveAndDisplayEntityAccess(accountReference); // Display the account access for the team and its members. var currentUserReference = new EntityReference( SystemUser.EntityLogicalName, _currentUserId); RetrieveAndDisplayPrincipalAccess(accountReference, currentUserReference, "Current User"); var firstSalesPersonReference = new EntityReference( SystemUser.EntityLogicalName, salesPersons[0]); RetrieveAndDisplayPrincipalAccess(accountReference, firstSalesPersonReference, "Sales Person"); var secondSalesPersonReference = new EntityReference( SystemUser.EntityLogicalName, salesPersons[1]); RetrieveAndDisplayPrincipalAccess(accountReference, secondSalesPersonReference, "Sales Person"); // Delete all records created by this sample. DeleteRequiredRecords(promptForDelete); } } // 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; } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a unique identifier for this sample for preventing name conflicts. var sampleIdentifier = Guid.NewGuid(); // Retrieve/create the system users to use for the sample. var ldapPath = String.Empty; _systemUserIds = SystemUserProvider.RetrieveDelegates( _serviceProxy, ref ldapPath); // Retrieve the root business unit to use for creating the team for the // sample. var businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = new FilterExpression() }; businessUnitQuery.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); var businessUnitResult = _serviceProxy.RetrieveMultiple(businessUnitQuery); var businessUnit = businessUnitResult.Entities[0].ToEntity <BusinessUnit>(); // Get the GUID of the current user. var who = new WhoAmIRequest(); var whoResponse = (WhoAmIResponse)_serviceProxy.Execute(who); _currentUserId = whoResponse.UserId; // Create a team for use in the sample. var team = new Team { AdministratorId = new EntityReference( "systemuser", _currentUserId), Name = String.Format("User Access Sample Team {0}", sampleIdentifier), BusinessUnitId = businessUnit.ToEntityReference() }; _teamId = _serviceProxy.Create(team); // Add the second user to the newly created team. var addToTeamRequest = new AddMembersTeamRequest { TeamId = _teamId, MemberIds = new[] { _systemUserIds[1] } }; _serviceProxy.Execute(addToTeamRequest); // Create a lead for use in the sample. var lead = new Lead { CompanyName = "User Access Sample Company", FirstName = "Sample", LastName = "Lead", Subject = "User Access Sample Lead", }; _leadId = _serviceProxy.Create(lead); // Create a task to associate to the lead. var leadReference = new EntityReference(Lead.EntityLogicalName, _leadId); var task = new Task { Subject = "User Access Sample Task", RegardingObjectId = leadReference }; _taskId = _serviceProxy.Create(task); // Create a letter to associate to the lead. var letter = new Letter { Subject = "User Access Sample Letter", RegardingObjectId = leadReference }; _serviceProxy.Create(letter); }
/// <summary> /// This method creates any entity records that this sample requires. /// Creates the dashboard. /// </summary> public void CreateRequiredRecords() { //Grab the default public view for opportunities. QueryExpression mySavedQuery = new QueryExpression { ColumnSet = new ColumnSet("savedqueryid"), EntityName = SavedQuery.EntityLogicalName, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "isdefault", Operator = ConditionOperator.Equal, Values = { true } }, new ConditionExpression { AttributeName = "querytype", Operator = ConditionOperator.Equal, Values = { 0 } }, new ConditionExpression { AttributeName = "returnedtypecode", Operator = ConditionOperator.Equal, Values = { Opportunity.EntityTypeCode } } } } }; //This query should return one and only one result. SavedQuery defaultOpportunityQuery = _serviceProxy.RetrieveMultiple(mySavedQuery) .Entities.Select(x => (SavedQuery)x).FirstOrDefault(); // Retrieve visualizations out of the system. // This sample assumes that you have the "Top Opportunities" // visualization that is installed with Microsoft Dynamics CRM. QueryByAttribute visualizationQuery = new QueryByAttribute { EntityName = SavedQueryVisualization.EntityLogicalName, ColumnSet = new ColumnSet("savedqueryvisualizationid"), Attributes = { "name" }, //If you do not have this visualization, you will need to change //this line. Values = { "Top Opportunities" } }; SavedQueryVisualization visualization = _serviceProxy.RetrieveMultiple(visualizationQuery). Entities.Select(x => (SavedQueryVisualization)x).FirstOrDefault(); //This is the language code for U.S. English. If you are running this code //in a different locale, you will need to modify this value. int languageCode = 1033; //We set up our dashboard and specify the FormXml. Refer to the //FormXml schema in the Microsoft Dynamics CRM SDK for more information. UserForm dashboard = new UserForm { Name = "Sample User Dashboard", Description = "Sample user-owned dashboard.", FormXml = String.Format(@"<form> <tabs> <tab name='Test Dashboard' verticallayout='true'> <labels> <label description='Sample User Dashboard' languagecode='{0}' /> </labels> <columns> <column width='100%'> <sections> <section name='Information Section' showlabel='false' showbar='false' columns='111'> <labels> <label description='Information Section' languagecode='{0}' /> </labels> <rows> <row> <cell colspan='1' rowspan='10' showlabel='false'> <labels> <label description='Top Opportunities - 1' languagecode='{0}' /> </labels> <control id='Top10Opportunities' classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'> <parameters> <ViewId>{1}</ViewId> <IsUserView>false</IsUserView> <RelationshipName /> <TargetEntityType>opportunity</TargetEntityType> <AutoExpand>Fixed</AutoExpand> <EnableQuickFind>false</EnableQuickFind> <EnableViewPicker>false</EnableViewPicker> <EnableJumpBar>false</EnableJumpBar> <ChartGridMode>Chart</ChartGridMode> <VisualizationId>{2}</VisualizationId> <EnableChartPicker>false</EnableChartPicker> <RecordsPerPage>10</RecordsPerPage> </parameters> </control> </cell> <cell colspan='1' rowspan='10' showlabel='false'> <labels> <label description='Top Opportunities - 2' languagecode='{0}' /> </labels> <control id='Top10Opportunities2' classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'> <parameters> <ViewId>{1}</ViewId> <IsUserView>false</IsUserView> <RelationshipName /> <TargetEntityType>opportunity</TargetEntityType> <AutoExpand>Fixed</AutoExpand> <EnableQuickFind>false</EnableQuickFind> <EnableViewPicker>false</EnableViewPicker> <EnableJumpBar>false</EnableJumpBar> <ChartGridMode>Grid</ChartGridMode> <VisualizationId>{2}</VisualizationId> <EnableChartPicker>false</EnableChartPicker> <RecordsPerPage>10</RecordsPerPage> </parameters> </control> </cell> </row> <row /> <row /> <row /> <row /> <row /> <row /> <row /> <row /> <row /> </rows> </section> </sections> </column> </columns> </tab> </tabs> </form>", languageCode, defaultOpportunityQuery.SavedQueryId.Value.ToString("B"), visualization.SavedQueryVisualizationId.Value.ToString("B")) }; _userDashboardId = _serviceProxy.Create(dashboard); Console.WriteLine("Created {0}.", dashboard.Name); // Create another user to whom the dashboard will be assigned. _otherUserId = SystemUserProvider.RetrieveSalesManager(_serviceProxy); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a second user that we will impersonate in our sample code. SystemUserProvider.RetrieveSalesManager(_serviceProxy); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // For this sample, all required entities are created in the Run() method. // Retrieve a user. _userId = SystemUserProvider.RetrieveAUserWithoutAnyRoleAssigned(_serviceProxy); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region create users Console.WriteLine(" Creating users"); var ldapPath = ""; _users = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); _users.Add(SystemUserProvider.RetrieveSystemUser( "dparker", "Darren", "Parker", "Salesperson", _serviceProxy, ref ldapPath)); #endregion #region fetch root business unit // Retrieve the root business unit to use for creating the team for the // sample. var businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = new FilterExpression() }; businessUnitQuery.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); var businessUnitResult = _serviceProxy.RetrieveMultiple(businessUnitQuery); _rootBusinessUnit = businessUnitResult.Entities[0].ToEntity <BusinessUnit>(); #endregion #region create new business unit Console.WriteLine(" Creating new business unit"); _businessUnit = new BusinessUnit() { Name = "A Sample Business Unit", ParentBusinessUnitId = _rootBusinessUnit.ToEntityReference() }; _businessUnit.Id = _serviceProxy.Create(_businessUnit); #endregion #region create team Console.WriteLine(" Creating a user team"); _team = new Team { AdministratorId = new EntityReference(SystemUser.EntityLogicalName, _users[0]), Name = "Sample team", BusinessUnitId = _rootBusinessUnit.ToEntityReference() }; _team.Id = _serviceProxy.Create(_team); var salespersonRole = (from role in _context.RoleSet where role.Name == "Salesperson" && role.BusinessUnitId.Id == _rootBusinessUnit.Id select role).First(); // assign role to the team _serviceProxy.Associate( Team.EntityLogicalName, _team.Id, new Relationship("teamroles_association"), new EntityReferenceCollection() { salespersonRole.ToEntityReference() } ); // wait for the async job to finish for (int i = 1; i <= 30; i++) { Console.WriteLine(" Checking to see if the async job has finished {0}/30", i); var teamPrivileges = (RetrieveTeamPrivilegesResponse) _serviceProxy.Execute(new RetrieveTeamPrivilegesRequest { TeamId = _team.Id }); if (teamPrivileges.RolePrivileges.Any((rp) => rp.PrivilegeId == new Guid("A8ECAC53-09E8-4A13-B598-8D8C87BC3D33"))) // prvReadLead { break; } System.Threading.Thread.Sleep(1000); } #endregion #region add users to team Console.WriteLine(" Adding users to the team"); AddMembersTeamRequest addMembers = new AddMembersTeamRequest() { TeamId = _team.Id, MemberIds = new Guid[] { _users[0], _users[1] } }; _serviceProxy.Execute(addMembers); #endregion #region create leads Console.WriteLine(" Creating leads"); _leads[0] = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Joe", LastName = "Andreshak", }; _leads[0].Id = _serviceProxy.Create(_leads[0]); _leads[1] = new Lead { CompanyName = "Wingtip Toys", FirstName = "Diogo", LastName = "Andrade" }; _leads[1].Id = _serviceProxy.Create(_leads[1]); _leads[2] = new Lead { CompanyName = "The Phone Company", FirstName = "Ronaldo", LastName = "Smith Jr." }; _leads[2].Id = _serviceProxy.Create(_leads[2]); _leads[3] = new Lead { CompanyName = "Tailspin Toys", FirstName = "Andrew", LastName = "Sullivan", }; _leads[3].Id = _serviceProxy.Create(_leads[3]); #endregion #region assign leads Console.WriteLine(" Assigning leads to users and teams"); _serviceProxy.Execute(new AssignRequest() { Assignee = new EntityReference(SystemUser.EntityLogicalName, _users[0]), Target = _leads[0].ToEntityReference() }); _serviceProxy.Execute(new AssignRequest() { Assignee = new EntityReference(SystemUser.EntityLogicalName, _users[1]), Target = _leads[1].ToEntityReference() }); _serviceProxy.Execute(new AssignRequest() { Assignee = new EntityReference(SystemUser.EntityLogicalName, _users[2]), Target = _leads[2].ToEntityReference() }); // give the team access to the record so that it can be assigned to it _serviceProxy.Execute(new GrantAccessRequest() { Target = _leads[3].ToEntityReference(), PrincipalAccess = new PrincipalAccess() { AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess, Principal = _team.ToEntityReference() } }); // assign the lead to the team _serviceProxy.Execute(new AssignRequest() { Assignee = _team.ToEntityReference(), Target = _leads[3].ToEntityReference() }); #endregion }
/// <summary> /// Helper method to create an active directory account /// </summary> /// <param name="userName">The username field as set in Microsoft Dynamics CRM</param> /// <param name="firstName">The first name of the system user to be retrieved</param> /// <param name="lastName">The last name of the system user to be retrieved</param> /// <param name="serviceProxy">The OrganizationServiceProxy object to your Microsoft /// Dynamics CRM environment</param> /// <param name="ldapPath">The LDAP path for your network - you can either call /// ConsolePromptForLDAPPath() to prompt the user or provide a value in code</param> /// <returns>Return true if new account is created or return false if account already exist.</returns> public static Boolean CreateADAccount(String userName, String firstName, String lastName, OrganizationServiceProxy serviceProxy, ref String ldapPath) { // Check to make sure this is not Microsoft Dynamics CRM Online. if (serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.LiveId || serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.OnlineFederation) { throw new Exception(String.Format("To run this sample, {0} {1} must be an active system user " + "\nin your Microsoft Dynamics CRM Online organization.", firstName, lastName)); } if (String.IsNullOrEmpty(ldapPath)) { ldapPath = SystemUserProvider.ConsolePromptForLDAPPath(); } // Create an Active Directory user account if it doesn't exist already. if (String.IsNullOrEmpty(ldapPath)) { throw new ArgumentException("Required argument ldapPath was not provided."); } DirectoryEntry directoryEntry; if (serviceProxy.ClientCredentials.Windows != null) { string LUser = serviceProxy.ClientCredentials.Windows.ClientCredential.UserName; string LPwd = serviceProxy.ClientCredentials.Windows.ClientCredential.Password; directoryEntry = new DirectoryEntry(ldapPath, LUser, LPwd); } else { directoryEntry = new DirectoryEntry(ldapPath); } DirectoryEntry userADAccount = null; // Search AD to see if the user already exists. DirectorySearcher search = new DirectorySearcher(directoryEntry); search.Filter = String.Format("(sAMAccountName={0})", userName); search.PropertiesToLoad.Add("samaccountname"); search.PropertiesToLoad.Add("givenname"); search.PropertiesToLoad.Add("sn"); search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); Boolean accountCreated = false; if (result == null) { // Create the Active Directory account. userADAccount = directoryEntry.Children.Add("CN= " + userName, "user"); userADAccount.Properties["samAccountName"].Value = userName; userADAccount.Properties["givenName"].Value = firstName; userADAccount.Properties["sn"].Value = lastName; userADAccount.CommitChanges(); accountCreated = true; } else { // Use the existing AD account. userADAccount = result.GetDirectoryEntry(); accountCreated = false; } // Set the password for the account. String password = "******"; userADAccount.Invoke("SetPassword", new object[] { password }); userADAccount.CommitChanges(); directoryEntry.Close(); userADAccount.Close(); // Enable the newly created Active Directory account. userADAccount.Properties["userAccountControl"].Value = (int)userADAccount.Properties["userAccountControl"].Value & ~0x2; userADAccount.CommitChanges(); // Wait 10 seconds for the AD account to propagate. Thread.Sleep(10000); return(accountCreated); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve the ldapPath String ldapPath = String.Empty; // Retrieve the sales team - 1 sales manager and 2 sales representatives. _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath); _salesRepresentativeIds = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); #endregion #region Create PhoneCall record and supporting account Account account = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(account)); account.Id = _accountId; // Create Guids for PhoneCalls _phoneCallId = Guid.NewGuid(); _phoneCall2Id = Guid.NewGuid(); // Create ActivityPartys for the phone calls' "From" field. ActivityParty activityParty = new ActivityParty() { PartyId = account.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9), }; ActivityParty activityPartyClosed = new ActivityParty() { PartyId = account.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCall2Id, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create an open phone call. PhoneCall phoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Sample Phone Call", DirectionCode = false, To = new ActivityParty[] { activityParty }, OwnerId = new EntityReference("systemuser", _salesRepresentativeIds[0]), ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the first phone call. SetStateRequest closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); // Create a second phone call. phoneCall = new PhoneCall() { Id = _phoneCall2Id, Subject = "Sample Phone Call 2", DirectionCode = true, To = new ActivityParty[] { activityParty }, OwnerId = new EntityReference("systemuser", _salesRepresentativeIds[1]), ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the second phone call. closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); #endregion }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve the ldapPath String ldapPath = String.Empty; // Retrieve the sales team - 1 sales manager and 2 sales representatives. _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath); _salesRepresentativeId = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath)[0]; #endregion #region Create records to support SalesOrder records // Create a unit group UoMSchedule newUnitGroup = new UoMSchedule { Name = "Example Unit Group", BaseUoMName = "Example Primary Unit" }; _unitGroupId = _serviceProxy.Create(newUnitGroup); // Retrieve the default unit id that was automatically created // when we created the Unit Group QueryExpression unitQuery = new QueryExpression { EntityName = UoM.EntityLogicalName, ColumnSet = new ColumnSet("uomid", "name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "uomscheduleid", Operator = ConditionOperator.Equal, Values = { _unitGroupId } } } }, PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; // Retrieve the unit. UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0]; _defaultUnitId = unit.UoMId.Value; // Create a few products Product newProduct = new Product { ProductNumber = "1", Name = "Example Product", ProductStructure = new OptionSetValue(1), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _productId = _serviceProxy.Create(newProduct); newProduct.Id = _productId; Console.WriteLine("Created {0}", newProduct.Name); // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Example Price List" }; _priceListId = _serviceProxy.Create(newPriceList); // Create a price list item for the first product and apply volume discount ProductPriceLevel newPriceListItem = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _productId), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(20), }; _priceListItemId = _serviceProxy.Create(newPriceListItem); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _productId), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("Published {0}", newProduct.Name); // Create an account record for the sales order's potential customerid Account newAccount = new Account { Name = "Litware, Inc.", Address1_PostalCode = "60661" }; _accountId = _serviceProxy.Create(newAccount); newAccount.Id = _accountId; #endregion Create records to support SalesOrder #region Create SalesOrder record // Create the sales order. SalesOrder order = new SalesOrder() { Name = "Faux Order", DateFulfilled = new DateTime(2010, 8, 1), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), FreightAmount = new Money(20.0M) }; _orderId = _serviceProxy.Create(order); order.Id = _orderId; // Add the product to the order with the price overriden with a // negative value. SalesOrderDetail orderDetail = new SalesOrderDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 4, SalesOrderId = order.ToEntityReference(), IsPriceOverridden = true, PricePerUnit = new Money(1000.0M), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _orderDetailId = _serviceProxy.Create(orderDetail); #endregion Create SalesOrder record }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve a sales manager. _salesManagerId = SystemUserProvider.RetrieveMarketingManager(_serviceProxy); #endregion #region Create PhoneCall record and supporting account Account newAccount = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(newAccount)); newAccount.Id = _accountId; // Create Guids for PhoneCalls _phoneCallId = Guid.NewGuid(); _phoneCall2Id = Guid.NewGuid(); // Create ActivityPartys for the phone calls' "From" field. ActivityParty activityParty = new ActivityParty() { PartyId = newAccount.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; ActivityParty activityPartyClosed = new ActivityParty() { PartyId = newAccount.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCall2Id, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create an open phone call. PhoneCall phoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Sample Phone Call", DirectionCode = false, To = new ActivityParty[] { activityParty } }; _serviceProxy.Create(phoneCall); // Create a second phone call to close phoneCall = new PhoneCall() { Id = _phoneCall2Id, Subject = "Sample Phone Call 2", DirectionCode = false, To = new ActivityParty[] { activityParty }, ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the second phone call. SetStateRequest closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); #endregion }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve the ldapPath String ldapPath = String.Empty; // Retrieve the sales team - 1 sales manager and 2 sales representatives. _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath); _salesRepresentativeIds = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); #endregion #region Create records to support Opportunity records // Create a unit group UoMSchedule newUnitGroup = new UoMSchedule { Name = "Example Unit Group", BaseUoMName = "Example Primary Unit" }; _unitGroupId = _serviceProxy.Create(newUnitGroup); // Retrieve the default unit id that was automatically created // when we created the Unit Group QueryExpression unitQuery = new QueryExpression { EntityName = UoM.EntityLogicalName, ColumnSet = new ColumnSet("uomid", "name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "uomscheduleid", Operator = ConditionOperator.Equal, Values = { _unitGroupId } } } }, PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; // Retrieve the unit. UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0]; _defaultUnitId = unit.UoMId.Value; // Create a few products Product newProduct1 = new Product { ProductNumber = "1", Name = "Example Product 1", ProductStructure = new OptionSetValue(1), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _product1Id = _serviceProxy.Create(newProduct1); Console.WriteLine("Created {0}", newProduct1.Name); Product newProduct2 = new Product { ProductNumber = "2", Name = "Example Product 2", ProductStructure = new OptionSetValue(1), QuantityDecimal = 3, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _product2Id = _serviceProxy.Create(newProduct2); Console.WriteLine("Created {0}", newProduct2.Name); // Create a new discount list DiscountType newDiscountType = new DiscountType { Name = "Example Discount List", IsAmountType = false }; _discountTypeId = _serviceProxy.Create(newDiscountType); // Create a new discount Discount newDiscount = new Discount { DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName, _discountTypeId), LowQuantity = 5, HighQuantity = 10, Percentage = 3 }; _discountId = _serviceProxy.Create(newDiscount); // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Example Price List" }; _priceListId = _serviceProxy.Create(newPriceList); // Create a price list item for the first product and apply volume discount ProductPriceLevel newPriceListItem1 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(20), DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName, _discountTypeId) }; _priceListItem1Id = _serviceProxy.Create(newPriceListItem1); // Create a price list item for the second product ProductPriceLevel newPriceListItem2 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product2Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(15) }; _priceListItem2Id = _serviceProxy.Create(newPriceListItem2); // Publish Product 1 SetStateRequest publishRequest1 = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product1Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest1); // Publish Product 2 SetStateRequest publishRequest2 = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest2); Console.WriteLine("Published {0} and {1}", newProduct1.Name, newProduct2.Name); // Create an account record for the opportunity's potential customerid Account newAccount = new Account { Name = "Litware, Inc.", Address1_PostalCode = "60661" }; _accountIds.Add(_serviceProxy.Create(newAccount)); newAccount = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountIds.Add(_serviceProxy.Create(newAccount)); #endregion Create records to support Opportunity records #region Create Opportunity records // Create a new opportunity with user specified estimated revenue Opportunity newOpportunity = new Opportunity { Name = "Example Opportunity", CustomerId = new EntityReference(Account.EntityLogicalName, _accountIds[0]), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), IsRevenueSystemCalculated = false, EstimatedValue = new Money(400.00m), FreightAmount = new Money(10.00m), DiscountAmount = new Money(0.10m), DiscountPercentage = 0.20m, ActualValue = new Money(400.00m), OwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName } }; _opportunityIds.Add(_serviceProxy.Create(newOpportunity)); Opportunity secondOpportunity = new Opportunity { Name = "Example Opportunity 2", CustomerId = new EntityReference(Account.EntityLogicalName, _accountIds[1]), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), IsRevenueSystemCalculated = false, EstimatedValue = new Money(400.00m), FreightAmount = new Money(10.00m), DiscountAmount = new Money(0.10m), DiscountPercentage = 0.20m, ActualValue = new Money(400.00m), OwnerId = new EntityReference { Id = _salesRepresentativeIds[1], LogicalName = SystemUser.EntityLogicalName } }; _opportunityIds.Add(_serviceProxy.Create(secondOpportunity)); // Create a catalog product OpportunityProduct catalogProduct = new OpportunityProduct { OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityIds[0]), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 8, Tax = new Money(12.42m), }; _catalogProductId = _serviceProxy.Create(catalogProduct); // Create another catalog product and override the list price OpportunityProduct catalogProductPriceOverride = new OpportunityProduct { OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityIds[1]), ProductId = new EntityReference(Product.EntityLogicalName, _product2Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 3, Tax = new Money(2.88m), IsPriceOverridden = true, PricePerUnit = new Money(12) }; _catalogProductPriceOverrideId = _serviceProxy.Create( catalogProductPriceOverride); // create a new write-in opportunity product with a manual discount applied OpportunityProduct writeInProduct = new OpportunityProduct { OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityIds[1]), IsProductOverridden = true, ProductDescription = "Example Write-in Product", PricePerUnit = new Money(20.00m), Quantity = 5, ManualDiscountAmount = new Money(10.50m), Tax = new Money(7.16m) }; _writeInProductId = _serviceProxy.Create(writeInProduct); // Close the opportunities as 'Won' WinOpportunityRequest winRequest = new WinOpportunityRequest() { OpportunityClose = new OpportunityClose() { OpportunityId = new EntityReference { Id = _opportunityIds[0], LogicalName = Opportunity.EntityLogicalName }, ActualRevenue = new Money(400.00M), ActualEnd = DateTime.Today }, Status = new OptionSetValue(3) }; _serviceProxy.Execute(winRequest); winRequest = new WinOpportunityRequest() { OpportunityClose = new OpportunityClose() { OpportunityId = new EntityReference { Id = _opportunityIds[1], LogicalName = Opportunity.EntityLogicalName }, ActualRevenue = new Money(400.00M), ActualEnd = DateTime.Today }, Status = new OptionSetValue(3) }; _serviceProxy.Execute(winRequest); #endregion Create Opportunity records }