示例#1
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Retrieve organization-owned visualizations.
        /// 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();

                    //<snippetRetrieveVisualizationsAttachedToAnEntity1>
                    // Create a query for retrieving all organization-owned visualizations
                    // that are attached to the account entity.
                    QueryExpression mySavedQuery = new QueryExpression
                    {
                        EntityName = SavedQueryVisualization.EntityLogicalName,
                        ColumnSet  = new ColumnSet("name"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "primaryentitytypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Account.EntityLogicalName }
                                }
                            }
                        }
                    };

                    // Retrieve a collection of organization-owned visualizations that are attached to the account entity.
                    DataCollection <Entity> results = _serviceProxy.RetrieveMultiple(mySavedQuery).Entities;

                    // Display the names of the retrieved organization-owned visualizations.
                    Console.WriteLine("Retrieved the following visualizations for the Account entity:");
                    foreach (Entity entity in results)
                    {
                        SavedQueryVisualization orgVisualization = (SavedQueryVisualization)entity;
                        Console.WriteLine("{0}", orgVisualization.Name);
                    }
                    //</snippetRetrieveVisualizationsAttachedToAnEntity1>
                }
            }
            // 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;
            }
        }
示例#2
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate

                    //Grab the default public view for opportunities.
                    QueryExpression mySavedQuery = new QueryExpression
                    {
                        ColumnSet  = new ColumnSet("savedqueryid"),
                        EntityName = SavedQuery.EntityLogicalName,
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "isdefault",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { true   }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "querytype",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = {      0 }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "returnedtypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Opportunity.EntityTypeCode }
                                }
                            }
                        }
                    };

                    //This query should return one and only one result.
                    SavedQuery defaultOpportunityQuery = service.RetrieveMultiple(mySavedQuery)
                                                         .Entities.Select(x => (SavedQuery)x).FirstOrDefault();

                    // Retrieve visualizations out of the system.
                    // This sample assumes that you have the "Top Opportunities"
                    // visualization that is installed with Microsoft Dynamics CRM.
                    QueryByAttribute visualizationQuery = new QueryByAttribute
                    {
                        EntityName = SavedQueryVisualization.EntityLogicalName,
                        ColumnSet  = new ColumnSet("savedqueryvisualizationid"),
                        Attributes = { "name" },
                        //If you do not have this visualization, you will need to change
                        //this line.
                        Values = { "Top Opportunities" }
                    };


                    SavedQueryVisualization visualization = service.RetrieveMultiple(visualizationQuery).
                                                            Entities.Select(x => (SavedQueryVisualization)x).FirstOrDefault();
                    //This is the language code for U.S. English. If you are running this code
                    //in a different locale, you will need to modify this value.
                    int languageCode = 1033;

                    //We set up our dashboard and specify the FormXml. Refer to the
                    //FormXml schema in the Microsoft Dynamics CRM SDK for more information.
                    SystemForm dashboard = new SystemForm
                    {
                        Name        = "Sample Dashboard",
                        Description = "Sample organization-owned dashboard.",
                        FormXml     = String.Format(@"<form>
                                <tabs>
                                    <tab name='Test Dashboard' verticallayout='true'>
                                        <labels>
                                            <label description='Sample Dashboard' languagecode='{0}' />
                                        </labels>
                                        <columns>
                                            <column width='100%'>
                                                <sections>
                                                    <section name='Information Section'
                                                        showlabel='false' showbar='false'
                                                        columns='111'>
                                                        <labels>
                                                            <label description='Information Section'
                                                                languagecode='{0}' />
                                                        </labels>
                                                        <rows>
                                                            <row>
                                                                <cell colspan='1' rowspan='10' 
                                                                    showlabel='false'>
                                                                    <labels>
                                                                        <label description='Top Opportunitiess - 1'
                                                                        languagecode='{0}' />
                                                                    </labels>
                                                                    <control id='TopOpportunities'
                                                                        classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'>
                                                                        <parameters>
                                                                            <ViewId>{1}</ViewId>
                                                                            <IsUserView>false</IsUserView>
                                                                            <RelationshipName />
                                                                            <TargetEntityType>opportunity</TargetEntityType>
                                                                            <AutoExpand>Fixed</AutoExpand>
                                                                            <EnableQuickFind>false</EnableQuickFind>
                                                                            <EnableViewPicker>false</EnableViewPicker>
                                                                            <EnableJumpBar>false</EnableJumpBar>
                                                                            <ChartGridMode>Chart</ChartGridMode>
                                                                            <VisualizationId>{2}</VisualizationId>
                                                                            <EnableChartPicker>false</EnableChartPicker>
                                                                            <RecordsPerPage>10</RecordsPerPage>
                                                                        </parameters>
                                                                    </control>
                                                                </cell>
                                                                <cell colspan='1' rowspan='10' 
                                                                    showlabel='false'>
                                                                    <labels>
                                                                        <label description='Top Opportunities - 2'
                                                                        languagecode='{0}' />
                                                                    </labels>
                                                                    <control id='TopOpportunities2'
                                                                        classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'>
                                                                        <parameters>
                                                                            <ViewId>{1}</ViewId>
                                                                            <IsUserView>false</IsUserView>
                                                                            <RelationshipName />
                                                                            <TargetEntityType>opportunity</TargetEntityType>
                                                                            <AutoExpand>Fixed</AutoExpand>
                                                                            <EnableQuickFind>false</EnableQuickFind>
                                                                            <EnableViewPicker>false</EnableViewPicker>
                                                                            <EnableJumpBar>false</EnableJumpBar>
                                                                            <ChartGridMode>Grid</ChartGridMode>
                                                                            <VisualizationId>{2}</VisualizationId>
                                                                            <EnableChartPicker>false</EnableChartPicker>
                                                                            <RecordsPerPage>10</RecordsPerPage>
                                                                        </parameters>
                                                                    </control>
                                                                </cell>
                                                            </row>
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                        </rows>
                                                    </section>
                                                </sections>
                                            </column>
                                        </columns>
                                    </tab>
                                </tabs>
                            </form>",
                                                    languageCode,
                                                    defaultOpportunityQuery.SavedQueryId.Value.ToString("B"),
                                                    visualization.SavedQueryVisualizationId.Value.ToString("B")),
                        IsDefault = false
                    };
                    _dashboardId = service.Create(dashboard);
                    Console.WriteLine("Created {0}.", dashboard.Name);

                    //Now we will retrieve the dashboard.
                    SystemForm retrievedDashboard = (SystemForm)service.Retrieve(SystemForm.EntityLogicalName, _dashboardId, new ColumnSet(true));
                    Console.WriteLine("Retrieved the dashboard.");

                    // Update the retrieved dashboard. Enable the chart picker on the chart.
                    var xDocument = XDocument.Parse(retrievedDashboard.FormXml);

                    var chartPicker = (from control in xDocument.Descendants("control")
                                       where control.Attribute("id").Value == "TopOpportunities"
                                       select control.Descendants("EnableChartPicker").First()
                                       ).First();
                    chartPicker.Value = "true";

                    //Now we place the updated Xml back into the dashboard, and update it.
                    retrievedDashboard.FormXml = xDocument.ToString();
                    service.Update(retrievedDashboard);

                    // Publish the dashboard changes to the solution.
                    // This is only required for organization-owned dashboards.
                    var updateRequest = new PublishXmlRequest
                    {
                        ParameterXml = @"<dashboard>_dashboardId</dashboard>"
                    };

                    service.Execute(updateRequest);

                    Console.WriteLine("Updated the dashboard.");
                    #endregion Demonstrate

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

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

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
示例#3
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate
                    // TODO Add demonstration code here
                    #endregion Demonstrate
                    // Create a query for retrieving all organization-owned visualizations
                    // that are attached to the account entity.
                    QueryExpression mySavedQuery = new QueryExpression
                    {
                        EntityName = SavedQueryVisualization.EntityLogicalName,
                        ColumnSet  = new ColumnSet("name"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "primaryentitytypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Account.EntityLogicalName }
                                }
                            }
                        }
                    };

                    // Retrieve a collection of organization-owned visualizations that are attached to the account entity.
                    DataCollection <Entity> results = service.RetrieveMultiple(mySavedQuery).Entities;

                    // Display the names of the retrieved organization-owned visualizations.
                    Console.WriteLine("Retrieved the following visualizations for the Account entity:");
                    foreach (Entity entity in results)
                    {
                        SavedQueryVisualization orgVisualization = (SavedQueryVisualization)entity;
                        Console.WriteLine("{0}", orgVisualization.Name);
                    }
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

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

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            //Grab the default public view for opportunities.
            var mySavedQuery = new QueryExpression
            {
                ColumnSet  = new ColumnSet("savedqueryid"),
                EntityName = SavedQuery.EntityLogicalName,
                Criteria   = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "isdefault",
                            Operator      = ConditionOperator.Equal,
                            Values        = { true   }
                        },
                        new ConditionExpression
                        {
                            AttributeName = "querytype",
                            Operator      = ConditionOperator.Equal,
                            Values        = {      0 }
                        },
                        new ConditionExpression
                        {
                            AttributeName = "returnedtypecode",
                            Operator      = ConditionOperator.Equal,
                            Values        = { Opportunity.EntityTypeCode }
                        }
                    }
                }
            };

            //This query should return one and only one result.
            SavedQuery defaultOpportunityQuery = service.RetrieveMultiple(mySavedQuery)
                                                 .Entities.Select(x => (SavedQuery)x).FirstOrDefault();

            // Retrieve visualizations out of the system.
            // This sample assumes that you have the "Top Opportunities"
            // visualization that is installed with Microsoft Dynamics CRM.
            QueryByAttribute visualizationQuery = new QueryByAttribute
            {
                EntityName = SavedQueryVisualization.EntityLogicalName,
                ColumnSet  = new ColumnSet("savedqueryvisualizationid"),
                Attributes = { "name" },
                //If you do not have this visualization, you will need to change
                //this line.
                Values = { "Top Opportunities" }
            };


            SavedQueryVisualization visualization = service.RetrieveMultiple(visualizationQuery).
                                                    Entities.Select(x => (SavedQueryVisualization)x).FirstOrDefault();

            //This is the language code for U.S. English. If you are running this code
            //in a different locale, you will need to modify this value.
            int languageCode = 1033;

            //We set up our dashboard and specify the FormXml. Refer to the
            //FormXml schema in the Microsoft Dynamics CRM SDK for more information.
            UserForm dashboard = new UserForm
            {
                Name        = "Sample User Dashboard",
                Description = "Sample user-owned dashboard.",
                FormXml     = String.Format(@"<form>
                                <tabs>
                                    <tab name='Test Dashboard' verticallayout='true'>
                                        <labels>
                                            <label description='Sample User Dashboard' languagecode='{0}' />
                                        </labels>
                                        <columns>
                                            <column width='100%'>
                                                <sections>
                                                    <section name='Information Section'
                                                        showlabel='false' showbar='false'
                                                        columns='111'>
                                                        <labels>
                                                            <label description='Information Section'
                                                                languagecode='{0}' />
                                                        </labels>
                                                        <rows>
                                                            <row>
                                                                <cell colspan='1' rowspan='10' 
                                                                    showlabel='false'>
                                                                    <labels>
                                                                        <label description='Top Opportunities - 1'
                                                                        languagecode='{0}' />
                                                                    </labels>
                                                                    <control id='Top10Opportunities'
                                                                        classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'>
                                                                        <parameters>
                                                                            <ViewId>{1}</ViewId>
                                                                            <IsUserView>false</IsUserView>
                                                                            <RelationshipName />
                                                                            <TargetEntityType>opportunity</TargetEntityType>
                                                                            <AutoExpand>Fixed</AutoExpand>
                                                                            <EnableQuickFind>false</EnableQuickFind>
                                                                            <EnableViewPicker>false</EnableViewPicker>
                                                                            <EnableJumpBar>false</EnableJumpBar>
                                                                            <ChartGridMode>Chart</ChartGridMode>
                                                                            <VisualizationId>{2}</VisualizationId>
                                                                            <EnableChartPicker>false</EnableChartPicker>
                                                                            <RecordsPerPage>10</RecordsPerPage>
                                                                        </parameters>
                                                                    </control>
                                                                </cell>
                                                                <cell colspan='1' rowspan='10' 
                                                                    showlabel='false'>
                                                                    <labels>
                                                                        <label description='Top Opportunities - 2'
                                                                        languagecode='{0}' />
                                                                    </labels>
                                                                    <control id='Top10Opportunities2'
                                                                        classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'>
                                                                        <parameters>
                                                                            <ViewId>{1}</ViewId>
                                                                            <IsUserView>false</IsUserView>
                                                                            <RelationshipName />
                                                                            <TargetEntityType>opportunity</TargetEntityType>
                                                                            <AutoExpand>Fixed</AutoExpand>
                                                                            <EnableQuickFind>false</EnableQuickFind>
                                                                            <EnableViewPicker>false</EnableViewPicker>
                                                                            <EnableJumpBar>false</EnableJumpBar>
                                                                            <ChartGridMode>Grid</ChartGridMode>
                                                                            <VisualizationId>{2}</VisualizationId>
                                                                            <EnableChartPicker>false</EnableChartPicker>
                                                                            <RecordsPerPage>10</RecordsPerPage>
                                                                        </parameters>
                                                                    </control>
                                                                </cell>
                                                            </row>
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                        </rows>
                                                    </section>
                                                </sections>
                                            </column>
                                        </columns>
                                    </tab>
                                </tabs>
                            </form>",
                                            languageCode,
                                            defaultOpportunityQuery.SavedQueryId.Value.ToString("B"),
                                            visualization.SavedQueryVisualizationId.Value.ToString("B"))
            };

            _userDashboardId = service.Create(dashboard);

            Console.WriteLine("Created {0}.", dashboard.Name);

            // Create another user to whom the dashboard will be assigned.
            _otherUserId = SystemUserProvider.RetrieveSalesManager(service);

            Console.WriteLine("Required records have been created.");
        }
