Ejemplo n.º 1
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate creating all entity records that this sample requires.
        /// Create a product family with a product property and two child product records.
        /// Create a substitute relation between the two products.
        /// Override the product property for one of the child products.
        /// Publish the product family hierarchy, including the child records.
        /// Revise a child product to overwrite the overridden property.
        /// Publish the child product.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetCreateandublishProducts1>
                    // Create a product family
                    Product newProductFamily = new Product
                    {
                        Name             = "Example Product Family",
                        ProductNumber    = "PF001",
                        ProductStructure = new OptionSetValue(2)
                    };
                    _productFamilyId = _serviceProxy.Create(newProductFamily);
                    Console.WriteLine("\nCreated '{0}'", newProductFamily.Name);

                    // Create a product property
                    DynamicProperty newProperty = new DynamicProperty
                    {
                        Name = "Example Property",
                        RegardingObjectId = new EntityReference(Product.EntityLogicalName,
                                                                _productFamilyId),
                        IsReadOnly         = true,
                        IsRequired         = true,
                        IsHidden           = false,
                        DataType           = new OptionSetValue(3), //Single line of text
                        DefaultValueString = "Default Value"
                    };
                    _productPropertyId = _serviceProxy.Create(newProperty);
                    Console.WriteLine("\nCreated '{0}' for the product family", newProperty.Name);

                    // Create couple of product records under the product family
                    Product newProduct1 = new Product
                    {
                        Name                 = "Example Product 1",
                        ProductNumber        = "P001",
                        ProductStructure     = new OptionSetValue(1),
                        ParentProductId      = new EntityReference(Product.EntityLogicalName, _productFamilyId),
                        QuantityDecimal      = 2,
                        DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
                        DefaultUoMId         = new EntityReference(UoM.EntityLogicalName, _unit.Id)
                    };
                    _product1Id = _serviceProxy.Create(newProduct1);

                    Console.WriteLine("\nCreated '{0}' under the product family", newProduct1.Name);

                    Product newProduct2 = new Product
                    {
                        Name                 = "Example Product 2",
                        ProductNumber        = "P002",
                        ProductStructure     = new OptionSetValue(1),
                        ParentProductId      = new EntityReference(Product.EntityLogicalName, _productFamilyId),
                        QuantityDecimal      = 2,
                        DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
                        DefaultUoMId         = new EntityReference(UoM.EntityLogicalName, _unit.Id)
                    };
                    _product2Id = _serviceProxy.Create(newProduct2);

                    Console.WriteLine("Created '{0}' under the product family", newProduct2.Name);



                    // Create a price list items for the products
                    ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
                    {
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                        ProductId    = new EntityReference(Product.EntityLogicalName, _product1Id),
                        UoMId        = new EntityReference(UoM.EntityLogicalName, _unit.Id),
                        Amount       = new Money(20)
                    };
                    _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);

                    Console.WriteLine("\nCreated price list for '{0}'", newProduct1.Name);

                    ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
                    {
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                        ProductId    = new EntityReference(Product.EntityLogicalName, _product2Id),
                        UoMId        = new EntityReference(UoM.EntityLogicalName, _unit.Id),
                        Amount       = new Money(20)
                    };
                    _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);

                    Console.WriteLine("Created price list for '{0}'", newProduct2.Name);

                    // Set the product relationship
                    // Set Example Product 1 and Example Product 2 as substitute of each other (bi-directional)
                    ProductSubstitute newProductRelation = new ProductSubstitute
                    {
                        SalesRelationshipType = new OptionSetValue(3),
                        Direction             = new OptionSetValue(1),
                        ProductId             = new EntityReference(Product.EntityLogicalName, _product1Id),
                        SubstitutedProductId  = new EntityReference(Product.EntityLogicalName, _product2Id)
                    };
                    _productRelationId = _serviceProxy.Create(newProductRelation);

                    Console.WriteLine("\nCreated a substitute relation between the two products.");
                    //</snippetCreateandublishProducts1>

                    // Override a product property at the product level
                    // In this case we will override the property for 'Example Product 1'
                    DynamicProperty newOverrideProperty = new DynamicProperty();
                    newOverrideProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName,
                                                                                    _productPropertyId);
                    newOverrideProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName, _product1Id);
                    _productOverridenPropertyId           = _serviceProxy.Create(newOverrideProperty);

                    // Retrieve the attributes of the cloned property you want to update
                    ColumnSet columns = new ColumnSet();
                    columns.AddColumns("name", "isreadonly", "isrequired");
                    DynamicProperty retrievedOverridenProperty = (DynamicProperty)_serviceProxy.Retrieve(
                        DynamicProperty.EntityLogicalName, _productOverridenPropertyId,
                        columns);

                    // Update the attributes
                    retrievedOverridenProperty.Name       = "Overridden Example Property";
                    retrievedOverridenProperty.IsReadOnly = true;
                    retrievedOverridenProperty.IsRequired = false;
                    _serviceProxy.Update(retrievedOverridenProperty);
                    Console.WriteLine("\nOverridden the product property for 'Example Product 1'.");

                    // Prompt the user whether to publish the product family and products
                    bool publishRecords = true;
                    Console.WriteLine("\nDo you want the product records published? (y/n)");
                    String answer = Console.ReadLine();
                    publishRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));

                    if (publishRecords)
                    {
                        PublishProductHierarchyRequest publishReq = new PublishProductHierarchyRequest
                        {
                            Target = new EntityReference(Product.EntityLogicalName, _productFamilyId)
                        };
                        PublishProductHierarchyResponse published = (PublishProductHierarchyResponse)_serviceProxy.Execute(publishReq);
                        if (published.Results != null)
                        {
                            Console.WriteLine("Published the product records");
                        }

                        // Overwrite a product property
                        Console.WriteLine("\nRevising 'Example Product 1' to demonstrate product property overwrite.");

                        // Retrieve the StateCode of Product that you want to revise
                        ColumnSet cols = new ColumnSet();
                        cols.AddColumns("name", "statecode");
                        Product retrievedPublishedProduct = (Product)_serviceProxy.Retrieve(
                            Product.EntityLogicalName, _product1Id,
                            cols);

                        // Update the state of the Product to "Under Revision"
                        retrievedPublishedProduct.StateCode = ProductState.UnderRevision;
                        UpdateRequest updatePropertyState = new UpdateRequest
                        {
                            Target = retrievedPublishedProduct
                        };
                        _serviceProxy.Execute(updatePropertyState);
                        Console.WriteLine("\nChanged '{0}' to 'Under Revision' state.", retrievedPublishedProduct.Name);

                        DynamicProperty newOverwriteProperty = new DynamicProperty();
                        newOverwriteProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName,
                                                                                         _productOverridenPropertyId);
                        newOverwriteProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName,
                                                                                     _product1Id);
                        _productOverwrittenPropertyId = _serviceProxy.Create(newOverwriteProperty);

                        // Retrieve the attributes of the cloned property you want to update
                        ColumnSet myCols = new ColumnSet();
                        myCols.AddColumns("name", "isreadonly", "isrequired");
                        DynamicProperty retrievedOverwrittenProperty = (DynamicProperty)_serviceProxy.Retrieve(
                            DynamicProperty.EntityLogicalName, _productOverwrittenPropertyId,
                            myCols);


                        // Update the attributes of the cloned property to complete the overwrite
                        retrievedOverwrittenProperty.Name       = "Overwritten Example Property";
                        retrievedOverwrittenProperty.IsReadOnly = true;
                        retrievedOverridenProperty.IsRequired   = false;
                        _serviceProxy.Update(retrievedOverwrittenProperty);
                        Console.WriteLine("\nOverwritten the product property for 'Example Product 1'.");

                        // Retrieve the StateCode of Product that you want to publish
                        ColumnSet prodCols = new ColumnSet();
                        prodCols.AddColumns("name", "statecode");
                        Product retrievedRevisedProduct = (Product)_serviceProxy.Retrieve(
                            Product.EntityLogicalName, _product1Id,
                            prodCols);

                        // Update the state of the Product to "Active"
                        retrievedRevisedProduct.StateCode = ProductState.Active;
                        UpdateRequest publishProduct1 = new UpdateRequest
                        {
                            Target = retrievedRevisedProduct
                        };
                        _serviceProxy.Execute(publishProduct1);
                        Console.WriteLine("\nPublished '{0}'.", retrievedRevisedProduct.Name);
                    }

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            catch
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Create a view.
        /// Retrieve Views
        /// Deactivate a view
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        /// <param name="promptForReactivate">When True, the user will be prompted to reactivate
        /// a view that was deactivated.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete, bool promptForReactivate)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Create the view.
                    //<snippetWorkWithViews1>
                    System.String layoutXml =
                        @"<grid name='resultset' object='3' jump='name' select='1' 
    preview='1' icon='1'>
    <row name='result' id='opportunityid'>
    <cell name='name' width='150' /> 
    <cell name='customerid' width='150' /> 
    <cell name='estimatedclosedate' width='150' /> 
    <cell name='estimatedvalue' width='150' /> 
    <cell name='closeprobability' width='150' /> 
    <cell name='opportunityratingcode' width='150' /> 
    <cell name='opportunitycustomeridcontactcontactid.emailaddress1' 
        width='150' disableSorting='1' /> 
    </row>
</grid>";

                    System.String fetchXml =
                        @"<fetch version='1.0' output-format='xml-platform' 
    mapping='logical' distinct='false'>
    <entity name='opportunity'>
    <order attribute='estimatedvalue' descending='false' /> 
    <filter type='and'>
        <condition attribute='statecode' operator='eq' 
        value='0' /> 
    </filter>
    <attribute name='name' /> 
    <attribute name='estimatedvalue' /> 
    <attribute name='estimatedclosedate' /> 
    <attribute name='customerid' /> 
    <attribute name='opportunityratingcode' /> 
    <attribute name='closeprobability' /> 
    <link-entity alias='opportunitycustomeridcontactcontactid' 
        name='contact' from='contactid' to='customerid' 
        link-type='outer' visible='false'>
        <attribute name='emailaddress1' /> 
    </link-entity>
    <attribute name='opportunityid' /> 
    </entity>