示例#5
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate

                    // Create a visualization

                    // Set The presentation XML string.
                    string presentationXml = @"
                    <Chart Palette='BrightPastel'>
                        <Series>
                            <Series _Template_='All' ShadowOffset='2' 
                                BorderColor='64, 64, 64' BorderDashStyle='Solid'
                                BorderWidth='1' IsValueShownAsLabel='true' 
                                Font='Tahoma, 6.75pt, GdiCharSet=0' 
                                LabelForeColor='100, 100, 100'
                                CustomProperties='FunnelLabelStyle=Outside' 
                                ChartType='Funnel'>
                                <SmartLabelStyle Enabled='True' />
                                <Points />
                            </Series>
                         </Series>
                        <ChartAreas>
                            <ChartArea _Template_='All' BackColor='Transparent'
                                BorderColor='Transparent' 
                                BorderDashStyle='Solid'>
                                <Area3DStyle Enable3D='True' 
                                    IsClustered='True'/>
                            </ChartArea>
                        </ChartAreas>
                        <Legends>
                            <Legend _Template_='All' Alignment='Center' 
                                LegendStyle='Table' Docking='Bottom' 
                                IsEquallySpacedItems='True' BackColor='White'
                                BorderColor='228, 228, 228' BorderWidth='0' 
                                Font='Tahoma, 8pt, GdiCharSet=0' 
                                ShadowColor='0, 0, 0, 0' 
                                ForeColor='100, 100, 100'>
                            </Legend>
                        </Legends>
                        <Titles>
                            <Title _Template_='All'
                                Font='Tahoma, 9pt, style=Bold, GdiCharSet=0'
                                ForeColor='102, 102, 102'>
                            </Title>
                        </Titles>
                        <BorderSkin PageColor='Control'
                            BackColor='CornflowerBlue'
                            BackSecondaryColor='CornflowerBlue' />
                    </Chart>
                    ";

                    // Set the data XML string.
                    string dataXml = @"
                    <datadefinition>
                        <fetchcollection>
                            <fetch mapping='logical' count='10' 
                                aggregate='true'>
                                <entity name='opportunity'>
                                    <attribute name='actualvalue_base' 
                                        aggregate='sum' 
                                        alias='sum_actualvalue_base' />
                                    <attribute name='stepname' groupby='true' 
                                        alias='stepname' />
                                    <order alias='stepname' descending='false'/>
                                </entity>
                            </fetch>
                        </fetchcollection>
                        <categorycollection>
                            <category>
                                <measurecollection>
                                    <measure alias='sum_actualvalue_base'/>
                                </measurecollection>
                            </category>
                        </categorycollection>
                    </datadefinition>
                    ";
                    // Create the visualization entity instance.
                    var newOrgOwnedVisualization = new SavedQueryVisualization
                    {
                        Name                    = "Sample Visualization",
                        Description             = "Sample organization-owned visualization.",
                        PresentationDescription = presentationXml,
                        DataDescription         = dataXml,
                        PrimaryEntityTypeCode   = Opportunity.EntityLogicalName,
                        IsDefault               = false
                    };
                    _orgOwnedVisualizationId = service.Create(newOrgOwnedVisualization);
                    Console.WriteLine("Created {0}.", newOrgOwnedVisualization.Name);

                    // Retrieve the visualization
                    var retrievedOrgOwnedVisualization = (SavedQueryVisualization)service.Retrieve(SavedQueryVisualization.EntityLogicalName, _orgOwnedVisualizationId, new ColumnSet(true));
                    Console.WriteLine("Retrieved the visualization.");

                    // Update the retrieved visualization
                    // 1.  Update the name.
                    // 2.  Update the data description string.

                    string newDataXml = @"<datadefinition>
                                        <fetchcollection>
                                            <fetch mapping='logical' count='10' 
                                                aggregate='true'>
                                                <entity name='opportunity'>
                                                    <attribute name='estimatedvalue_base' 
                                                        aggregate='sum' 
                                                        alias='sum_estimatedvalue_base' />
                                                    <attribute name='name' 
                                                        groupby='true' 
                                                        alias='name' />
                                                    <order alias='name' 
                                                        descending='false'/>
                                                </entity>
                                            </fetch>
                                        </fetchcollection>
                                        <categorycollection>
                                            <category>
                                                <measurecollection>
                                                    <measure alias='sum_estimatedvalue_base'/>
                                                </measurecollection>
                                            </category>
                                        </categorycollection>
                                    </datadefinition>";

                    retrievedOrgOwnedVisualization.Name            = "Updated Sample Visualization";
                    retrievedOrgOwnedVisualization.DataDescription = newDataXml;

                    service.Update(retrievedOrgOwnedVisualization);

                    // Publish the changes to the solution. This step is only required
                    // for organization-owned visualizations.
                    var updateRequest = new PublishAllXmlRequest();
                    service.Execute(updateRequest);

                    Console.WriteLine("Updated the visualization.");
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

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

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
示例#6
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create a dashboard.
        /// Retrieve the dashboard.
        /// Update the dashboard.
        /// Delete the dashboard.
        /// </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();

                    //<snippetCRUDDashboards1>

                    //Grab the default public view for opportunities.
                    QueryExpression mySavedQuery = new QueryExpression
                    {
                        ColumnSet  = new ColumnSet("savedqueryid"),
                        EntityName = SavedQuery.EntityLogicalName,
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "isdefault",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { true   }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "querytype",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = {      0 }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "returnedtypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Opportunity.EntityTypeCode }
                                }
                            }
                        }
                    };

                    //This query should return one and only one result.
                    SavedQuery defaultOpportunityQuery = _serviceProxy.RetrieveMultiple(mySavedQuery)
                                                         .Entities.Select(x => (SavedQuery)x).FirstOrDefault();

                    // Retrieve visualizations out of the system.
                    // This sample assumes that you have the "Top Opportunities"
                    // visualization that is installed with Microsoft Dynamics CRM.
                    QueryByAttribute visualizationQuery = new QueryByAttribute
                    {
                        EntityName = SavedQueryVisualization.EntityLogicalName,
                        ColumnSet  = new ColumnSet("savedqueryvisualizationid"),
                        Attributes = { "name" },
                        //If you do not have this visualization, you will need to change
                        //this line.
                        Values = { "Top Opportunities" }
                    };


                    SavedQueryVisualization visualization = _serviceProxy.RetrieveMultiple(visualizationQuery).
                                                            Entities.Select(x => (SavedQueryVisualization)x).FirstOrDefault();
                    //<snippetCRUDDashboards2>
                    //This is the language code for U.S. English. If you are running this code
                    //in a different locale, you will need to modify this value.
                    int languageCode = 1033;

                    //We set up our dashboard and specify the FormXml. Refer to the
                    //FormXml schema in the Microsoft Dynamics CRM SDK for more information.
                    SystemForm dashboard = new SystemForm
                    {
                        Name        = "Sample Dashboard",
                        Description = "Sample organization-owned dashboard.",
                        FormXml     = String.Format(@"<form>
                                <tabs>
                                    <tab name='Test Dashboard' verticallayout='true'>
                                        <labels>
                                            <label description='Sample Dashboard' languagecode='{0}' />
                                        </labels>
                                        <columns>
                                            <column width='100%'>
                                                <sections>
                                                    <section name='Information Section'
                                                        showlabel='false' showbar='false'
                                                        columns='111'>
                                                        <labels>
                                                            <label description='Information Section'
                                                                languagecode='{0}' />
                                                        </labels>
                                                        <rows>
                                                            <row>
                                                                <cell colspan='1' rowspan='10' 
                                                                    showlabel='false'>
                                                                    <labels>
                                                                        <label description='Top Opportunitiess - 1'
                                                                        languagecode='{0}' />
                                                                    </labels>
                                                                    <control id='TopOpportunities'
                                                                        classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'>
                                                                        <parameters>
                                                                            <ViewId>{1}</ViewId>
                                                                            <IsUserView>false</IsUserView>
                                                                            <RelationshipName />
                                                                            <TargetEntityType>opportunity</TargetEntityType>
                                                                            <AutoExpand>Fixed</AutoExpand>
                                                                            <EnableQuickFind>false</EnableQuickFind>
                                                                            <EnableViewPicker>false</EnableViewPicker>
                                                                            <EnableJumpBar>false</EnableJumpBar>
                                                                            <ChartGridMode>Chart</ChartGridMode>
                                                                            <VisualizationId>{2}</VisualizationId>
                                                                            <EnableChartPicker>false</EnableChartPicker>
                                                                            <RecordsPerPage>10</RecordsPerPage>
                                                                        </parameters>
                                                                    </control>
                                                                </cell>
                                                                <cell colspan='1' rowspan='10' 
                                                                    showlabel='false'>
                                                                    <labels>
                                                                        <label description='Top Opportunities - 2'
                                                                        languagecode='{0}' />
                                                                    </labels>
                                                                    <control id='TopOpportunities2'
                                                                        classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'>
                                                                        <parameters>
                                                                            <ViewId>{1}</ViewId>
                                                                            <IsUserView>false</IsUserView>
                                                                            <RelationshipName />
                                                                            <TargetEntityType>opportunity</TargetEntityType>
                                                                            <AutoExpand>Fixed</AutoExpand>
                                                                            <EnableQuickFind>false</EnableQuickFind>
                                                                            <EnableViewPicker>false</EnableViewPicker>
                                                                            <EnableJumpBar>false</EnableJumpBar>
                                                                            <ChartGridMode>Grid</ChartGridMode>
                                                                            <VisualizationId>{2}</VisualizationId>
                                                                            <EnableChartPicker>false</EnableChartPicker>
                                                                            <RecordsPerPage>10</RecordsPerPage>
                                                                        </parameters>
                                                                    </control>
                                                                </cell>
                                                            </row>
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                            <row />
                                                        </rows>
                                                    </section>
                                                </sections>
                                            </column>
                                        </columns>
                                    </tab>
                                </tabs>
                            </form>",
                                                    languageCode,
                                                    defaultOpportunityQuery.SavedQueryId.Value.ToString("B"),
                                                    visualization.SavedQueryVisualizationId.Value.ToString("B")),
                        IsDefault = false
                    };
                    _dashboardId = _serviceProxy.Create(dashboard);
                    //</snippetCRUDDashboards2>
                    Console.WriteLine("Created {0}.", dashboard.Name);

                    //Now we will retrieve the dashboard.
                    SystemForm retrievedDashboard = (SystemForm)_serviceProxy.Retrieve(SystemForm.EntityLogicalName, _dashboardId, new ColumnSet(true));
                    Console.WriteLine("Retrieved the dashboard.");

                    // Update the retrieved dashboard. Enable the chart picker on the chart.
                    XDocument xDocument = XDocument.Parse(retrievedDashboard.FormXml);

                    var chartPicker = (from control in xDocument.Descendants("control")
                                       where control.Attribute("id").Value == "TopOpportunities"
                                       select control.Descendants("EnableChartPicker").First()
                                       ).First();
                    chartPicker.Value = "true";

                    //Now we place the updated Xml back into the dashboard, and update it.
                    retrievedDashboard.FormXml = xDocument.ToString();
                    _serviceProxy.Update(retrievedDashboard);

                    // Publish the dashboard changes to the solution.
                    // This is only required for organization-owned dashboards.
                    PublishXmlRequest updateRequest = new PublishXmlRequest
                    {
                        ParameterXml = @"<dashboard>_dashboardId</dashboard>"
                    };

                    _serviceProxy.Execute(updateRequest);

                    Console.WriteLine("Updated the dashboard.");

                    DeleteRequiredRecords(promptForDelete);

                    //</snippetCRUDDashboards1>
                }
            }

            // 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;
            }
        }