</fetch>";

                    SavedQuery sq = new SavedQuery
                    {
                        Name             = "A New Custom Public View",
                        Description      = "A Saved Query created in code",
                        ReturnedTypeCode = "opportunity",
                        FetchXml         = fetchXml,
                        LayoutXml        = layoutXml,
                        QueryType        = 0
                    };

                    _customViewId = _serviceProxy.Create(sq);
                    Console.WriteLine("A new view with the name {0} was created.", sq.Name);
                    //</snippetWorkWithViews1>


                    // Retrieve Views
                    //<snippetWorkWithViews2>
                    QueryExpression mySavedQuery = new QueryExpression
                    {
                        ColumnSet  = new ColumnSet("savedqueryid", "name", "querytype", "isdefault", "returnedtypecode", "isquickfindquery"),
                        EntityName = SavedQuery.EntityLogicalName,
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "querytype",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = {      0 }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "returnedtypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Opportunity.EntityTypeCode }
                                }
                            }
                        }
                    };
                    RetrieveMultipleRequest retrieveSavedQueriesRequest = new RetrieveMultipleRequest {
                        Query = mySavedQuery
                    };

                    RetrieveMultipleResponse retrieveSavedQueriesResponse = (RetrieveMultipleResponse)_serviceProxy.Execute(retrieveSavedQueriesRequest);

                    DataCollection <Entity> savedQueries = retrieveSavedQueriesResponse.EntityCollection.Entities;

                    //Display the Retrieved views
                    foreach (Entity ent in savedQueries)
                    {
                        SavedQuery rsq = (SavedQuery)ent;
                        Console.WriteLine("{0} : {1} : {2} : {3} : {4} : {5},", rsq.SavedQueryId, rsq.Name, rsq.QueryType, rsq.IsDefault, rsq.ReturnedTypeCode, rsq.IsQuickFindQuery);
                    }
                    //</snippetWorkWithViews2>

                    // Deactivate a view
                    //<snippetWorkWithViews3>
                    System.String   SavedQueryName = "Closed Opportunities in Current Fiscal Year";
                    QueryExpression ClosedOpportunitiesViewQuery = new QueryExpression
                    {
                        ColumnSet  = new ColumnSet("savedqueryid", "statecode", "statuscode"),
                        EntityName = SavedQuery.EntityLogicalName,
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "querytype",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = {      0 }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "returnedtypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Opportunity.EntityTypeCode }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "name",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { SavedQueryName }
                                }
                            }
                        }
                    };

                    RetrieveMultipleRequest retrieveOpportuntiesViewRequest = new RetrieveMultipleRequest {
                        Query = ClosedOpportunitiesViewQuery
                    };

                    RetrieveMultipleResponse retrieveOpportuntiesViewResponse = (RetrieveMultipleResponse)_serviceProxy.Execute(retrieveOpportuntiesViewRequest);

                    SavedQuery OpportunityView = (SavedQuery)retrieveOpportuntiesViewResponse.EntityCollection.Entities[0];
                    _viewOriginalState  = (SavedQueryState)OpportunityView.StateCode;
                    _viewOriginalStatus = OpportunityView.StatusCode;


                    SetStateRequest ssreq = new SetStateRequest
                    {
                        EntityMoniker = new EntityReference(SavedQuery.EntityLogicalName, (Guid)OpportunityView.SavedQueryId),
                        State         = new OptionSetValue((int)SavedQueryState.Inactive),
                        Status        = new OptionSetValue(2)
                    };
                    _serviceProxy.Execute(ssreq);
                    //</snippetWorkWithViews3>
                    _deactivatedViewId = (Guid)OpportunityView.SavedQueryId;


                    DeleteRequiredRecords(promptForDelete);
                    ReactivateDeactivatedView(promptForReactivate);
                }
            }

            // 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;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create a parent account record and subsequent 10 child account records.
        /// Retrieve batch of records using RetrieveMultiple message with paging cookie.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetFetchPagingWithCookie1>
                    // Define the fetch attributes.
                    // Set the number of records per page to retrieve.
                    int fetchCount = 3;
                    // Initialize the page number.
                    int pageNumber = 1;
                    // Initialize the number of records.
                    int recordCount = 0;
                    // Specify the current paging cookie. For retrieving the first page,
                    // pagingCookie should be null.
                    string pagingCookie = null;

                    // Create the FetchXml string for retrieving all child accounts to a parent account.
                    // This fetch query is using 1 placeholder to specify the parent account id
                    // for filtering out required accounts. Filter query is optional.
                    // Fetch query also includes optional order criteria that, in this case, is used
                    // to order the results in ascending order on the name data column.
                    string fetchXml = string.Format(@"<fetch version='1.0' 
                                                    mapping='logical' 
                                                    output-format='xml-platform'>
                                                    <entity name='account'>
                                                        <attribute name='name' />
                                                        <attribute name='emailaddress1' />
                                                        <order attribute='name' descending='false'/>
                                                        <filter type='and'>
				                                            <condition attribute='parentaccountid' 
                                                                operator='eq' value='{0}' uiname='' uitype='' />
                                                        </filter>
                                                    </entity>
                                                </fetch>",
                                                    _parentAccountId);

                    Console.WriteLine("Retrieving data in pages\n");
                    Console.WriteLine("#\tAccount Name\t\t\tEmail Address");

                    while (true)
                    {
                        // Build fetchXml string with the placeholders.
                        string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);

                        // Excute the fetch query and get the xml result.
                        RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
                        {
                            Query = new FetchExpression(xml)
                        };

                        EntityCollection returnCollection = ((RetrieveMultipleResponse)_service.Execute(fetchRequest1)).EntityCollection;

                        foreach (var c in returnCollection.Entities)
                        {
                            System.Console.WriteLine("{0}.\t{1}\t\t{2}", ++recordCount, c.Attributes["name"], c.Attributes["emailaddress1"]);
                        }

                        // Check for morerecords, if it returns 1.
                        if (returnCollection.MoreRecords)
                        {
                            Console.WriteLine("\n****************\nPage number {0}\n****************", pageNumber);
                            Console.WriteLine("#\tAccount Name\t\t\tEmail Address");

                            // Increment the page number to retrieve the next page.
                            pageNumber++;

                            // Set the paging cookie to the paging cookie returned from current results.
                            pagingCookie = returnCollection.PagingCookie;
                        }
                        else
                        {
                            // If no more records in the result nodes, exit the loop.
                            break;
                        }
                    }
                    //</snippetFetchPagingWithCookie1>

                    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;
            }
            return;
        }
        /// <summary>
        /// Create an e-mail activity instance from the specified e-mail message.
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        /// </summary>
        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 = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Create a contact to send an email to (To: field)
                    Contact emailContact = new Contact()
                    {
                        FirstName     = "Lisa",
                        LastName      = "Andrews",
                        EMailAddress1 = "*****@*****.**"
                    };
                    _contactId = _serviceProxy.Create(emailContact);
                    Console.WriteLine("Created a sample contact.");

                    // Get a system user to send the email (From: field)
                    WhoAmIRequest  systemUserRequest  = new WhoAmIRequest();
                    WhoAmIResponse systemUserResponse = (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);

                    ColumnSet  cols        = new ColumnSet("internalemailaddress");
                    SystemUser emailSender = (SystemUser)_serviceProxy.Retrieve(SystemUser.EntityLogicalName, systemUserResponse.UserId, cols);

                    //<snippetDeliverPromoteEmail1>

                    // Create the request.
                    DeliverPromoteEmailRequest deliverEmailRequest = new DeliverPromoteEmailRequest
                    {
                        Subject     = "SDK Sample Email",
                        To          = emailContact.EMailAddress1,
                        From        = emailSender.InternalEMailAddress,
                        Bcc         = String.Empty,
                        Cc          = String.Empty,
                        Importance  = "high",
                        Body        = "This message will create an email activity.",
                        MessageId   = Guid.NewGuid().ToString(),
                        SubmittedBy = "",
                        ReceivedOn  = DateTime.Now
                    };

                    // We won't attach a file to the email, but the Attachments property is required.
                    deliverEmailRequest.Attachments            = new EntityCollection(new ActivityMimeAttachment[0]);
                    deliverEmailRequest.Attachments.EntityName = ActivityMimeAttachment.EntityLogicalName;

                    // Execute the request.
                    DeliverPromoteEmailResponse deliverEmailResponse = (DeliverPromoteEmailResponse)_serviceProxy.Execute(deliverEmailRequest);

                    // Verify the success.

                    // Define an anonymous type to define the possible values for
                    // email status
                    var EmailStatus = new
                    {
                        Draft       = 1,
                        Completed   = 2,
                        Sent        = 3,
                        Received    = 3,
                        Canceled    = 5,
                        PendingSend = 6,
                        Sending     = 7,
                        Failed      = 8,
                    };

                    // Query for the delivered email, and verify the status code is "Sent".
                    ColumnSet deliveredMailColumns = new ColumnSet("statuscode");
                    Email     deliveredEmail       = (Email)_serviceProxy.Retrieve(Email.EntityLogicalName, deliverEmailResponse.EmailId, deliveredMailColumns);

                    _emailId = deliveredEmail.ActivityId.Value;

                    if (deliveredEmail.StatusCode.Value == EmailStatus.Sent)
                    {
                        Console.WriteLine("Successfully created and delivered the e-mail message.");
                    }

                    //</snippetDeliverPromoteEmail1>

                    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;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// This method connects to the Organization _service.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>

        public void Run(ServerConnection.Configuration serverConfig)
        {
            try
            {
                // Connect to the Organization _service.
                // The using statement assures that the _service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    _userId       = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
                    _languageCode = RetrieveUserUILanguageCode(_userId);



                    //A filter expression to limit entities returned to non-intersect entities
                    MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);
                    EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false));


                    //A properties expression to limit the properties to be included with entities
                    MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
                    {
                        AllProperties = false
                    };
                    EntityProperties.PropertyNames.AddRange(new string[] { "OneToManyRelationships", "LogicalName", "DisplayName" });



                    //A filter expression to only return system entity relationships
                    MetadataFilterExpression relationshipFilter = new MetadataFilterExpression(LogicalOperator.And);
                    relationshipFilter.Conditions.Add(new MetadataConditionExpression("IsCustomRelationship", MetadataConditionOperator.Equals, false));

                    //A Properties expression to limit the properties to be included with relationships
                    MetadataPropertiesExpression relationshipProperties = new MetadataPropertiesExpression()
                    {
                        AllProperties = false
                    };
                    relationshipProperties.PropertyNames.Add("CascadeConfiguration");
                    relationshipProperties.PropertyNames.Add("SchemaName");
                    relationshipProperties.PropertyNames.Add("IsCustomizable");


                    //A label query expression to limit the labels returned to only those for the user's preferred language
                    LabelQueryExpression labelQuery = new LabelQueryExpression();
                    labelQuery.FilterLanguages.Add(_languageCode);


                    //An entity query expression to combine the filter expressions and property expressions for the query.
                    EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
                    {
                        Criteria          = EntityFilter,
                        Properties        = EntityProperties,
                        RelationshipQuery = new RelationshipQueryExpression()
                        {
                            Criteria = relationshipFilter, Properties = relationshipProperties
                        },
                        LabelQuery = labelQuery
                    };

                    //Define the request
                    RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest()
                    {
                        Query = entityQueryExpression
                    };

                    //Retrieve the data
                    RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_service.Execute(request);


                    //Process the data
                    foreach (EntityMetadata entity in response.EntityMetadata)
                    {
                        if (entity.OneToManyRelationships != null)
                        {
                            foreach (OneToManyRelationshipMetadata relationship in entity.OneToManyRelationships)
                            {
                                var cascadeConfig = relationship.CascadeConfiguration;
                                //When all of the CascadeConfiguration properties use the Cascade behavior the relationship is considered parental
                                if (cascadeConfig.Assign == CascadeType.Cascade &&
                                    cascadeConfig.Delete == CascadeType.Cascade &&
                                    cascadeConfig.Merge == CascadeType.Cascade &&
                                    cascadeConfig.Reparent == CascadeType.Cascade &&
                                    cascadeConfig.Share == CascadeType.Cascade &&
                                    cascadeConfig.Unshare == CascadeType.Cascade)
                                {
                                    //Only show results for relationships that can be customized
                                    if (relationship.IsCustomizable.Value)
                                    {
                                        //Write the entity name and the name of the relationship.
                                        Console.WriteLine(entity.DisplayName.UserLocalizedLabel.Label + "," + relationship.SchemaName);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 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;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// records are retrieved from the systemuserroles intersect table via three
        /// methods: Query Expression, Fetch, and LINQ.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();
                    //<snippetRetrieveRecordsFromAnIntersectTable1>
                    #region Retrieve records from an intersect table via QueryExpression

                    //Create Query Expression.
                    QueryExpression query = new QueryExpression()
                    {
                        EntityName   = "role",
                        ColumnSet    = new ColumnSet("name"),
                        LinkEntities =
                        {
                            new LinkEntity
                            {
                                LinkFromEntityName    = Role.EntityLogicalName,
                                LinkFromAttributeName = "roleid",
                                LinkToEntityName      = SystemUserRoles.EntityLogicalName,
                                LinkToAttributeName   = "roleid",
                                LinkCriteria          = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions     =
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = "systemuserid",
                                            Operator      = ConditionOperator.Equal,
                                            Values        = { _userId }
                                        }
                                    }
                                }
                            }
                        }
                    };

                    // Obtain results from the query expression.
                    EntityCollection ec = _serviceProxy.RetrieveMultiple(query);

                    // Display results.
                    for (int i = 0; i < ec.Entities.Count; i++)
                    {
                        Console.WriteLine("Query Expression Retrieved: {0}", ((Role)ec.Entities[i]).Name);
                    }

                    #endregion
                    //</snippetRetrieveRecordsFromAnIntersectTable1>
                    //<snippetRetrieveRecordsFromAnIntersectTable2>
                    #region Retrieve records from an intersect table via Fetch

                    // Setup Fetch XML.
                    StringBuilder linkFetch = new StringBuilder();
                    linkFetch.Append("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"true\">");
                    linkFetch.Append("<entity name=\"role\">");
                    linkFetch.Append("<attribute name=\"name\"/>");
                    linkFetch.Append("<link-entity name=\"systemuserroles\" from=\"roleid\" to=\"roleid\" visible=\"false\" intersect=\"true\">");
                    linkFetch.Append("<filter type=\"and\">");
                    linkFetch.Append("<condition attribute=\"systemuserid\" operator=\"eq\" value=\"" + _userId + "\"/>");
                    linkFetch.Append("</filter>");
                    linkFetch.Append("</link-entity>");
                    linkFetch.Append("</entity>");
                    linkFetch.Append("</fetch>");

                    // Build fetch request and obtain results.
                    RetrieveMultipleRequest efr = new RetrieveMultipleRequest()
                    {
                        Query = new FetchExpression(linkFetch.ToString())
                    };
                    EntityCollection entityResults = ((RetrieveMultipleResponse)_serviceProxy.Execute(efr)).EntityCollection;

                    // Display results.
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Fetch Retrieved: {0}", e.Attributes["name"]);
                    }

                    #endregion
                    //</snippetRetrieveRecordsFromAnIntersectTable2>
                    //<snippetRetrieveRecordsFromAnIntersectTable3>
                    #region Retrieve records from an intersect table via LINQ

                    // Obtain the Organization Context.
                    OrganizationServiceContext context = new OrganizationServiceContext(_serviceProxy);

                    // Create Linq Query.
                    var roles = (from r in context.CreateQuery <Role>()
                                 join s in context.CreateQuery <SystemUserRoles>() on r.RoleId equals s.RoleId
                                 where s.SystemUserId == _userId
                                 orderby r.RoleId
                                 select r.Name);

                    // Display results.
                    foreach (var role in roles)
                    {
                        Console.WriteLine("Linq Retrieved: {0}", role);
                    }

                    #endregion
                    //</snippetRetrieveRecordsFromAnIntersectTable3>
                    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;
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// This method connects to the Organization service using an impersonated user
        /// credential. Afterwards, basic create, retrieve, update, and delete entity
        /// operations are performed as the impersonated user.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete
        /// all created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetImpersonateWithOnBehalfOfPrivilege1>
                //<snippetImpersonateWithOnBehalfOfPrivilege2>
                // Connect to the Organization service.
                // The using statement ensures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // Retrieve the system user ID of the user to impersonate.
                    OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy);
                    _userId = (from user in orgContext.CreateQuery <SystemUser>()
                               where user.FullName == "Kevin Cook"
                               select user.SystemUserId.Value).FirstOrDefault();

                    // To impersonate another user, set the OrganizationServiceProxy.CallerId
                    // property to the ID of the other user.
                    _serviceProxy.CallerId = _userId;

                    // Instantiate an account object.
                    // See the Entity Metadata topic in the SDK documentation to determine
                    // which attributes must be set for each entity.
                    Account account = new Account {
                        Name = "Fourth Coffee"
                    };

                    // Create an account record named Fourth Coffee.
                    _accountId = _serviceProxy.Create(account);
                    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);
                    //</snippetImpersonateWithOnBehalfOfPrivilege2>

                    // Retrieve the account containing several of its attributes.
                    // CreatedBy should reference the impersonated SystemUser.
                    // CreatedOnBehalfBy should reference the running SystemUser.
                    ColumnSet cols = new ColumnSet(
                        "name",
                        "createdby",
                        "createdonbehalfby",
                        "address1_postalcode",
                        "lastusedincampaign");

                    Account retrievedAccount =
                        (Account)_serviceProxy.Retrieve(Account.EntityLogicalName,
                                                        _accountId, cols);
                    Console.Write("retrieved, ");

                    // Update the postal code attribute.
                    retrievedAccount.Address1_PostalCode = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    retrievedAccount.Address2_PostalCode = null;

                    // Shows use of a Money value.
                    retrievedAccount.Revenue = new Money(5000000);

                    // Shows use of a boolean value.
                    retrievedAccount.CreditOnHold = false;

                    // Update the account record.
                    _serviceProxy.Update(retrievedAccount);
                    Console.Write("updated, ");

                    // Delete the account record.
                    _serviceProxy.Delete(Account.EntityLogicalName, _accountId);
                    Console.WriteLine("and deleted.");

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

            // 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;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Demonstrates how to use the Deployment Web Service to create an organization
        /// and poll the status of the job.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete
        /// all created entities.</param>

        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords(serverConfig, promptforDelete);

                    //<snippetUseAsyncDeploymentServiceMessages1>
                    // Instantiate DeploymentServiceClient for calling the service.
                    client =
                        ProxyClientHelper.CreateClient(
                            new Uri(serverConfig.DiscoveryUri.ToString()
                                    .Replace("Services", "Deployment")
                                    .Replace("Discovery", "Deployment")));

                    // Setting credentials from the current security context.
                    if (serverConfig.Credentials == null)
                    {
                        client.ClientCredentials.Windows.ClientCredential =
                            CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        client.ClientCredentials.Windows.ClientCredential =
                            serverConfig.Credentials.Windows.ClientCredential;
                    }

                    using (client)
                    {
                        // Set properties for the new organization
                        Microsoft.Xrm.Sdk.Deployment.Organization organization =
                            new Microsoft.Xrm.Sdk.Deployment.Organization
                        {
                            BaseCurrencyCode      = "USD",
                            BaseCurrencyName      = "US Dollar",
                            BaseCurrencyPrecision = 2,
                            BaseCurrencySymbol    = "$",
                            BaseLanguageCode      = 1033,
                            FriendlyName          = _friendlyName,
                            UniqueName            = _uniqueName,
                            SqlCollation          = "Latin1_General_CI_AI",
                            SqlServerName         = _sqlServerName,
                            SrsUrl       = _srsUrl,
                            SqmIsEnabled = false
                        };

                        // Create a request for the deployment web service
                        // CRM server app pool must have permissions on SQL server
                        BeginCreateOrganizationRequest request =
                            new BeginCreateOrganizationRequest
                        {
                            Organization = organization,
                            SysAdminName = _sysAdminName
                        };

                        // Execute the request
                        BeginCreateOrganizationResponse response =
                            (BeginCreateOrganizationResponse)client.Execute(request);

                        // The operation is asynchronous, so the response object contains
                        // a unique identifier for the operation
                        Guid operationId = response.OperationId;

                        // Retrieve the Operation using the OperationId
                        RetrieveRequest retrieveOperationStatus = new RetrieveRequest();
                        retrieveOperationStatus.EntityType =
                            DeploymentEntityType.DeferredOperationStatus;
                        retrieveOperationStatus.InstanceTag =
                            new EntityInstanceId {
                            Id = operationId
                        };

                        RetrieveResponse        retrieveResponse;
                        DeferredOperationStatus deferredOperationStatus;

                        Console.WriteLine("Retrieving state of the job...");

                        // Retrieve the Operation State until Organization is created
                        do
                        {
                            // Wait 3 secs to not overload server
                            Thread.Sleep(3000);

                            retrieveResponse =
                                (RetrieveResponse)client.Execute(retrieveOperationStatus);

                            deferredOperationStatus =
                                ((DeferredOperationStatus)retrieveResponse.Entity);
                        }while (deferredOperationStatus.State !=
                                DeferredOperationState.Processing &&
                                deferredOperationStatus.State !=
                                DeferredOperationState.Completed);

                        // Poll OrganizationStatusRequest
                        RetrieveRequest retrieveReqServer = new RetrieveRequest();
                        retrieveReqServer.EntityType       = DeploymentEntityType.Organization;
                        retrieveReqServer.InstanceTag      = new EntityInstanceId();
                        retrieveReqServer.InstanceTag.Name = organization.UniqueName;

                        RetrieveResponse  retrieveRespServer;
                        OrganizationState orgState;

                        Console.WriteLine("Retrieving state of the organization...");

                        // Retrieve and check the Organization State until is enabled
                        do
                        {
                            retrieveRespServer =
                                (RetrieveResponse)client.Execute(retrieveReqServer);
                            _organizationID =
                                ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).Id;
                            orgState =
                                ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).State;

                            // Wait 5 secs to not overload server
                            Thread.Sleep(5000);
                        }while (orgState != OrganizationState.Enabled);

                        Console.WriteLine("Organization has been created!");

                        //</snippetUseAsyncDeploymentServiceMessages1>
                        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;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// creates/retrieves a system user,
        /// updates the system user to associate with the salesperson role.
        /// Note: Creating a user is only supported
        /// in an on-premises/active directory environment.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user is prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetAddRoleToUser1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy is properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // 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>();

                        Console.WriteLine("Role {0} is retrieved for the role assignment.", _givenRole);

                        _roleId = salesRole.Id;

                        // Associate the user with the role.
                        if (_roleId != Guid.Empty && _userId != Guid.Empty)
                        {
                            _serviceProxy.Associate(
                                "systemuser",
                                _userId,
                                new Relationship("systemuserroles_association"),
                                new EntityReferenceCollection()
                            {
                                new EntityReference(Role.EntityLogicalName, _roleId)
                            });

                            Console.WriteLine("Role is associated with the user.");
                        }
                    }

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

                    CreateRequiredRecords();

                    OrganizationServiceContext orgContext =
                        new OrganizationServiceContext(_serviceProxy);

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

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

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

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

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

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

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