示例#7
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create an organization-owned visualization.
        /// Retrieve the visualization.
        /// Update the visualization; update the name and set it as the default
        /// visualization for the Opportunity entity.
        /// 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();

                    //<snippetCRUDVisualization1>
                    // Create a visualization

                    // Set The presentation XML string.
                    string presentationXml = @"
                    <Chart Palette='BrightPastel'>
                        <Series>
                            <Series _Template_='All' ShadowOffset='2' 
                                BorderColor='64, 64, 64' BorderDashStyle='Solid'
                                BorderWidth='1' IsValueShownAsLabel='true' 
                                Font='Tahoma, 6.75pt, GdiCharSet=0' 
                                LabelForeColor='100, 100, 100'
                                CustomProperties='FunnelLabelStyle=Outside' 
                                ChartType='Funnel'>
                                <SmartLabelStyle Enabled='True' />
                                <Points />
                            </Series>
                         </Series>
                        <ChartAreas>
                            <ChartArea _Template_='All' BackColor='Transparent'
                                BorderColor='Transparent' 
                                BorderDashStyle='Solid'>
                                <Area3DStyle Enable3D='True' 
                                    IsClustered='True'/>
                            </ChartArea>
                        </ChartAreas>
                        <Legends>
                            <Legend _Template_='All' Alignment='Center' 
                                LegendStyle='Table' Docking='Bottom' 
                                IsEquallySpacedItems='True' BackColor='White'
                                BorderColor='228, 228, 228' BorderWidth='0' 
                                Font='Tahoma, 8pt, GdiCharSet=0' 
                                ShadowColor='0, 0, 0, 0' 
                                ForeColor='100, 100, 100'>
                            </Legend>
                        </Legends>
                        <Titles>
                            <Title _Template_='All'
                                Font='Tahoma, 9pt, style=Bold, GdiCharSet=0'
                                ForeColor='102, 102, 102'>
                            </Title>
                        </Titles>
                        <BorderSkin PageColor='Control'
                            BackColor='CornflowerBlue'
                            BackSecondaryColor='CornflowerBlue' />
                    </Chart>
                    ";

                    // Set the data XML string.
                    string dataXml = @"
                    <datadefinition>
                        <fetchcollection>
                            <fetch mapping='logical' count='10' 
                                aggregate='true'>
                                <entity name='opportunity'>
                                    <attribute name='actualvalue_base' 
                                        aggregate='sum' 
                                        alias='sum_actualvalue_base' />
                                    <attribute name='stepname' groupby='true' 
                                        alias='stepname' />
                                    <order alias='stepname' descending='false'/>
                                </entity>
                            </fetch>
                        </fetchcollection>
                        <categorycollection>
                            <category>
                                <measurecollection>
                                    <measure alias='sum_actualvalue_base'/>
                                </measurecollection>
                            </category>
                        </categorycollection>
                    </datadefinition>
                    ";
                    //<snippetCRUDVisualization2>
                    // Create the visualization entity instance.
                    SavedQueryVisualization newOrgOwnedVisualization = new SavedQueryVisualization
                    {
                        Name                    = "Sample Visualization",
                        Description             = "Sample organization-owned visualization.",
                        PresentationDescription = presentationXml,
                        DataDescription         = dataXml,
                        PrimaryEntityTypeCode   = Opportunity.EntityLogicalName,
                        IsDefault               = false
                    };
                    _orgOwnedVisualizationId = _serviceProxy.Create(newOrgOwnedVisualization);
                    //</snippetCRUDVisualization2>
                    Console.WriteLine("Created {0}.", newOrgOwnedVisualization.Name);
                    //</snippetCRUDVisualization1>

                    // Retrieve the visualization
                    SavedQueryVisualization retrievedOrgOwnedVisualization = (SavedQueryVisualization)_serviceProxy.Retrieve(SavedQueryVisualization.EntityLogicalName, _orgOwnedVisualizationId, new ColumnSet(true));
                    Console.WriteLine("Retrieved the visualization.");

                    // Update the retrieved visualization
                    // 1.  Update the name.
                    // 2.  Update the data description string.

                    string newDataXml = @"<datadefinition>
                                        <fetchcollection>
                                            <fetch mapping='logical' count='10' 
                                                aggregate='true'>
                                                <entity name='opportunity'>
                                                    <attribute name='estimatedvalue_base' 
                                                        aggregate='sum' 
                                                        alias='sum_estimatedvalue_base' />
                                                    <attribute name='name' 
                                                        groupby='true' 
                                                        alias='name' />
                                                    <order alias='name' 
                                                        descending='false'/>
                                                </entity>
                                            </fetch>
                                        </fetchcollection>
                                        <categorycollection>
                                            <category>
                                                <measurecollection>
                                                    <measure alias='sum_estimatedvalue_base'/>
                                                </measurecollection>
                                            </category>
                                        </categorycollection>
                                    </datadefinition>";

                    retrievedOrgOwnedVisualization.Name            = "Updated Sample Visualization";
                    retrievedOrgOwnedVisualization.DataDescription = newDataXml;

                    _serviceProxy.Update(retrievedOrgOwnedVisualization);

                    // Publish the changes to the solution. This step is only required
                    // for organization-owned visualizations.
                    PublishAllXmlRequest updateRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(updateRequest);

                    Console.WriteLine("Updated the visualization.");

                    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;
            }
        }
        private async Task PerformUpdateEntityField(string folder, Guid idSavedQueryVisualization, string entityName, string name, string fieldName, string fieldTitle)
        {
            if (!this.IsControlsEnabled)
            {
                return;
            }

            var service = await GetService();

            if (service == null)
            {
                return;
            }

            ToggleControls(service.ConnectionData, false, Properties.OutputStrings.InConnectionUpdatingFieldFormat2, service.ConnectionData.Name, fieldName);

            try
            {
                var repository = new SavedQueryVisualizationRepository(service);

                var savedQueryVisualization = await repository.GetByIdAsync(idSavedQueryVisualization, new ColumnSet(fieldName));

                string xmlContent = savedQueryVisualization.GetAttributeValue <string>(fieldName);

                {
                    if (ContentComparerHelper.TryParseXml(xmlContent, out var doc))
                    {
                        xmlContent = doc.ToString();
                    }
                }

                string filePath = await CreateFileAsync(folder, entityName, name, fieldTitle + " BackUp", xmlContent);

                var  newText      = string.Empty;
                bool?dialogResult = false;

                this.Dispatcher.Invoke(() =>
                {
                    var form = new WindowTextField("Enter " + fieldTitle, fieldTitle, xmlContent);

                    dialogResult = form.ShowDialog();

                    newText = form.FieldText;
                });

                if (dialogResult.GetValueOrDefault() == false)
                {
                    ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionUpdatingFieldFailedFormat2, service.ConnectionData.Name, fieldName);
                    return;
                }

                newText = ContentComparerHelper.RemoveInTextAllCustomXmlAttributesAndNamespaces(newText);

                {
                    if (ContentComparerHelper.TryParseXml(newText, out var doc))
                    {
                        newText = doc.ToString(SaveOptions.DisableFormatting);
                    }
                }

                var updateEntity = new SavedQueryVisualization
                {
                    Id = idSavedQueryVisualization
                };
                updateEntity.Attributes[fieldName] = newText;

                await service.UpdateAsync(updateEntity);

                UpdateStatus(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingEntitiesFormat2, service.ConnectionData.Name, entityName);

                {
                    var repositoryPublish = new PublishActionsRepository(service);

                    await repositoryPublish.PublishEntitiesAsync(new[] { entityName });
                }

                ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionUpdatingFieldCompletedFormat2, service.ConnectionData.Name, fieldName);
            }
            catch (Exception ex)
            {
                _iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);

                ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionUpdatingFieldFailedFormat2, service.ConnectionData.Name, fieldName);
            }
        }
 public EntityViewItem(SavedQueryVisualization savedQueryVisualization)
 {
     this.SavedQueryVisualization = savedQueryVisualization;
 }