Sincerely,
Mary Kay Andersen

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

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

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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Shows how to detect dependencies that may cause a managed solution to become
        /// un-deletable.
        ///
        /// Get all solution components of a solution
        /// For each solution component, list the dependencies upon that component.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();
                    //<snippetGetSolutionDependencies1>

                    // Grab all Solution Components for a solution.
                    QueryByAttribute componentQuery = new QueryByAttribute
                    {
                        EntityName = SolutionComponent.EntityLogicalName,
                        ColumnSet  = new ColumnSet("componenttype", "objectid", "solutioncomponentid", "solutionid"),
                        Attributes = { "solutionid" },

                        // In your code, this value would probably come from another query.
                        Values = { _primarySolutionId }
                    };

                    IEnumerable <SolutionComponent> allComponents =
                        _serviceProxy.RetrieveMultiple(componentQuery).Entities.Cast <SolutionComponent>();

                    foreach (SolutionComponent component in allComponents)
                    {
                        // For each solution component, retrieve all dependencies for the component.
                        RetrieveDependentComponentsRequest dependentComponentsRequest =
                            new RetrieveDependentComponentsRequest
                        {
                            ComponentType = component.ComponentType.Value,
                            ObjectId      = component.ObjectId.Value
                        };
                        RetrieveDependentComponentsResponse dependentComponentsResponse =
                            (RetrieveDependentComponentsResponse)_serviceProxy.Execute(dependentComponentsRequest);

                        // If there are no dependent components, we can ignore this component.
                        if (dependentComponentsResponse.EntityCollection.Entities.Any() == false)
                        {
                            continue;
                        }

                        // If there are dependencies upon this solution component, and the solution
                        // itself is managed, then you will be unable to delete the solution.
                        Console.WriteLine("Found {0} dependencies for Component {1} of type {2}",
                                          dependentComponentsResponse.EntityCollection.Entities.Count,
                                          component.ObjectId.Value,
                                          component.ComponentType.Value
                                          );
                        //A more complete report requires more code
                        foreach (Dependency d in dependentComponentsResponse.EntityCollection.Entities)
                        {
                            DependencyReport(d);
                        }
                    }
                    //</snippetGetSolutionDependencies1>

                    //Find out if any dependencies on a  specific global option set would prevent it from being deleted
                    //<snippetGetSolutionDependencies8>
                    // Use the RetrieveOptionSetRequest message to retrieve
                    // a global option set by it's name.
                    RetrieveOptionSetRequest retrieveOptionSetRequest =
                        new RetrieveOptionSetRequest
                    {
                        Name = _globalOptionSetName
                    };

                    // Execute the request.
                    RetrieveOptionSetResponse retrieveOptionSetResponse =
                        (RetrieveOptionSetResponse)_serviceProxy.Execute(
                            retrieveOptionSetRequest);
                    _globalOptionSetId = retrieveOptionSetResponse.OptionSetMetadata.MetadataId;
                    if (_globalOptionSetId != null)
                    {
                        //Use the global OptionSet MetadataId with the appropriate componenttype
                        // to call RetrieveDependenciesForDeleteRequest
                        RetrieveDependenciesForDeleteRequest retrieveDependenciesForDeleteRequest = new RetrieveDependenciesForDeleteRequest
                        {
                            ComponentType = (int)componenttype.OptionSet,
                            ObjectId      = (Guid)_globalOptionSetId
                        };

                        RetrieveDependenciesForDeleteResponse retrieveDependenciesForDeleteResponse =
                            (RetrieveDependenciesForDeleteResponse)_serviceProxy.Execute(retrieveDependenciesForDeleteRequest);
                        Console.WriteLine("");
                        foreach (Dependency d in retrieveDependenciesForDeleteResponse.EntityCollection.Entities)
                        {
                            if (d.DependentComponentType.Value == 2)//Just testing for Attributes
                            {
                                String attributeLabel = "";
                                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
                                {
                                    MetadataId = (Guid)d.DependentComponentObjectId
                                };
                                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveAttributeRequest);

                                AttributeMetadata attmet = retrieveAttributeResponse.AttributeMetadata;

                                attributeLabel = attmet.DisplayName.UserLocalizedLabel.Label;

                                Console.WriteLine("An {0} named {1} will prevent deleting the {2} global option set.",
                                                  (componenttype)d.DependentComponentType.Value,
                                                  attributeLabel,
                                                  _globalOptionSetName);
                            }
                        }
                    }

                    //</snippetGetSolutionDependencies8>

                    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;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create a parent account record and subsequent 10 child account records.
        /// Retrieve batch of records using RetrieveMultiple message with paging cookie.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetQueryExpressionPagingWithCookie1>
                    // Query using the paging cookie.
                    // Define the paging attributes.
                    // The number of records per page to retrieve.
                    int queryCount = 3;

                    // Initialize the page number.
                    int pageNumber = 1;

                    // Initialize the number of records.
                    int recordCount = 0;

                    // Define the condition expression for retrieving records.
                    ConditionExpression pagecondition = new ConditionExpression();
                    pagecondition.AttributeName = "parentaccountid";
                    pagecondition.Operator      = ConditionOperator.Equal;
                    pagecondition.Values.Add(_parentAccountId);

                    // Define the order expression to retrieve the records.
                    OrderExpression order = new OrderExpression();
                    order.AttributeName = "name";
                    order.OrderType     = OrderType.Ascending;

                    // Create the query expression and add condition.
                    QueryExpression pagequery = new QueryExpression();
                    pagequery.EntityName = "account";
                    pagequery.Criteria.AddCondition(pagecondition);
                    pagequery.Orders.Add(order);
                    pagequery.ColumnSet.AddColumns("name", "emailaddress1");

                    // Assign the pageinfo properties to the query expression.
                    pagequery.PageInfo            = new PagingInfo();
                    pagequery.PageInfo.Count      = queryCount;
                    pagequery.PageInfo.PageNumber = pageNumber;

                    // The current paging cookie. When retrieving the first page,
                    // pagingCookie should be null.
                    pagequery.PageInfo.PagingCookie = null;
                    Console.WriteLine("Retrieving sample account records in pages...\n");
                    Console.WriteLine("#\tAccount Name\t\tEmail Address");

                    while (true)
                    {
                        // Retrieve the page.
                        EntityCollection results = _serviceProxy.RetrieveMultiple(pagequery);
                        if (results.Entities != null)
                        {
                            // Retrieve all records from the result set.
                            foreach (Account acct in results.Entities)
                            {
                                Console.WriteLine("{0}.\t{1}\t{2}", ++recordCount, acct.Name,
                                                  acct.EMailAddress1);
                            }
                        }

                        // Check for more records, if it returns true.
                        if (results.MoreRecords)
                        {
                            Console.WriteLine("\n****************\nPage number {0}\n****************", pagequery.PageInfo.PageNumber);
                            Console.WriteLine("#\tAccount Name\t\tEmail Address");

                            // Increment the page number to retrieve the next page.
                            pagequery.PageInfo.PageNumber++;

                            // Set the paging cookie to the paging cookie returned from current results.
                            pagequery.PageInfo.PagingCookie = results.PagingCookie;
                        }
                        else
                        {
                            // If no more records are in the result nodes, exit the loop.
                            break;
                        }
                    }
                    //</snippetQueryExpressionPagingWithCookie1>

                    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;
            }
            return;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetDumpAttributeInfo1>
                    #region How to dump attribute info
                    //<snippetDumpAttributeInfo2>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.
                    String filename = String.Concat("AllAttributeDesc.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }
                                if (currentEntity.IsIntersect.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsIntersect", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsIntersect", "no");
                                }



                                #region Attributes


                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("LogicalName", currentAttribute.LogicalName);
                                        // Write the Description if it is set.
                                        if (currentAttribute.Description.UserLocalizedLabel != null)
                                        {
                                            metadataWriter.WriteElementString("Description", currentAttribute.Description.UserLocalizedLabel.Label.ToString());
                                        }

                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());
                                        if (currentAttribute.DisplayName.UserLocalizedLabel != null)
                                        {
                                            metadataWriter.WriteElementString("DisplayName", currentAttribute.DisplayName.UserLocalizedLabel.Label.ToString());
                                        }
                                        if (currentAttribute.SchemaName != null)
                                        {
                                            metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName.ToString());
                                        }
                                        if (currentAttribute.IntroducedVersion != null)
                                        {
                                            metadataWriter.WriteElementString("IntroducedVersion", currentAttribute.IntroducedVersion.ToString());
                                        }
                                        if (currentAttribute.DeprecatedVersion != null)
                                        {
                                            metadataWriter.WriteElementString("DeprecatedVersion", currentAttribute.DeprecatedVersion.ToString());
                                        }
                                        if (currentAttribute.IsCustomAttribute != null)
                                        {
                                            metadataWriter.WriteElementString("IsCustomAttribute", currentAttribute.IsCustomAttribute.Value.ToString());
                                        }
                                        if (currentAttribute.IsCustomizable != null)
                                        {
                                            metadataWriter.WriteElementString("IsCustomizable", currentAttribute.IsCustomizable.Value.ToString());
                                        }
                                        if (currentAttribute.RequiredLevel != null)
                                        {
                                            metadataWriter.WriteElementString("RequiredLevel", currentAttribute.RequiredLevel.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForCreate != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForCreate", currentAttribute.IsValidForCreate.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForRead != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForRead", currentAttribute.IsValidForRead.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForUpdate != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForUpdate", currentAttribute.IsValidForUpdate.Value.ToString());
                                        }
                                        if (currentAttribute.CanBeSecuredForCreate != null)
                                        {
                                            metadataWriter.WriteElementString("CanBeSecuredForCreate", currentAttribute.CanBeSecuredForCreate.Value.ToString());
                                        }
                                        if (currentAttribute.CanBeSecuredForRead != null)
                                        {
                                            metadataWriter.WriteElementString("CanBeSecuredForRead", currentAttribute.CanBeSecuredForRead.Value.ToString());
                                        }
                                        if (currentAttribute.CanBeSecuredForUpdate != null)
                                        {
                                            metadataWriter.WriteElementString("CanBeSecuredForUpdate", currentAttribute.CanBeSecuredForUpdate.Value.ToString());
                                        }
                                        if (currentAttribute.IsAuditEnabled != null)
                                        {
                                            metadataWriter.WriteElementString("IsAuditEnabled", currentAttribute.IsAuditEnabled.Value.ToString());
                                        }
                                        if (currentAttribute.IsManaged != null)
                                        {
                                            metadataWriter.WriteElementString("IsManaged", currentAttribute.IsManaged.Value.ToString());
                                        }
                                        if (currentAttribute.IsPrimaryId != null)
                                        {
                                            metadataWriter.WriteElementString("IsPrimaryId", currentAttribute.IsPrimaryId.Value.ToString());
                                        }
                                        if (currentAttribute.IsPrimaryName != null)
                                        {
                                            metadataWriter.WriteElementString("IsPrimaryName", currentAttribute.IsPrimaryName.Value.ToString());
                                        }
                                        if (currentAttribute.IsRenameable != null)
                                        {
                                            metadataWriter.WriteElementString("IsRenameable", currentAttribute.IsRenameable.Value.ToString());
                                        }
                                        if (currentAttribute.IsSecured != null)
                                        {
                                            metadataWriter.WriteElementString("IsSecured", currentAttribute.IsSecured.Value.ToString());
                                        }
                                        if (currentAttribute.IsValidForAdvancedFind != null)
                                        {
                                            metadataWriter.WriteElementString("IsValidForAdvancedFind", currentAttribute.IsValidForAdvancedFind.Value.ToString());
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    //</snippetDumpAttributeInfo2>
                    #endregion How to dump attribute info



                    Console.WriteLine("Done.");
                    //</snippetDumpAttributeInfo1>

                    //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;
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Shows how to create an Option Set.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                    {
                        // This statement is required to enable early-bound type support.
                        _serviceProxy.EnableProxyTypes();

                        //<snippetCreateOptionSet1>

                        // Define the option set to create.
                        OptionSetMetadata setupOptionSetMetadata = new OptionSetMetadata()
                        {
                            // The name will be used to uniquely identify the option set.
                            // Normally you should generate this identifier using the publisher's
                            // prefix and double-check that the name is not in use.
                            Name          = _optionSetName,
                            DisplayName   = new Label("Example Option Set", _languageCode),
                            Description   = new Label("An Example Option Set", _languageCode),
                            IsGlobal      = true,
                            OptionSetType = OptionSetType.Picklist,

                            // Define the list of options that populate the option set
                            // The order here determines the order shown in the option set.
                            Options =
                            {
                                // Options accepts any number of OptionMetadata instances, which
                                // are simply pairs of Labels and integer values.
                                new OptionMetadata(new Label("Option 1", _languageCode), null),
                                new OptionMetadata(new Label("Option 2", _languageCode), null)
                            }
                        };

                        // Wrap the OptionSetMetadata in the appropriate request.
                        CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest
                        {
                            OptionSet = setupOptionSetMetadata
                        };

                        // Pass the execute statement to the CRM service.
                        _serviceProxy.Execute(createOptionSetRequest);
                        Console.WriteLine("Option Set created");

                        //</snippetCreateOptionSet1>

                        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;
            }
        }
        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 = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    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;

                    //<snippetCreateAndShareAccessTeam1>
                    // 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.");
                    //</snippetCreateAndShareAccessTeam1>

                    // 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>
        /// This sample demonstrates how to roll up opportunities by their parent account.
        /// The sample first creates the Rollup Request. Next, it executes that request.
        /// Finally, the sample displays the results of the Rollup Response.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Create QueryExpression
                    // Create QueryExpression
                    QueryExpression query = new QueryExpression()
                    {
                        EntityName = Opportunity.EntityLogicalName,
                        ColumnSet  = new ColumnSet("name", "accountid"),
                        Criteria   =
                        {
                            Filters                =
                            {
                                new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions     =
                                    {
                                        new ConditionExpression("name", ConditionOperator.Equal, "Opportunity 1")
                                    },
                                }
                            }
                        },
                    };
                    Console.WriteLine("Created QueryExpression.");
                    #endregion Create QueryExpression

                    #region Create RollupRequest
                    //<snippetRollup1>
                    // Create RollupRequest
                    RollupRequest rollupRequest = new RollupRequest();
                    rollupRequest.Query      = query;
                    rollupRequest.Target     = new EntityReference("account", _accountId);
                    rollupRequest.RollupType = RollupType.Extended;
                    Console.WriteLine("Created RollupRequest.");
                    #endregion Create RollupRequest

                    #region Execute RollupRequest
                    // Execute RollupRequest
                    RollupResponse rollupResponse = (RollupResponse)_serviceProxy.Execute(rollupRequest);
                    Console.WriteLine("Executed RollupRequest.");
                    //</snippetRollup1>
                    #endregion Execute RollupRequest

                    #region Show RollupResponse results
                    // Show RollupResponse results
                    Console.WriteLine("RollupResponse Results:");
                    Console.WriteLine("--------------------------------------------------");
                    Console.WriteLine("Count: " + rollupResponse.Results.Count);
                    for (int i = 0; i < rollupResponse.Results.Count; i++)
                    {
                        Console.WriteLine();
                        Console.WriteLine("LogicalName: " + rollupResponse.EntityCollection.Entities[i].LogicalName);
                        Console.WriteLine("Id: " + rollupResponse.EntityCollection.Entities[i].Id);
                    }
                    #endregion Show RollupResponse results

                    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;
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetDumpEntityInfo1>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Entity,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Defaulted setting is to false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);


                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("EntityInfo.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString());
                                metadataWriter.WriteElementString("OwnershipType", currentEntity.OwnershipType.Value.ToString());
                                if (currentEntity.DisplayName.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocalizedLabel.Label);
                                }
                                if (currentEntity.DisplayCollectionName.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocalizedLabel.Label);
                                }
                                metadataWriter.WriteElementString("IntroducedVersion", currentEntity.IntroducedVersion.ToString());
                                metadataWriter.WriteElementString("AutoRouteToOwnerQueue", currentEntity.AutoRouteToOwnerQueue.ToString());
                                metadataWriter.WriteElementString("CanBeInManyToMany", currentEntity.CanBeInManyToMany.Value.ToString());
                                metadataWriter.WriteElementString("CanBePrimaryEntityInRelationship", currentEntity.CanBePrimaryEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanBeRelatedEntityInRelationship", currentEntity.CanBeRelatedEntityInRelationship.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateAttributes", currentEntity.CanCreateAttributes.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateCharts", currentEntity.CanCreateCharts.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateForms", currentEntity.CanCreateForms.Value.ToString());
                                metadataWriter.WriteElementString("CanCreateViews", currentEntity.CanCreateViews.Value.ToString());
                                metadataWriter.WriteElementString("CanModifyAdditionalSettings", currentEntity.CanModifyAdditionalSettings.Value.ToString());
                                metadataWriter.WriteElementString("CanTriggerWorkflow", currentEntity.CanTriggerWorkflow.Value.ToString());

                                metadataWriter.WriteElementString("IsActivity", currentEntity.IsActivity.Value.ToString());
                                //metadataWriter.WriteElementString("ActivityTypeMask", currentEntity.ActivityTypeMask.ToString());

                                metadataWriter.WriteElementString("IsActivityParty", currentEntity.IsActivityParty.Value.ToString());

                                metadataWriter.WriteElementString("IsAuditEnabled", currentEntity.IsAuditEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsAvailableOffline", currentEntity.IsAvailableOffline.ToString());
                                metadataWriter.WriteElementString("IsChildEntity", currentEntity.IsChildEntity.ToString());
                                metadataWriter.WriteElementString("IsConnectionsEnabled", currentEntity.IsConnectionsEnabled.ManagedPropertyLogicalName.ToString());
                                metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.Value.ToString());
                                metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.Value.ToString());

                                metadataWriter.WriteElementString("IsDocumentManagementEnabled", currentEntity.IsDocumentManagementEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsDuplicateDetectionEnabled", currentEntity.IsDuplicateDetectionEnabled.Value.ToString());
                                if (currentEntity.IsEnabledForCharts != null)
                                {
                                    metadataWriter.WriteElementString("IsEnabledForCharts", currentEntity.IsEnabledForCharts.Value.ToString());
                                }
                                metadataWriter.WriteElementString("IsImportable", currentEntity.IsImportable.Value.ToString());
                                metadataWriter.WriteElementString("IsIntersect", currentEntity.IsIntersect.Value.ToString());

                                metadataWriter.WriteElementString("IsMailMergeEnabled", currentEntity.IsMailMergeEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsManaged", currentEntity.IsManaged.Value.ToString());
                                metadataWriter.WriteElementString("IsMappable", currentEntity.IsMappable.Value.ToString());

                                metadataWriter.WriteElementString("IsReadingPaneEnabled", currentEntity.IsReadingPaneEnabled.Value.ToString());
                                metadataWriter.WriteElementString("IsRenameable", currentEntity.IsRenameable.Value.ToString());
                                metadataWriter.WriteElementString("IsValidForAdvancedFind", currentEntity.IsValidForAdvancedFind.Value.ToString());
                                metadataWriter.WriteElementString("IsValidForQueue", currentEntity.IsValidForQueue.Value.ToString());
                                metadataWriter.WriteElementString("IsVisibleInMobile", currentEntity.IsVisibleInMobile.Value.ToString());

                                metadataWriter.WriteElementString("PrimaryIdAttribute", currentEntity.PrimaryIdAttribute);
                                metadataWriter.WriteElementString("PrimaryNameAttribute", currentEntity.PrimaryNameAttribute);
                                metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName);
                                metadataWriter.WriteElementString("RecurrenceBaseEntityLogicalName", currentEntity.RecurrenceBaseEntityLogicalName);
                                if (currentEntity.Description.UserLocalizedLabel != null)
                                {
                                    metadataWriter.WriteElementString("Description", currentEntity.Description.UserLocalizedLabel.Label);
                                }



                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }



                    Console.WriteLine("Done.");
                    //</snippetDumpEntityInfo1>

                    //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;
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create an email template and several attachments.
        /// Retrieve the email attachments
        /// Optionally delete template and attachments.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetGetEmailTemplateAttachments1>

                    //Create a query to retrieve attachments.
                    QueryExpression query = new QueryExpression
                    {
                        EntityName = ActivityMimeAttachment.EntityLogicalName,
                        ColumnSet  = new ColumnSet("filename"),

                        //Define the conditions for each attachment.
                        Criteria =
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions     =
                            {
                                //The ObjectTypeCode must be specified, or else the query
                                //defaults to "email" instead of "template".
                                new ConditionExpression
                                {
                                    AttributeName = "objecttypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Template.EntityTypeCode }
                                },
                                //Specify which template we need.
                                new ConditionExpression
                                {
                                    AttributeName = "objectid",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { _emailTemplateId        }
                                }
                            }
                        }
                    };

                    //Write out the filename of each attachment retrieved.
                    foreach (ActivityMimeAttachment attachment in _serviceProxy.RetrieveMultiple(query).Entities)
                    {
                        Console.WriteLine("Retrieved attachment {0}", attachment.FileName);
                    }

                    //</snippetGetEmailTemplateAttachments1>

                    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;
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// a FieldSecurityProfile object is created and tied to an existing team. Then a
        /// custom entity and several attributes are created and FieldPermission is
        /// assigned to the Identity attribute of the new entity.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetEnableFieldSecurityForAnEntity1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // Create Field Security Profile.
                    FieldSecurityProfile managersProfile = new FieldSecurityProfile();
                    managersProfile.Name = "Managers";
                    _profileId           = _serviceProxy.Create(managersProfile);
                    Console.Write("Created Profile, ");

                    //<snippetEnableFieldSecurityForAnEntity2>
                    // Create the request object and set the monikers with the
                    // teamprofiles_association relationship.
                    AssociateRequest teamToProfile = new AssociateRequest
                    {
                        Target          = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId),
                        RelatedEntities = new EntityReferenceCollection
                        {
                            new EntityReference(Team.EntityLogicalName, _teamId)
                        },
                        Relationship = new Relationship("teamprofiles_association")
                    };

                    // Execute the request.
                    _serviceProxy.Execute(teamToProfile);
                    //</snippetEnableFieldSecurityForAnEntity2>

                    // Create custom activity entity.
                    CreateEntityRequest req = new CreateEntityRequest()
                    {
                        Entity = new EntityMetadata
                        {
                            LogicalName           = "new_tweet",
                            DisplayName           = new Label("Tweet", 1033),
                            DisplayCollectionName = new Label("Tweet", 1033),
                            OwnershipType         = OwnershipTypes.UserOwned,
                            SchemaName            = "New_Tweet",
                            IsActivity            = true,
                            IsAvailableOffline    = true,
                            IsAuditEnabled        = new BooleanManagedProperty(true),
                            IsMailMergeEnabled    = new BooleanManagedProperty(false)
                        },
                        HasActivities    = false,
                        HasNotes         = true,
                        PrimaryAttribute = new StringAttributeMetadata()
                        {
                            SchemaName    = "Subject",
                            LogicalName   = "subject",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength     = 100,
                            DisplayName   = new Label("Subject", 1033)
                        }
                    };

                    // Execute the request.
                    _serviceProxy.Execute(req);
                    Console.Write("Entity Created, ");

                    // Create custom attributes.
                    CreateAttributeRequest attrReq = new CreateAttributeRequest()
                    {
                        Attribute = new StringAttributeMetadata()
                        {
                            LogicalName   = "new_identity",
                            DisplayName   = new Label("Identity", 1033),
                            SchemaName    = "New_Identity",
                            MaxLength     = 500,
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended),
                            IsSecured     = true
                        },
                        EntityName = "new_tweet"
                    };

                    // Execute the request.
                    CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq);
                    _identityId = identityAttributeResponse.AttributeId;
                    Console.Write("Identity Created, ");

                    attrReq = new CreateAttributeRequest()
                    {
                        Attribute = new StringAttributeMetadata()
                        {
                            LogicalName   = "new_message",
                            DisplayName   = new Label("Message", 1033),
                            SchemaName    = "New_Message",
                            MaxLength     = 140,
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended),
                            IsSecured     = true
                        },
                        EntityName = "new_tweet"
                    };

                    // Execute the request.
                    CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq);
                    _messageId = messageAttributeResponse.AttributeId;
                    Console.Write("Message Created, ");

                    // Create the field permission for the Identity attribute.
                    FieldPermission identityPermission = new FieldPermission()
                    {
                        AttributeLogicalName = "new_identity",
                        EntityName           = "new_tweet",
                        CanRead = new OptionSetValue(FieldPermissionType.Allowed),
                        FieldSecurityProfileId = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId)
                    };

                    // Execute the request
                    _identityPermissionId = _serviceProxy.Create(identityPermission);
                    Console.Write("Permission Created. ");

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

            // 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;
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// This method first connects to the Organization service and service context.
        /// Afterwards, several LINQ query techniques are demonstrated.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete
        /// all created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    CreateRequiredRecords();

                    ServiceContext svcContext =
                        new ServiceContext(_service);


                    // Retrieve records with Skip/Take record paging. Setting a page size
                    // can help you manage your Skip and Take calls, since Skip must be
                    // passed a multiple of Take's parameter value.
                    //<snippetUseLinqQuery1>
                    int pageSize = 5;

                    var accountsByPage = (from a in svcContext.AccountSet
                                          select new Account
                    {
                        Name = a.Name,
                    });
                    System.Console.WriteLine("Skip 10 accounts, then Take 5 accounts");
                    System.Console.WriteLine("======================================");
                    foreach (var a in accountsByPage.Skip(2 * pageSize).Take(pageSize))
                    {
                        System.Console.WriteLine(a.Name);
                    }
                    //</snippetUseLinqQuery1>
                    System.Console.WriteLine();
                    System.Console.WriteLine("<End of Listing>");
                    System.Console.WriteLine();
                    //OUTPUT:
                    //Skip 10 accounts, then Take 5 accounts
                    //======================================
                    //Fourth Coffee 6
                    //Fourth Coffee 7
                    //Fourth Coffee 8
                    //Fourth Coffee 9
                    //Fourth Coffee 10

                    //<End of Listing>



                    // Use orderBy to order items retrieved.
                    //<snippetUseLinqQuery2>
                    var orderedAccounts = from a in svcContext.AccountSet
                                          orderby a.Name
                                          select new Account
                    {
                        Name = a.Name,
                    };
                    System.Console.WriteLine("Display accounts ordered by name");
                    System.Console.WriteLine("================================");
                    foreach (var a in orderedAccounts)
                    {
                        System.Console.WriteLine(a.Name);
                    }
                    //</snippetUseLinqQuery2>
                    System.Console.WriteLine();
                    System.Console.WriteLine("<End of Listing>");
                    System.Console.WriteLine();
                    //OUTPUT:
                    //Display accounts ordered by name
                    //================================
                    //A. Datum Corporation
                    //Adventure Works
                    //Coho Vineyard
                    //Fabrikam
                    //Fourth Coffee 1
                    //Fourth Coffee 10
                    //Fourth Coffee 2
                    //Fourth Coffee 3
                    //Fourth Coffee 4
                    //Fourth Coffee 5
                    //Fourth Coffee 6
                    //Fourth Coffee 7
                    //Fourth Coffee 8
                    //Fourth Coffee 9
                    //Humongous Insurance

                    //<End of Listing>


                    // Filter multiple entities using LINQ.
                    //<snippetUseLinqQuery3>
                    var query = from c in svcContext.ContactSet
                                join a in svcContext.AccountSet
                                on c.ContactId equals a.PrimaryContactId.Id
                                where c.LastName == "Wilcox" || c.LastName == "Andrews"
                                where a.Address1_Telephone1.Contains("(206)") ||
                                a.Address1_Telephone1.Contains("(425)")
                                select new
                    {
                        Contact = new Contact
                        {
                            FirstName = c.FirstName,
                            LastName  = c.LastName,
                        },
                        Account = new Account
                        {
                            Address1_Telephone1 = a.Address1_Telephone1
                        }
                    };

                    Console.WriteLine("Join account and contact");
                    Console.WriteLine("List all records matching specified parameters");
                    Console.WriteLine("Contact name: Wilcox or Andrews");
                    Console.WriteLine("Account area code: 206 or 425");
                    Console.WriteLine("==============================================");
                    foreach (var record in query)
                    {
                        Console.WriteLine("Contact Name: {0} {1}",
                                          record.Contact.FirstName, record.Contact.LastName);
                        Console.WriteLine("Account Phone: {0}",
                                          record.Account.Address1_Telephone1);
                    }
                    //</snippetUseLinqQuery3>
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //OUTPUT:
                    //Join account and contact
                    //List all records matching specified parameters
                    //Contact name: Wilcox or Andrews
                    //Account area code: 206 or 425
                    //==============================================
                    //Contact Name: Ben Andrews
                    //Account Phone: (206)555-5555
                    //Contact Name: Ben Andrews
                    //Account Phone: (425)555-5555
                    //Contact Name: Colin Wilcox
                    //Account Phone: (425)555-5555
                    //<End of Listing>



                    // Build a complex query with LINQ. This query includes multiple
                    // JOINs and a complex WHERE statement.
                    //<snippetUseLinqQuery4>
                    var complexQuery = from c in svcContext.ContactSet
                                       join a in svcContext.AccountSet
                                       on c.ContactId equals a.PrimaryContactId.Id
                                       join l in svcContext.CreateQuery <Lead>()
                                       on a.OriginatingLeadId.Id equals l.LeadId
                                       where c.LastName == "Wilcox" || c.LastName == "Andrews"
                                       where a.Address1_Telephone1.Contains("(206)") ||
                                       a.Address1_Telephone1.Contains("(425)")
                                       select new
                    {
                        Contact = new Contact
                        {
                            FirstName = c.FirstName,
                            LastName  = c.LastName,
                        },
                        Account = new Account
                        {
                            Address1_Telephone1 = a.Address1_Telephone1
                        },
                        Lead = new Lead
                        {
                            LeadId = l.LeadId
                        }
                    };

                    Console.WriteLine("Join account, contact and lead");
                    Console.WriteLine("List all records matching specified parameters");
                    Console.WriteLine("Contact name: Wilcox or Andrews");
                    Console.WriteLine("Account area code: 206 or 425");
                    Console.WriteLine("==============================================");
                    foreach (var record in complexQuery)
                    {
                        Console.WriteLine("Lead ID: {0}",
                                          record.Lead.LeadId);
                        Console.WriteLine("Contact Name: {0} {1}",
                                          record.Contact.FirstName, record.Contact.LastName);
                        Console.WriteLine("Account Phone: {0}",
                                          record.Account.Address1_Telephone1);
                    }
                    //</snippetUseLinqQuery4>
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //OUTPUT:
                    //Join account, contact and lead
                    //List all records matching specified parameters
                    //Contact name: Wilcox or Andrews
                    //Account area code: 206 or 425
                    //==============================================
                    //Lead ID: 78d5df14-64a3-e011-aea3-00155dba3818
                    //Contact Name: Colin Wilcox
                    //Account Phone: (425)555-5555
                    //<End of Listing>

                    //Retrieve a related Task for a Contact
                    //Shows requirement that LoadProperty must be used to access the related record.
                    //<snippetUseLinqQuery5>
                    Contact benAndrews = svcContext.ContactSet.Where(c => c.FullName == "Ben Andrews").FirstOrDefault();
                    if (benAndrews != null)
                    {
                        //benAndrews.Contact_Tasks is null until LoadProperty is used.
                        svcContext.LoadProperty(benAndrews, "Contact_Tasks");
                        Task benAndrewsFirstTask = benAndrews.Contact_Tasks.FirstOrDefault();
                        if (benAndrewsFirstTask != null)
                        {
                            Console.WriteLine("Ben Andrews first task with Subject: '{0}' retrieved.", benAndrewsFirstTask.Subject);
                        }
                    }
                    //</snippetUseLinqQuery5>

                    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;
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// retrieves the Contact entity record, and then enables the document management
        /// for the entity.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforRevert">When True, the user will be prompted to revert all
        /// the changes done in this sample.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforRevert)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    //<snippetEnableDocumentManagement1>
                    // Retrieve an entity for which you want to enable document management.
                    // In this sample, we will retrieve and enable document management
                    // for the Contact entity because by default, document management is
                    // not enabled for this entity.

                    RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
                    {
                        EntityFilters = EntityFilters.All,
                        LogicalName   = Contact.EntityLogicalName,

                        // Retrieve only the currently published changes, ignoring the changes
                        // that have not been published.
                        RetrieveAsIfPublished = false
                    };
                    RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);
                    Console.WriteLine("Retrieved the contact entity.");

                    // Get the entity from the response.
                    EntityMetadata contactEntity = entityResponse.EntityMetadata;

                    // Enable document management for the retrieved entity.
                    contactEntity.IsDocumentManagementEnabled = true;

                    // Create an update request.
                    UpdateEntityRequest updateRequest = new UpdateEntityRequest
                    {
                        Entity = contactEntity
                    };
                    _serviceProxy.Execute(updateRequest);

                    // Publish the entity.
                    // All customizations must be published before they can be used.
                    PublishAllXmlRequest enableRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(enableRequest);

                    // Retrieve the contact entity, and verify that document management is enabled.
                    entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);
                    contactEntity  = entityResponse.EntityMetadata;
                    if (contactEntity.IsDocumentManagementEnabled.Value == true)
                    {
                        Console.WriteLine("Enabled document management for the contact entity.");
                    }

                    RevertChanges(promptforRevert);
                    //</snippetEnableDocumentManagement1>
                }
            }

            // 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>
        /// This method first connects to the organization service. Afterwards,
        /// auditing is enabled on the organization, account entity, and a couple
        /// of attributes. Finally, display that information in Console, and creates
        /// an XML file.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            _sampleStartTime = DateTime.Now;
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                // You can access the service through the proxy, but this sample uses the interface instead.
                _service = _serviceProxy;

                #region Enable Auditing for an Account

                Console.WriteLine("Enabling auditing on the organization and account entities.");

                // Enable auditing on the organization.
                // First, get the organization's ID from the system user record.
                Guid orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId;

                // Next, retrieve the organization's record.
                Organization org = _service.Retrieve(Organization.EntityLogicalName, orgId,
                                                     new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                // Finally, enable auditing on the organization.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                bool usersAccessAuditingFlag  = org.IsUserAccessAuditEnabled.HasValue ?
                                                org.IsUserAccessAuditEnabled.Value : false;

                org.IsAuditEnabled           = true;
                org.IsUserAccessAuditEnabled = true;
                _service.Update(org);

                // Enable auditing on account entities.
                bool accountAuditingFlag = EnableEntityAuditing(Account.EntityLogicalName, true);

                #endregion Enable Auditing for an Account

                CreateRequiredRecords();

                #region Create and start XML file

                // Create the XML file
                String fileName = "auditReport.xml";
                textWriter = new XmlTextWriter(fileName, null);
                textWriter.WriteStartDocument();

                // Start Audit Node
                textWriter.WriteStartElement("auditReport", "");

                #endregion

                #region Retrive user access audit records

                var query = new QueryExpression(Audit.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet("createdon", "action", "operation", "objectid"),
                    Criteria  = new FilterExpression(LogicalOperator.And)
                };

                // Only retrieve audit records that track user access.
                query.Criteria.AddCondition("action", ConditionOperator.In,
                                            (int)AuditAction.UserAccessAuditStarted,
                                            (int)AuditAction.UserAccessAuditStopped,
                                            (int)AuditAction.UserAccessviaWebServices,
                                            (int)AuditAction.UserAccessviaWeb);

                // Change this to false in order to retrieve audit records for all users
                // when running the sample.
                var filterAuditsRetrievedByUser = true;
                if (filterAuditsRetrievedByUser)
                {
                    // Only retrieve audit records for the current user.
                    var userFilter = new FilterExpression(LogicalOperator.Or);
                    userFilter.AddCondition(
                        "userid", ConditionOperator.Equal, _serviceProxy.CallerId);
                }
                // Only retrieve records for this sample run, so that we don't get too
                // many results if auditing was enabled previously.
                query.Criteria.AddCondition(
                    "createdon", ConditionOperator.GreaterEqual, _sampleStartTime);

                var results = _serviceProxy.RetrieveMultiple(query);
                foreach (Audit audit in results.Entities)
                {
                    // Display results
                    DisplayAndAddToXMLFileUserAccessDetails(audit);
                }

                #endregion

                #region Retrieve the Audit History
                Console.WriteLine("Retrieving the account change history.\n");

                DateTime startTime = DateTime.Now;

                // Retrieve the audit records for accounts.
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                RetrieveRecordChangeHistoryResponse changeResponse =
                    (RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);

                AuditDetailCollection details = changeResponse.AuditDetailCollection;

                foreach (AttributeAuditDetail detail in details.AuditDetails)
                {
                    // Write out some of the information in each audit record.
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }
                #endregion Retrieve the Audit History

                #region RetrieveAttributeChangeHistoryRequest
                // How to use message: RetrieveAttributeChangeHistoryRequest

                // Update Telephone1 in account entity
                Account accountToUpdate = new Account();
                accountToUpdate.AccountId  = _newAccountId;
                accountToUpdate.Telephone1 = "123-555-5555";
                _serviceProxy.Update(accountToUpdate);
                Console.WriteLine("Updated Telephone1 field in Account entity.");

                Console.WriteLine("Retrieving attribute change history for Telephone1.");
                // Create RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                {
                    Target = new EntityReference(
                        Account.EntityLogicalName, _newAccountId),
                    AttributeLogicalName = "telephone1"
                };

                // Execute RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryResponse =
                    (RetrieveAttributeChangeHistoryResponse)_service.Execute(attributeChangeHistoryRequest);

                // Set AuditDetailCollection and output to console
                details = attributeChangeHistoryResponse.AuditDetailCollection;

                foreach (var detail in details.AuditDetails)
                {
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }

                // Create an Audit record
                // to store a sample for use with RetrieveAuditDetailsRequest
                Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                #endregion RetrieveAttributeChangeHistoryRequest

                #region RetrieveAuditDetailsRequest
                // How to use message: RetrieveAuditDetailsRequest

                Console.WriteLine("Retrieving audit details for an audit record.");
                // Create RetrieveAuditDetailsRequest
                var auditDetailsRequest = new RetrieveAuditDetailsRequest
                {
                    AuditId = auditSampleId
                };

                // Execute RetrieveAuditDetailsRequest
                var auditDetailsResponse =
                    (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);

                // Display results
                DisplayAndAddToXMLFileAuditDetails(auditDetailsResponse.AuditDetail);

                #endregion RetrieveAuditDetailsRequest

                #region Retrieve AuditExtension details

                Console.WriteLine("Simulating a user reading records");
                _service.Retrieve(Account.EntityLogicalName, _newAccountId, new ColumnSet("accountid"));

                // creating read records is an async process - wait until the records have been created
                // wait a max of 30 seconds
                Console.WriteLine("Fetching read audit records for accounts");
                for (int i = 0; i < 30; i++)
                {
                    query = new QueryExpression
                    {
                        EntityName = "sample_auditextension",
                        ColumnSet  = new ColumnSet("createdon", "sample_objectlogicalname",
                                                   "sample_objectid", "sample_userid", "sample_action", "sample_operation"),
                        Criteria = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression("sample_objectlogicalname", ConditionOperator.Equal, Account.EntityLogicalName),
                                new ConditionExpression("sample_objectid",          ConditionOperator.Equal,
                                                        _newAccountId.ToString().TrimStart('{').TrimEnd('}'))
                            }
                        }
                    };
                    results = _service.RetrieveMultiple(query);
                    if (results.Entities.Count > 0)
                    {
                        break;
                    }
                    else if (i == 29)
                    {
                        throw new Exception("Exceeded maximum wait time");
                    }
                    System.Threading.Thread.Sleep(1000);
                }

                foreach (var record in results.Entities)
                {
                    _auditExtensionRecordIds.Add(record.Id);
                    DisplayAndAddToXmlFileAuditExtension(record);
                }

                #endregion

                #region Finish and close XML file

                // End auditReport Xml Node
                textWriter.WriteEndElement();
                textWriter.WriteEndDocument();

                // Close xml writer.
                textWriter.Close();

                Console.WriteLine("File name: " + fileName);

                #endregion

                #region Revert auditing
                // Set the organization and account auditing flags back to the old values
                org.IsAuditEnabled           = organizationAuditingFlag;
                org.IsUserAccessAuditEnabled = usersAccessAuditingFlag;
                _service.Update(org);

                EnableEntityAuditing(Account.EntityLogicalName, accountAuditingFlag);

                #endregion Revert auditing

                DeleteRequiredRecords(promptforDelete);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetDumpPicklistInfo1>
                    #region How to dump attribute info
                    //<snippetDumpPicklistInfo2>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AttributePicklistValues.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }

                                #region Attributes

                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName);
                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());

                                        if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata))
                                        {
                                            PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StateAttributeMetadata))
                                        {
                                            StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata))
                                        {
                                            StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata)
                                                {
                                                    metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString());
                                                }
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    //</snippetDumpPicklistInfo2>
                    #endregion How to dump attribute info



                    Console.WriteLine("Done.");
                    //</snippetDumpPicklistInfo1>

                    //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;
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Delete a new queue instance.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    #region Run a QC with marketing list as input

                    //<snippetQuickCampaign1>

                    List newList = new List()
                    {
                        ListName        = "TestList",
                        CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account)
                    };

                    _newListId = _serviceProxy.Create(newList);

                    for (int j = 0; j < 5; j++)
                    {
                        AddMemberListRequest addMemberListRequest = new AddMemberListRequest();
                        addMemberListRequest.EntityId = _accountIdArray[j];
                        addMemberListRequest.ListId   = _newListId;
                        AddMemberListResponse addMemberListResponse =
                            _serviceProxy.Execute(addMemberListRequest) as AddMemberListResponse;
                    }

                    Guid BOId = CreateAndRetrieveQuickCampaignForMarketingList(
                        _templateLetterActivity,
                        _newListId,
                        PropagationOwnershipOptions.ListMemberOwner,
                        true);

                    //</snippetQuickCampaign1>

                    #endregion

                    #region Run a QC with a list of accounts as input

                    // Construct a Query Expression(QE) which specifies which records QC should include
                    QueryExpression query = new QueryExpression("account");
                    query.ColumnSet = new ColumnSet("accountid");
                    query.Criteria  = new FilterExpression();
                    FilterExpression filter = query.Criteria.AddFilter(LogicalOperator.Or);
                    for (int j = 0; j < 5; j++)
                    {
                        filter.AddCondition("accountid", ConditionOperator.Equal, _accountIdArray[j]);
                    }
                    _qcBOId = CreateAndRetrieveQuickCampaignForQueryExpression(
                        _templateEmailActivity,
                        query,
                        PropagationOwnershipOptions.ListMemberOwner,
                        true);

                    #endregion

                    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;
            }
        }
Ejemplo n.º 25
0
        public void Run(ServerConnection.Configuration serverConfig,
                        bool promptforDelete)
        {
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // This statement is required to enable early bound type support.
                _serviceProxy.EnableProxyTypes();
                CreateRequiredRecords();

                // Retrieve and display the access that the calling user has to the
                // created lead.
                var leadReference        = new EntityReference(Lead.EntityLogicalName, _leadId);
                var currentUserReference = new EntityReference(
                    SystemUser.EntityLogicalName, _currentUserId);
                RetrieveAndDisplayPrincipalAccess(leadReference, currentUserReference,
                                                  "Current User");

                // Retrieve and display the access that the first user has to the
                // created lead.
                var systemUser1Ref = new EntityReference(SystemUser.EntityLogicalName,
                                                         _systemUserIds[0]);
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser1Ref,
                                                  "System User 1");

                // Grant the first user read access to the created lead.
                var grantAccessRequest1 = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.ReadAccess,
                        Principal  = systemUser1Ref
                    },
                    Target = leadReference
                };

                Console.WriteLine("Granting {0} to {1} ({2}) on the lead...\r\n",
                                  AccessRights.ReadAccess, GetEntityReferenceString(systemUser1Ref), "System User 1");
                _serviceProxy.Execute(grantAccessRequest1);


                // Retrieve and display access information for the lead.
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser1Ref,
                                                  "System User 1");
                RetrieveAndDisplayLeadAccess(leadReference);

                //<snippetUserAccess1>
                // Grant the team read/write access to the lead.
                var teamReference      = new EntityReference(Team.EntityLogicalName, _teamId);
                var grantAccessRequest = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                        Principal  = teamReference
                    },
                    Target = leadReference
                };

                Console.WriteLine("Granting {0} to {1} ({2}) on the lead...\r\n",
                                  AccessRights.ReadAccess | AccessRights.WriteAccess, GetEntityReferenceString(teamReference), "Team");
                _serviceProxy.Execute(grantAccessRequest);

                var systemUser2Ref = new EntityReference(SystemUser.EntityLogicalName,
                                                         _systemUserIds[1]);

                //</snippetUserAccess1>

                // Retrieve and display access information for the lead and system user 2.
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser2Ref,
                                                  "System User 2");
                RetrieveAndDisplayLeadAccess(leadReference);

                //<snippetUserAccess2>

                // Grant the first user delete access to the lead.
                var modifyUser1AccessReq = new ModifyAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.DeleteAccess,
                        Principal  = systemUser1Ref
                    },
                    Target = leadReference
                };

                Console.WriteLine("Granting delete access to {0} on the lead...\r\n",
                                  GetEntityReferenceString(systemUser1Ref));
                _serviceProxy.Execute(modifyUser1AccessReq);
                //</snippetUserAccess2>

                // Retrieve and display access information for the lead.
                RetrieveAndDisplayLeadAccess(leadReference);

                //<snippetUserAccess3>

                // Revoke access to the lead for the second user.
                var revokeUser2AccessReq = new RevokeAccessRequest
                {
                    Revokee = systemUser2Ref,
                    Target  = leadReference
                };

                Console.WriteLine("Revoking access to the lead for {0}...\r\n",
                                  GetEntityReferenceString(systemUser2Ref));
                _serviceProxy.Execute(revokeUser2AccessReq);
                //</snippetUserAccess3>

                // Retrieve and display access information for the lead.
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser2Ref,
                                                  "System User 2");

                RetrieveAndDisplayLeadAccess(leadReference);

                DeleteRequiredRecords(promptforDelete);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Main entry point for the application.
        /// </summary>
        /// <param name="CmdArgs">Entities to place on the diagram</param>
        public static int Main(string[] args)
        {
            String filename = String.Empty;

            VisioApi.Application application;
            VisioApi.Document    document;
            DiagramBuilder       builder = new DiagramBuilder();

            try
            {
                // Obtain the target organization's Web address and client logon
                // credentials from the user.
                ServerConnection serverConnect        = new ServerConnection();
                ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(config))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Load Visio and create a new document.
                    application          = new VisioApi.Application();
                    application.Visible  = false; // Not showing the UI increases rendering speed
                    builder.VersionName  = application.Version;
                    document             = application.Documents.Add(String.Empty);
                    builder._application = application;
                    builder._document    = document;

                    // Load the metadata.
                    Console.WriteLine("Loading Metadata...");
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships,
                        RetrieveAsIfPublished = true,
                    };
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                    builder._metadataResponse = response;

                    // Diagram all entities if given no command-line parameters, otherwise diagram
                    // those entered as command-line parameters.
                    if (args.Length < 1)
                    {
                        ArrayList entities = new ArrayList();

                        foreach (EntityMetadata entity in response.EntityMetadata)
                        {
                            // Only draw an entity if it does not exist in the excluded entity table.
                            if (!_excludedEntityTable.ContainsKey(entity.LogicalName.GetHashCode()))
                            {
                                entities.Add(entity.LogicalName);
                            }
                            else
                            {
                                Console.WriteLine("Excluding entity: {0}", entity.LogicalName);
                            }
                        }

                        builder.BuildDiagram((string[])entities.ToArray(typeof(string)), "All Entities");
                        filename = "AllEntities.vsd";
                    }
                    else
                    {
                        builder.BuildDiagram(args, String.Join(", ", args));
                        filename = String.Concat(args[0], ".vsd");
                    }

                    // Save the diagram in the current directory using the name of the first
                    // entity argument or "AllEntities" if none were given. Close the Visio application.
                    document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
                    application.Quit();
                }
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (System.TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe
                        = ex.InnerException
                          as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine("Inner Fault: {0}",
                                          null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            finally
            {
                //Console.WriteLine("Rendering complete.");
                Console.WriteLine("Rendering complete.  Press any key to continue.");
                Console.ReadLine();
            }
            return(0);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, it
        /// creates/retrieves a system user,
        /// retrieves user details, and
        /// creates a query to find the system user using domain\username or first and last name details.
        /// Note: Creating a user is only supported
        /// in an on-premises/active directory environment.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user is prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetRetrieveAUser1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy is properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // Find a user using domain\username or first and last name details.
                    QueryExpression userQuery = new QueryExpression
                    {
                        EntityName = "systemuser",
                        // Retrieve all columns.
                        ColumnSet = new ColumnSet(new String[] { "systemuserid", "domainname", "fullname" }),

                        Criteria =
                        {
                            FilterOperator = LogicalOperator.Or,
                            Filters        =
                            {
                                new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions     =
                                    {
                                        new ConditionExpression("domainname", ConditionOperator.Equal, _domain + _userName)
                                    }
                                },
                                new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions     =
                                    {
                                        new ConditionExpression("firstname", ConditionOperator.Equal, _firstName),
                                        new ConditionExpression("lastname",  ConditionOperator.Equal, _lastName)
                                    }
                                }
                            }
                        }
                    };


                    EntityCollection entities = _serviceProxy.RetrieveMultiple(userQuery);

                    if (entities.Entities.Count > 0)
                    {
                        SystemUser user = entities[0].ToEntity <SystemUser>();

                        // Write out some key user properties.
                        Console.WriteLine("Id: {0}", user.Id);
                        Console.WriteLine("DomainName: {0}", user.DomainName);
                        Console.WriteLine("FullName: {0}", user.FullName);
                    }
                }
                //</snippetRetrieveAUser1>
            }
            // 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>
        /// Retrieve a role from CRM.
        /// Assign that role to a team.
        /// <param name="organizationFriendlyName">The friendly name of
        /// the target organization.</param>
        /// <param name="discoveryServer">The name of the discovery server.</param>
        /// <param name="promptForDelete">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        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 = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetAssignSecurityRoleToTeam1>

                    // Retrieve a role from CRM.
                    QueryExpression query = new QueryExpression
                    {
                        EntityName = Role.EntityLogicalName,
                        ColumnSet  = new ColumnSet("roleid"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                // You would replace the condition below with an actual role
                                // name, or skip this query if you had a role id.
                                new ConditionExpression
                                {
                                    AttributeName = "name",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { _roleName }
                                }
                            }
                        }
                    };

                    Role role = _service.RetrieveMultiple(query).Entities.
                                Cast <Role>().First();


                    // Add the role to the team.
                    _service.Associate(
                        Team.EntityLogicalName,
                        _teamId,
                        new Relationship("teamroles_association"),
                        new EntityReferenceCollection()
                    {
                        new EntityReference(Role.EntityLogicalName, _roleId)
                    });

                    Console.WriteLine("Assigned role to team");
                    //</snippetAssignSecurityRoleToTeam1>

                    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;
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create few types of attributes.
        /// Insert status in the existing status list.
        /// Retrieve attribute.
        /// Update attribute.
        /// Update existing state value.
        /// Optionally delete/revert any attributes
        /// that were created/changed for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetWorkWithAttributes1>
                    #region How to create attributes
                    //<snippetWorkWithAttributes2>
                    // Create storage for new attributes being created
                    addedAttributes = new List <AttributeMetadata>();

                    // Create a boolean attribute
                    BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_boolean",
                        DisplayName   = new Label("Sample Boolean", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Boolean Attribute", _languageCode),
                        // Set extended properties
                        OptionSet = new BooleanOptionSetMetadata(
                            new OptionMetadata(new Label("True", _languageCode), 1),
                            new OptionMetadata(new Label("False", _languageCode), 0)
                            )
                    };

                    // Add to list
                    addedAttributes.Add(boolAttribute);

                    // Create a date time attribute
                    DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_datetime",
                        DisplayName   = new Label("Sample DateTime", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("DateTime Attribute", _languageCode),
                        // Set extended properties
                        Format  = DateTimeFormat.DateOnly,
                        ImeMode = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(dtAttribute);

                    // Create a decimal attribute
                    DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_decimal",
                        DisplayName   = new Label("Sample Decimal", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Decimal Attribute", _languageCode),
                        // Set extended properties
                        MaxValue  = 100,
                        MinValue  = 0,
                        Precision = 1
                    };

                    // Add to list
                    addedAttributes.Add(decimalAttribute);

                    // Create a integer attribute
                    IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_integer",
                        DisplayName   = new Label("Sample Integer", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Integer Attribute", _languageCode),
                        // Set extended properties
                        Format   = IntegerFormat.None,
                        MaxValue = 100,
                        MinValue = 0
                    };

                    // Add to list
                    addedAttributes.Add(integerAttribute);

                    // Create a memo attribute
                    MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_memo",
                        DisplayName   = new Label("Sample Memo", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Memo Attribute", _languageCode),
                        // Set extended properties
                        Format    = StringFormat.TextArea,
                        ImeMode   = ImeMode.Disabled,
                        MaxLength = 500
                    };

                    // Add to list
                    addedAttributes.Add(memoAttribute);

                    // Create a money attribute
                    MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_money",
                        DisplayName   = new Label("Money Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Money Attribue", _languageCode),
                        // Set extended properties
                        MaxValue        = 1000.00,
                        MinValue        = 0.00,
                        Precision       = 1,
                        PrecisionSource = 1,
                        ImeMode         = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(moneyAttribute);

                    // Create a picklist attribute
                    PicklistAttributeMetadata pickListAttribute =
                        new PicklistAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_picklist",
                        DisplayName   = new Label("Sample Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Picklist Attribute", _languageCode),
                        // Set extended properties
                        // Build local picklist options
                        OptionSet = new OptionSetMetadata
                        {
                            IsGlobal      = false,
                            OptionSetType = OptionSetType.Picklist,
                            Options       =
                            {
                                new OptionMetadata(
                                    new Label("Created",                        _languageCode), null),
                                new OptionMetadata(
                                    new Label("Updated",                        _languageCode), null),
                                new OptionMetadata(
                                    new Label("Deleted",                        _languageCode), null)
                            }
                        }
                    };

                    // Add to list
                    addedAttributes.Add(pickListAttribute);

                    // Create a string attribute
                    StringAttributeMetadata stringAttribute = new StringAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_string",
                        DisplayName   = new Label("Sample String", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("String Attribute", _languageCode),
                        // Set extended properties
                        MaxLength = 100
                    };

                    // Add to list
                    addedAttributes.Add(stringAttribute);

                    // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship.
                    // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type.

                    // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK.

                    foreach (AttributeMetadata anAttribute in addedAttributes)
                    {
                        // Create the request.
                        CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
                        {
                            EntityName = Contact.EntityLogicalName,
                            Attribute  = anAttribute
                        };

                        // Execute the request.
                        _serviceProxy.Execute(createAttributeRequest);

                        Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName);
                    }
                    //</snippetWorkWithAttributes2>
                    #endregion How to create attributes

                    #region How to insert status
                    //<snippetWorkWithAttributes3>
                    // Use InsertStatusValueRequest message to insert a new status
                    // in an existing status attribute.
                    // Create the request.
                    InsertStatusValueRequest insertStatusValueRequest =
                        new InsertStatusValueRequest
                    {
                        AttributeLogicalName = "statuscode",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        Label     = new Label("Dormant", _languageCode),
                        StateCode = 0
                    };

                    // Execute the request and store newly inserted value
                    // for cleanup, used later part of this sample.
                    _insertedStatusValue = ((InsertStatusValueResponse)_serviceProxy.Execute(
                                                insertStatusValueRequest)).NewOptionValue;

                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertStatusValueRequest.Label.LocalizedLabels[0].Label,
                                      _insertedStatusValue);
                    //</snippetWorkWithAttributes3>
                    #endregion How to insert status

                    #region How to retrieve attribute
                    //<snippetWorkWithAttributes4>
                    // Create the request
                    RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
                    {
                        EntityLogicalName = Contact.EntityLogicalName,
                        LogicalName       = "new_string",
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Execute the request
                    RetrieveAttributeResponse attributeResponse =
                        (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest);

                    Console.WriteLine("Retrieved the attribute {0}.",
                                      attributeResponse.AttributeMetadata.SchemaName);
                    //</snippetWorkWithAttributes4>
                    #endregion How to retrieve attribute

                    #region How to update attribute
                    //<snippetWorkWithAttributes5>
                    // Modify the retrieved attribute
                    AttributeMetadata retrievedAttributeMetadata =
                        attributeResponse.AttributeMetadata;
                    retrievedAttributeMetadata.DisplayName =
                        new Label("Update String Attribute", _languageCode);

                    // Update an attribute retrieved via RetrieveAttributeRequest
                    UpdateAttributeRequest updateRequest = new UpdateAttributeRequest
                    {
                        Attribute   = retrievedAttributeMetadata,
                        EntityName  = Contact.EntityLogicalName,
                        MergeLabels = false
                    };

                    // Execute the request
                    _serviceProxy.Execute(updateRequest);

                    Console.WriteLine("Updated the attribute {0}.",
                                      retrievedAttributeMetadata.SchemaName);
                    //</snippetWorkWithAttributes5>
                    #endregion How to update attribute

                    #region How to update state value
                    //<snippetWorkWithAttributes6>
                    // Modify the state value label from Active to Open.
                    // Create the request.
                    UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest
                    {
                        AttributeLogicalName = "statecode",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        Value = 1,
                        Label = new Label("Open", _languageCode)
                    };

                    // Execute the request.
                    _serviceProxy.Execute(updateStateValue);

                    Console.WriteLine(
                        "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.",
                        updateStateValue.AttributeLogicalName,
                        updateStateValue.EntityLogicalName,
                        updateStateValue.Label.LocalizedLabels[0].Label
                        );
                    //</snippetWorkWithAttributes6>
                    #endregion How to update state value

                    #region How to insert a new option item in a local option set
                    //<snippetWorkWithAttributes7>
                    // Create a request.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        AttributeLogicalName = "new_picklist",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        Label = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request.
                    int insertOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute(
                                                 insertOptionValueRequest)).NewOptionValue;

                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                                      insertOptionValue);
                    //</snippetWorkWithAttributes7>
                    #endregion How to insert a new option item in a local option set

                    #region How to change the order of options of a local option set
                    //<snippetWorkWithAttributes8>
                    // Use the RetrieveAttributeRequest message to retrieve
                    // a attribute by it's logical name.
                    RetrieveAttributeRequest retrieveAttributeRequest =
                        new RetrieveAttributeRequest
                    {
                        EntityLogicalName = Contact.EntityLogicalName,
                        LogicalName       = "new_picklist",
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Execute the request.
                    RetrieveAttributeResponse retrieveAttributeResponse =
                        (RetrieveAttributeResponse)_serviceProxy.Execute(
                            retrieveAttributeRequest);

                    // Access the retrieved attribute.
                    PicklistAttributeMetadata retrievedPicklistAttributeMetadata =
                        (PicklistAttributeMetadata)
                        retrieveAttributeResponse.AttributeMetadata;

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();

                    // Change the order of the original option's list.
                    // Use the OrderBy (OrderByDescending) linq function to sort options in
                    // ascending (descending) order according to label text.
                    // For ascending order use this:
                    var updateOptionList =
                        optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

                    // For descending order use this:
                    // var updateOptionList =
                    //      optionList.OrderByDescending(
                    //      x => x.Label.LocalizedLabels[0].Label).ToList();

                    // Create the request.
                    OrderOptionRequest orderOptionRequest = new OrderOptionRequest
                    {
                        // Set the properties for the request.
                        AttributeLogicalName = "new_picklist",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        // Set the changed order using Select linq function
                        // to get only values in an array from the changed option list.
                        Values = updateOptionList.Select(x => x.Value.Value).ToArray()
                    };

                    // Execute the request
                    _serviceProxy.Execute(orderOptionRequest);

                    Console.WriteLine("Option Set option order changed");
                    //</snippetWorkWithAttributes8>
                    #endregion How to change the order of options of a global option set

                    // NOTE: All customizations must be published before they can be used.
                    _serviceProxy.Execute(new PublishAllXmlRequest());
                    Console.WriteLine("Published all customizations.");
                    //</snippetWorkWithAttributes1>

                    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>
        /// Create and configure the organization service proxy.
        /// Initiate method to create any data that this sample requires.
        /// Retrieve opportunity and opportunity products.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();


                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetRetrieveOpportunity1>
                    // Retrieve Opportunity record.
                    Opportunity checkOpportunity = (Opportunity)_serviceProxy.Retrieve(
                        Opportunity.EntityLogicalName,
                        _opportunityId,
                        new ColumnSet("name"));

                    Console.WriteLine("Retrieved {0}", checkOpportunity.Name);

                    // Retrieve the related opportunity products
                    QueryExpression opportunityProductsQuery = new QueryExpression
                    {
                        EntityName = OpportunityProduct.EntityLogicalName,
                        ColumnSet  = new ColumnSet("opportunityproductid", "volumediscountamount"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "opportunityid",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { _opportunityId }
                                }
                            }
                        }
                    };

                    DataCollection <Entity> opportunityProducts = _serviceProxy.RetrieveMultiple(
                        opportunityProductsQuery).Entities;

                    foreach (Entity entity in opportunityProducts)
                    {
                        OpportunityProduct opportunityProduct = (OpportunityProduct)entity;
                        Console.WriteLine("Retrieved Opportunity Product {0}",
                                          opportunityProduct.OpportunityProductId.Value);
                    }
                    //</snippetRetrieveOpportunity1>

                    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;
            }
        }