示例#10
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create an organization-owned visualization.
        /// Retrieve the visualization.
        /// Update the visualization; update the name and set it as the default
        /// visualization for the Opportunity entity.
        /// 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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();


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

                    //<snippetCRUDVisualization1>
                    // Create a visualization

                    // Set The presentation XML string.
                    string presentationXml = @"
                    <Chart Palette='BrightPastel'>
                        <Series>
                            <Series _Template_='All' ShadowOffset='2' 
                                BorderColor='64, 64, 64' BorderDashStyle='Solid'
                                BorderWidth='1' IsValueShownAsLabel='true' 
                                Font='Tahoma, 6.75pt, GdiCharSet=0' 
                                LabelForeColor='100, 100, 100'
                                CustomProperties='FunnelLabelStyle=Outside' 
                                ChartType='Funnel'>
                                <SmartLabelStyle Enabled='True' />
                                <Points />
                            </Series>
                         </Series>
                        <ChartAreas>
                            <ChartArea _Template_='All' BackColor='Transparent'
                                BorderColor='Transparent' 
                                BorderDashStyle='Solid'>
                                <Area3DStyle Enable3D='True' 
                                    IsClustered='True'/>
                            </ChartArea>
                        </ChartAreas>
                        <Legends>
                            <Legend _Template_='All' Alignment='Center' 
                                LegendStyle='Table' Docking='Bottom' 
                                IsEquallySpacedItems='True' BackColor='White'
                                BorderColor='228, 228, 228' BorderWidth='0' 
                                Font='Tahoma, 8pt, GdiCharSet=0' 
                                ShadowColor='0, 0, 0, 0' 
                                ForeColor='100, 100, 100'>
                            </Legend>
                        </Legends>
                        <Titles>
                            <Title _Template_='All'
                                Font='Tahoma, 9pt, style=Bold, GdiCharSet=0'
                                ForeColor='102, 102, 102'>
                            </Title>
                        </Titles>
                        <BorderSkin PageColor='Control'
                            BackColor='CornflowerBlue'
                            BackSecondaryColor='CornflowerBlue' />
                    </Chart>
                    ";

                    // Set the data XML string.
                    string dataXml = @"
                    <datadefinition>
                        <fetchcollection>
                            <fetch mapping='logical' count='10' 
                                aggregate='true'>
                                <entity name='opportunity'>
                                    <attribute name='actualvalue_base' 
                                        aggregate='sum' 
                                        alias='sum_actualvalue_base' />
                                    <attribute name='stepname' groupby='true' 
                                        alias='stepname' />
                                    <order alias='stepname' descending='false'/>
                                </entity>
                            </fetch>
                        </fetchcollection>
                        <categorycollection>
                            <category>
                                <measurecollection>
                                    <measure alias='sum_actualvalue_base'/>
                                </measurecollection>
                            </category>
                        </categorycollection>
                    </datadefinition>
                    ";
                    //<snippetCRUDVisualization2>
                    // Create the visualization entity instance.
                    SavedQueryVisualization newOrgOwnedVisualization = new SavedQueryVisualization
                    {
                        Name = "Sample Visualization",
                        Description = "Sample organization-owned visualization.",
                        PresentationDescription = presentationXml,
                        DataDescription = dataXml,
                        PrimaryEntityTypeCode = Opportunity.EntityLogicalName,
                        IsDefault = false
                    };
                    _orgOwnedVisualizationId = _serviceProxy.Create(newOrgOwnedVisualization);
                    //</snippetCRUDVisualization2>
                    Console.WriteLine("Created {0}.", newOrgOwnedVisualization.Name);
                    //</snippetCRUDVisualization1>

                    // Retrieve the visualization
                    SavedQueryVisualization retrievedOrgOwnedVisualization = (SavedQueryVisualization)_serviceProxy.Retrieve(SavedQueryVisualization.EntityLogicalName, _orgOwnedVisualizationId, new ColumnSet(true));
                    Console.WriteLine("Retrieved the visualization.");

                    // Update the retrieved visualization
                    // 1.  Update the name.
                    // 2.  Update the data description string.                    

                    string newDataXml = @"<datadefinition>
                                        <fetchcollection>
                                            <fetch mapping='logical' count='10' 
                                                aggregate='true'>
                                                <entity name='opportunity'>
                                                    <attribute name='estimatedvalue_base' 
                                                        aggregate='sum' 
                                                        alias='sum_estimatedvalue_base' />
                                                    <attribute name='name' 
                                                        groupby='true' 
                                                        alias='name' />
                                                    <order alias='name' 
                                                        descending='false'/>
                                                </entity>
                                            </fetch>
                                        </fetchcollection>
                                        <categorycollection>
                                            <category>
                                                <measurecollection>
                                                    <measure alias='sum_estimatedvalue_base'/>
                                                </measurecollection>
                                            </category>
                                        </categorycollection>
                                    </datadefinition>";

                    retrievedOrgOwnedVisualization.Name = "Updated Sample Visualization";
                    retrievedOrgOwnedVisualization.DataDescription = newDataXml;

                    _serviceProxy.Update(retrievedOrgOwnedVisualization);

                    // Publish the changes to the solution. This step is only required
                    // for organization-owned visualizations.
                    PublishAllXmlRequest updateRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(updateRequest);

                    Console.WriteLine("Updated the visualization.");

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