Ejemplo n.º 1
0
        public FlowEntity GetForm(SystemForm systemForm)
        {
            var expression = ExtLinq.True <FlowEntity>();

            expression = expression.And(t => t.DeleteMark != true && t.EnabledMark == true && t.FormType == (int)FormType.System && t.SystemFormType == (int)systemForm);
            return(service.IQueryable(expression).OrderBy(t => t.SortCode).FirstOrDefault());
        }
Ejemplo n.º 2
0
        public bool Start(SystemForm systemForm, string key, Dictionary <string, string> prarms)
        {
            bool bResult = false;

            try
            {
                List <WorkControlEntity> controls = new List <WorkControlEntity>();
                if (prarms != null && prarms.Count > 0)
                {
                    WorkControlEntity workControlEntity = new WorkControlEntity();
                    foreach (var item in prarms)
                    {
                        workControlEntity          = new WorkControlEntity();
                        workControlEntity.FullName = item.Key;
                        workControlEntity.Value    = item.Value;
                        controls.Add(workControlEntity);
                    }
                }
                FlowEntity flowEntity = flowApp.GetForm(systemForm);
                workApp.StartApply(flowEntity?.Id, key, controls);
                bResult = true;
            }
            catch
            {
                bResult = false;
            }
            return(bResult);
        }
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecutePreValidateSmartintForEntityCreate(LocalPluginContext localContext)
        {
            Entity entity = GetTargetEntity(localContext);

            if (entity == null)
            {
                return;
            }

            var        entityInfo = GetEntityInfo(entity);
            SystemForm systemForm = GetSystemForm(localContext, entityInfo);
            FormType   form       = Deserialize <FormType>(systemForm.FormXml);

            form = FixFormNavigation(form);

            form.Navigation.NavBar.Items = AddItem(form.Navigation.NavBar.Items);

            string result = Serialize <FormType>(form);

            if (result.Equals(systemForm.FormXml))
            {
                return;
            }

            systemForm.FormXml = result;
            UpdateSystemForm(localContext, systemForm);
            PublishSystemForm(localContext, entityInfo.Item1);
        }
Ejemplo n.º 4
0
        public IActionResult CopyForm(Guid systemFormId, string name)
        {
            string msg = string.Empty;

            if (!systemFormId.Equals(Guid.Empty))
            {
                var entity = _systemFormFinder.FindById(systemFormId);
                if (entity != null)
                {
                    var newForm = new SystemForm();
                    entity.CopyTo(newForm);
                    newForm.Name         = name.IfEmpty(entity.Name + " Copy");
                    newForm.IsDefault    = false;
                    newForm.CreatedBy    = CurrentUser.SystemUserId;
                    newForm.CreatedOn    = DateTime.Now;
                    newForm.SystemFormId = Guid.NewGuid();
                    List <Guid> assignRolesId = null;
                    if (entity.AuthorizationEnabled)
                    {
                        var assignRoles = _roleObjectAccessService.Query(entity.SystemFormId, FormDefaults.ModuleName);
                        if (assignRoles.NotEmpty())
                        {
                            assignRolesId = assignRoles.Select(x => x.RoleId).ToList();
                        }
                    }
                    _systemFormCreater.Create(newForm);
                    return(SaveSuccess(new { id = entity.SystemFormId }));
                }
            }
            return(SaveFailure());
        }
Ejemplo n.º 5
0
        protected SystemForm GetSystemForm(LocalPluginContext localContext, Tuple <string, string, bool> entityInfo)
        {
            QueryExpression q = new QueryExpression(SystemForm.EntityLogicalName);

            q.EntityName = SystemForm.EntityLogicalName;
            q.ColumnSet  = new ColumnSet("formxml");
            q.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, entityInfo.Item1);
            q.Criteria.AddCondition("type", ConditionOperator.Equal, "2");

            if (entityInfo.Item3)
            {
                q.AddOrder("publishedon", OrderType.Ascending);
            }
            else
            {
                q.Criteria.AddCondition("name", ConditionOperator.Equal, entityInfo.Item2);
            }


            EntityCollection entityCollection = localContext.OrganizationService.RetrieveMultiple(q);
            SystemForm       systemForm       = entityCollection.Entities.FirstOrDefault() as SystemForm;

            if (systemForm == null)
            {
                throw new InvalidPluginExecutionException(string.Format("No form found for entity"));
            }
            return(systemForm);
        }
Ejemplo n.º 6
0
        private void updateButton_Click(object sender, EventArgs e)
        {
            //do stuff

            SystemForm parent = (SystemForm)this.Owner;

            parent.searchButton.PerformClick();

            this.Close();
        }
        public void LoadData(SystemForm systemForm)
        {
            if (systemForm.FormId.HasValue)
            {
                this.FormId = systemForm.FormId;
            }

            this.Name           = systemForm.Name;
            this.Description    = systemForm.Description;
            this.ObjectTypeCode = systemForm.ObjectTypeCode;
        }
Ejemplo n.º 8
0
 public IActionResult CreateForm(EditFormModel model)
 {
     if (ModelState.IsValid)
     {
         var entity = new SystemForm();
         model.CopyTo(entity);
         entity.SystemFormId = Guid.NewGuid();
         entity.StateCode    = RecordState.Enabled;
         entity.FormType     = (int)FormType.Main;
         _systemFormCreater.Create(entity);
         return(CreateSuccess(new { id = entity.SystemFormId }));
     }
     return(CreateFailure(GetModelErrors()));
 }
        public DependentEntity GetDependencyObject(Dependency dependency)
        {
            var objectId = dependency.DependentComponentObjectId.Value;

            switch (dependency.DependentComponentTypeValue)
            {
            case Dependency.ComponentType.SystemForm:
                return(SystemForm.GetEntity(this.Service, objectId));

            case Dependency.ComponentType.EntityRelationship:
                return(EntityRelationship.GetEntity(this.Service, objectId));
            }

            return(null);
        }
Ejemplo n.º 10
0
        public bool Start(SystemForm systemForm, string key)
        {
            bool bResult = false;

            try
            {
                FlowEntity flowEntity = flowApp.GetForm(systemForm);
                workApp.StartApply(flowEntity?.Id, key);
                bResult = true;
            }
            catch
            {
                bResult = false;
            }
            return(bResult);
        }
Ejemplo n.º 11
0
 public IActionResult CreateDashBoard([FromBody] EditDashBoardModel model)
 {
     if (ModelState.IsValid)
     {
         var entity = new SystemForm();
         model.CopyTo(entity);
         entity.SystemFormId = Guid.NewGuid();
         entity.SolutionId   = SolutionId.Value;
         entity.EntityId     = Guid.Empty;
         entity.StateCode    = Core.RecordState.Enabled;
         entity.FormType     = (int)FormType.Dashboard;
         entity.CreatedBy    = CurrentUser.SystemUserId;
         entity.CreatedOn    = DateTime.Now;
         return(_systemFormCreater.Create(entity).CreateResult(T, new { id = entity.SystemFormId }));
     }
     return(CreateFailure(GetModelErrors()));
 }
Ejemplo n.º 12
0
        public async Task <IActionResult> Edit(int id)
        {
            try
            {
                SystemForm item = await _systemFormRepository.GetByIDAsync(id);

                SystemFormViewModel model = _mapper.Map <SystemForm, SystemFormViewModel>(item);
                return(View(model));
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                return(View("~/Views/Shared/Error.cshtml", new ErrorViewModel {
                    RequestId = e.Message
                }));
            }
        }
Ejemplo n.º 13
0
        private void simpleButtonHardware_Click(object sender, EventArgs e)
        {
            var sp = DevExpressHelper.GetSelectedRecord <SalePoint>(gridViewSalePoints);

            if (sp != null)
            {
                try
                {
                    var clientService = Protocol.CreateClientProxy(sp.IP);
                    SystemForm.Show(this, sp, clientService.GetSystemInfo());
                }
                catch (Exception ex)
                {
                    ErrorHelper.ShowError <ErrorForm>(null, ex);
                }
            }
        }
Ejemplo n.º 14
0
 public IActionResult CopyDashboard(Guid systemFormId, string name)
 {
     if (!systemFormId.Equals(Guid.Empty))
     {
         var entity = _systemFormFinder.FindById(systemFormId);
         if (entity != null)
         {
             var newForm = new SystemForm();
             entity.CopyTo(newForm);
             newForm.Name         = name.IfEmpty(entity.Name + " Copy");
             newForm.CreatedBy    = CurrentUser.SystemUserId;
             newForm.CreatedOn    = DateTime.Now;
             newForm.SystemFormId = Guid.NewGuid();
             return(_systemFormCreater.Create(newForm).CreateResult(T, new { id = entity.SystemFormId }));
         }
     }
     return(CreateFailure(GetModelErrors()));
 }
Ejemplo n.º 15
0
        private bool IsExistSystemFlow(SystemForm systemForm, string flowId)
        {
            bool bResult    = false;
            var  expression = ExtLinq.True <FlowEntity>();

            expression = expression.And(t => t.DeleteMark != true &&
                                        t.EnabledMark == true &&
                                        t.FormType == (int)FormType.System &&
                                        t.SystemFormType == (int)systemForm);
            if (!string.IsNullOrWhiteSpace(flowId))
            {
                expression = expression.And(t => t.Id != flowId);
            }
            FlowEntity flow = service.IQueryable(expression).OrderBy(t => t.SortCode).FirstOrDefault();

            if (flow == null || string.IsNullOrWhiteSpace(flow.Id))
            {
                bResult = true;
            }
            return(bResult);
        }
        private void ShowImage()
        {
            CrmQuery qe = new CrmQuery("systemform");

            qe.AddSimpleCondition("type", "2"); //main form
            qe.AddSimpleCondition("objecttypecode", Person.EntityLogicalName.ToLower());
            qe.Attributes = new List <string>()
            {
                "formxml"
            };
            var        allSysforms = WebControlUtility.CrmData.RetrieveMultiple <SystemForm>(qe);
            SystemForm ImageAttributeDemoMainForm = allSysforms.First <SystemForm>();

            XDocument ImageAttributeDemoMainFormXml = XDocument.Parse(ImageAttributeDemoMainForm.formxml);

            if (ImageAttributeDemoMainFormXml.Root.Attribute("showImage").Value == "true")
            {
                ImageAttributeDemoMainFormXml.Root.SetAttributeValue("showImage", false);
            }
            else
            {
                ImageAttributeDemoMainFormXml.Root.SetAttributeValue("showImage", true);           //Updating the entity form definition
            }
            ImageAttributeDemoMainForm.formxml = ImageAttributeDemoMainFormXml.ToString();
            WebControlUtility.CrmData.Update(ImageAttributeDemoMainForm);

            OrganizationServiceContext context = new OrganizationServiceContext(WebControlUtility.CrmData.Connection.OrganizationService);
            PublishXmlRequest          pxReq1  = new PublishXmlRequest {
                ParameterXml = String.Format(@"
               <importexportxml>
                <entities>
                 <entity>{0}</entity>
                </entities>
               </importexportxml>", Person.EntityLogicalName.ToLower())
            };

            context.Execute(pxReq1);
        }
Ejemplo n.º 17
0
        public StringBuilder CopySetTabandFieldsData(string entityLogicalName, List <TabParametersModel> tabParm)
        {
            QueryExpression qe = new QueryExpression("systemform");

            qe.Criteria.AddCondition("type", ConditionOperator.Equal, 2);                           //main form
            qe.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, entityLogicalName); //for new_bankaccount entity
            qe.ColumnSet.AddColumn("formxml");
            //Retrieve the first main entity form for this entity
            SystemForm bankAccountMainForm = (SystemForm)_serviceProxy.RetrieveMultiple(qe).Entities[0];

            XDocument bankAccountFormXml = XDocument.Parse(bankAccountMainForm.FormXml);

            //Set the showImage attribute so the entity image will be displayed
            bankAccountFormXml.Root.SetAttributeValue("showImage", true);
            bankAccountFormXml.Element("form")
            .Element("tabs")
            .Elements("tab")
            .Where(x => (string)x.Attribute("verticallayout") == "true")
            .Remove();

            StringBuilder MyStringBuilder = new StringBuilder();
            int           i = 1;

            foreach (var tab in tabParm)
            {
                i += 1;
                Guid tabId    = Guid.NewGuid();
                Guid sectioId = Guid.NewGuid();
                if (i > 2)
                {
                    MyStringBuilder.AppendLine();
                    MyStringBuilder.Append("<tab name=\"" + tab.TabName + "\" id=\"{" + tabId + "}\" IsUserDefined=\"0\" locklevel=\"0\" showlabel=\"true\"  expanded=\"true\" >");
                }
                else
                {
                    MyStringBuilder.Append("<tab name=\"" + tab.TabName + "\" id=\"{" + tabId + "}\" IsUserDefined=\"0\" locklevel=\"0\" showlabel=\"true\"  expanded=\"true\" >");
                }

                MyStringBuilder.Append("<labels><label description=\"" + tab.TabDisplayName + "\" languagecode=\"1033\" /></labels>");
                MyStringBuilder.Append("<columns><column width=\"100%\"><sections><section name=\"" + tab.TabSectionName + "\" showlabel=\"false\"  showbar=\"false\" locklevel=\"0\" id=\"{" + sectioId + "}\" IsUserDefined=\"0\" layout=\"varwidth\" columns=\"1\" labelwidth=\"115\" celllabelalignment=\"Left\" celllabelposition=\"Left\" ><labels><label description=\"" + tab.TabSectionDisplayName + "\" languagecode=\"1033\" /></labels>");
                MyStringBuilder.Append("<rows>");
                foreach (var field in tab.EntityFields)
                {
                    Guid cellId  = Guid.NewGuid();
                    Guid classId = Guid.NewGuid();
                    if (field.IsGrid)
                    {
                        MyStringBuilder.Append("<row><cell id=\"{" + cellId + "}\" showlabel=\"true\" locklevel=\"0\" > <labels><label description=\"" + field.FieldDisplayName + "\" languagecode=\"1033\" /> </labels><control id=\"" + field.ControlId + "\" classid=\"{" + classId + "}\"  disabled=\"false\"><parameters><ViewId>" + field.ViewId + "</ViewId><IsUserView>false</IsUserView><RelationshipName>New_Parent_powerformId</RelationshipName><TargetEntityType>new_powerformfieldsid</TargetEntityType><AutoExpand>Fixed</AutoExpand><EnableQuickFind>false</EnableQuickFind><EnableViewPicker>false</EnableViewPicker><ViewIds>" + field.ViewId + "</ViewIds ><EnableJumpBar>false</EnableJumpBar><ChartGridMode>Grid</ChartGridMode><VisualizationId/><IsUserChart>false</IsUserChart><EnableChartPicker>false</EnableChartPicker><RecordsPerPage>10</RecordsPerPage></parameters></control></cell></row>");
                    }
                    else
                    {
                        MyStringBuilder.Append("<row><cell id=\"{" + cellId + "}\" showlabel=\"true\" locklevel=\"0\" > <labels><label description=\"" + field.FieldDisplayName + "\" languagecode=\"1033\" /> </labels><control id=\"" + field.ControlId + "\" classid=\"{" + classId + "}\" datafieldname=\"" + field.DataFieldName + "\" disabled=\"false\" /></cell></row>");
                    }
                }

                MyStringBuilder.Append("</rows>");
                MyStringBuilder.Append("</section></sections></column></columns>");
                MyStringBuilder.Append("</tab>");
            }

            var sd = MyStringBuilder.ToString();

            if (!String.IsNullOrEmpty(MyStringBuilder.ToString()))
            {
                using (StringReader reader = new StringReader(sd))
                {
                    string line;

                    while ((line = reader.ReadLine()) != null)
                    {
                        XDocument formTabXml = XDocument.Parse(line.ToString());
                        //Adding this tab to the tabs element
                        var s = formTabXml.Root;
                        bankAccountFormXml.Root.Element("tabs").Add(formTabXml.Root);
                    }
                    //Updateing the entity form definition
                    bankAccountMainForm.FormXml = bankAccountFormXml.ToString();
                    //saving the bank account form
                    _serviceProxy.Update(bankAccountMainForm);

                    // Customizations must be published after an entity is updated.
                    PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(publishRequest);
                    Console.WriteLine("\nCustomizations were published.");
                }
            }



            return(MyStringBuilder);
        }
        private async Task GetCurrentFormDescription(IOrganizationServiceExtented service, CommonConfiguration commonConfig, SystemForm systemForm)
        {
            string formXml = systemForm.FormXml;

            if (string.IsNullOrEmpty(formXml))
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, SystemForm.Schema.EntityLogicalName, systemForm.Name, SystemForm.Schema.Headers.formxml);
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                return;
            }

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            var descriptor = new SolutionComponentDescriptor(service);

            descriptor.SetSettings(commonConfig);

            var handler = new FormDescriptionHandler(descriptor, new DependencyRepository(service));

            string fileName = EntityFileNameFormatter.GetSystemFormFileName(service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name, "FormDescription", FileExtension.txt);
            string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

            try
            {
                XElement doc = XElement.Parse(formXml);

                string desc = await handler.GetFormDescriptionAsync(doc, systemForm.ObjectTypeCode, systemForm.Id, systemForm.Name, systemForm.FormattedValues[SystemForm.Schema.Attributes.type]);

                File.WriteAllText(filePath, desc, new UTF8Encoding(false));

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, SystemForm.Schema.EntityLogicalName, systemForm.Name, "FormDescription", filePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);

                service.TryDispose();
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }
        }
Ejemplo n.º 19
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();
            }
        }
 private Task OpenInWebSystemFormXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, SystemForm systemForm)
 {
     return(Task.Run(() =>
     {
         service.UrlGenerator.OpenSolutionComponentInWeb(ComponentType.SystemForm, systemForm.Id);
         service.TryDispose();
     }));
 }
 private Task GetCurrentSystemFormXmlAsync(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, SystemForm systemForm)
 {
     return(Task.Run(() => GetCurrentSystemFormXml(service, commonConfig, systemForm)));
 }
        private void GetCurrentSystemFormJson(IOrganizationServiceExtented service, CommonConfiguration commonConfig, SystemForm systemForm)
        {
            string formJson = systemForm.FormJson;

            if (string.IsNullOrEmpty(formJson))
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, SystemForm.Schema.EntityLogicalName, systemForm.Name, SystemForm.Schema.Headers.formjson);
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                return;
            }

            formJson = ContentComparerHelper.FormatJson(formJson);

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string currentFileName = EntityFileNameFormatter.GetSystemFormFileName(service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name, SystemForm.Schema.Headers.formjson, FileExtension.json);
            string currentFilePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(currentFileName));

            try
            {
                File.WriteAllText(currentFilePath, formJson, new UTF8Encoding(false));

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, SystemForm.Schema.EntityLogicalName, systemForm.Name, SystemForm.Schema.Headers.formjson, currentFilePath);
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }

            this._iWriteToOutput.PerformAction(service.ConnectionData, currentFilePath);

            service.TryDispose();
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateImageAttributeDemoEntity()
        {
            //Create a Custom entity
            CreateEntityRequest createrequest = new CreateEntityRequest
            {
                //Define the entity
                Entity = new EntityMetadata
                {
                    SchemaName            = _customEntityName,
                    DisplayName           = new Label("Image Attribute Demo", 1033),
                    DisplayCollectionName = new Label("Image Attribute Demos", 1033),
                    Description           = new Label("An entity created by an SDK sample to demonstrate how to upload and retrieve entity images.", 1033),
                    OwnershipType         = OwnershipTypes.UserOwned,
                    IsActivity            = false,
                },

                // Define the primary attribute for the entity
                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = "sample_Name",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 100,
                    FormatName    = StringFormatName.Text,
                    DisplayName   = new Label("Name", 1033),
                    Description   = new Label("The primary attribute for the Image Attribute Demo entity.", 1033)
                }
            };

            _serviceProxy.Execute(createrequest);
            Console.WriteLine("The Image Attribute Demo entity has been created.");

            //Create an Image attribute for the custom entity
            // Only one Image attribute can be added to an entity that doesn't already have one.
            CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest
            {
                EntityName = _customEntityName.ToLower(),
                Attribute  = new ImageAttributeMetadata
                {
                    SchemaName = "EntityImage", //The name is always EntityImage
                    //Required level must be AttributeRequiredLevel.None
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    DisplayName   = new Label("Image", 1033),
                    Description   = new Label("An image to show with this demonstration.", 1033)
                }
            };

            _serviceProxy.Execute(createEntityImageRequest);
            Console.WriteLine("The Image attribute has been created.");

            //<snippetEntityImages5>
            QueryExpression qe = new QueryExpression("systemform");

            qe.Criteria.AddCondition("type", ConditionOperator.Equal, 2); //main form
            qe.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, _customEntityName.ToLower());
            qe.ColumnSet.AddColumn("formxml");

            SystemForm ImageAttributeDemoMainForm = (SystemForm)_serviceProxy.RetrieveMultiple(qe).Entities[0];

            XDocument ImageAttributeDemoMainFormXml = XDocument.Parse(ImageAttributeDemoMainForm.FormXml);

            //Set the showImage attribute so the entity image will be displayed
            ImageAttributeDemoMainFormXml.Root.SetAttributeValue("showImage", true);

            //Updating the entity form definition
            ImageAttributeDemoMainForm.FormXml = ImageAttributeDemoMainFormXml.ToString();

            _serviceProxy.Update(ImageAttributeDemoMainForm);
            //</snippetEntityImages5>
            Console.WriteLine("The Image Attribute Demo main form has been updated to show images.");


            PublishXmlRequest pxReq1 = new PublishXmlRequest {
                ParameterXml = String.Format(@"
   <importexportxml>
    <entities>
     <entity>{0}</entity>
    </entities>
   </importexportxml>", _customEntityName.ToLower())
            };

            _serviceProxy.Execute(pxReq1);

            Console.WriteLine("The Image Attribute Demo entity was published");
        }
Ejemplo n.º 24
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;
            }
        }
Ejemplo n.º 25
0
        //<snippetCreateUpdateEntityMetadata12>
        /// <summary>
        /// Updates the formXml to add a new tab containing the fields added by this sample.
        /// <param name="entityLogicalName">The logical name of the new_bankaccount entity used in this sample</param>
        /// </summary>
        public void UpdateEntityForm(String entityLogicalName)
        {
            QueryExpression qe = new QueryExpression("systemform");

            qe.Criteria.AddCondition("type", ConditionOperator.Equal, 2);                           //main form
            qe.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, entityLogicalName); //for new_bankaccount entity
            qe.ColumnSet.AddColumn("formxml");
            //Retrieve the first main entity form for this entity
            SystemForm bankAccountMainForm = (SystemForm)_serviceProxy.RetrieveMultiple(qe).Entities[0];

            XDocument bankAccountFormXml = XDocument.Parse(bankAccountMainForm.FormXml);

            //Set the showImage attribute so the entity image will be displayed
            bankAccountFormXml.Root.SetAttributeValue("showImage", true);

            // Definition of a custom tab containing the custom attributes created in this sample
            String formTabXmlString = @"<tab name=""custom_attributes""
       id=""{824792c4-ea85-1504-40e2-b780b26dc6ab}""
       IsUserDefined=""0""
       locklevel=""0""
       showlabel=""true""
       expanded=""true"">
   <labels>
    <label description=""Custom Attributes""
           languagecode=""1033"" />
   </labels>
   <columns>
    <column width=""100%"">
     <sections>
      <section name=""custom_section""
               showlabel=""false""
               showbar=""false""
               locklevel=""0""
               id=""{9bda81ec-e41b-7a4d-08b4-4536c5862ce1}""
               IsUserDefined=""0""
               layout=""varwidth""
               columns=""1""
               labelwidth=""115""
               celllabelalignment=""Left""
               celllabelposition=""Left"">
       <labels>
        <label description=""Section""
               languagecode=""1033"" />
       </labels>
       <rows>
        <row>
         <cell id=""{04b95931-78c7-6913-a005-922d20e521b7}""
               showlabel=""true""
               locklevel=""0"">
          <labels>
           <label description=""Account Owner""
                  languagecode=""1033"" />
          </labels>
          <control id=""new_parent_contactid""
                   classid=""{270BD3DB-D9AF-4782-9025-509E298DEC0A}""
                   datafieldname=""new_parent_contactid""
                   disabled=""false"" />
         </cell>
        </row>
        <row>
         <cell id=""{6e5975d3-64b5-14eb-00e4-064e3dd298b9}""
               showlabel=""true""
               locklevel=""0"">
          <labels>
           <label description=""Bank Name""
                  languagecode=""1033"" />
          </labels>
          <control id=""new_bankname""
                   classid=""{4273EDBD-AC1D-40d3-9FB2-095C621B552D}""
                   datafieldname=""new_bankname""
                   disabled=""false"" />
         </cell>
        </row>
        <row>
         <cell id=""{3b436dba-6156-42e9-697b-e275d373505b}""
               showlabel=""true""
               locklevel=""0"">
          <labels>
           <label description=""Balance""
                  languagecode=""1033"" />
          </labels>
          <control id=""new_balance""
                   classid=""{533B9E00-756B-4312-95A0-DC888637AC78}""
                   datafieldname=""new_balance""
                   disabled=""false"" />
         </cell>
        </row>
        <row>
         <cell id=""{0e9a3d8a-bd69-71ad-4ca4-2dcd10858719}""
               showlabel=""true""
               locklevel=""0"">
          <labels>
           <label description=""Date""
                  languagecode=""1033"" />
          </labels>
          <control id=""new_checkeddate""
                   classid=""{5B773807-9FB2-42db-97C3-7A91EFF8ADFF}""
                   datafieldname=""new_checkeddate""
                   disabled=""false"" />
         </cell>
        </row>
       </rows>
      </section>
     </sections>
    </column>
   </columns>
  </tab>";

            XDocument formTabXml = XDocument.Parse(formTabXmlString);

            //Adding this tab to the tabs element
            bankAccountFormXml.Root.Element("tabs").Add(formTabXml.Root);
            //Updateing the entity form definition
            bankAccountMainForm.FormXml = bankAccountFormXml.ToString();
            //saving the bank account form
            _serviceProxy.Update(bankAccountMainForm);
        }
Ejemplo n.º 26
0
        public AggregateRoot Retrieve(QueryBase request, bool ignorePermissions = false)
        {
            //查询单个实体,查询列表

            //var entity = args.EntityId.Equals(Guid.Empty) ? _entityFinder.FindByName(args.EntityName) : _entityFinder.FindById(args.EntityId);

            //var record = _dataFinder.RetrieveById(entity.Name, args.RecordId.Value);

            string entityname = "";
            Guid?  recordId   = null;
            Guid?  formId     = null;

            _aggregateRoot.MainEntity = _dataFinder.RetrieveById(entityname, recordId.Value);

            //表单列表
            SystemForm formEntity = null;

            formEntity = _systemFormFinder.FindById(formId.Value);
            FormBuilder formBuilder = new FormBuilder(formEntity.FormConfig);

            List <PanelDescriptor> panelDescriptors = formBuilder.Form.Panels;

            foreach (var panel in panelDescriptors)
            {
                foreach (var section in panel.Sections)
                {
                    foreach (var row in section.Rows)
                    {
                        foreach (var cell in row.Cells)
                        {
                            if (cell.Control.ControlType == FormControlType.SubGrid)
                            {
                                var param = (SubGridParameters)cell.Control.Parameters;

                                //param.ViewId;
                                //param.RelationshipName

                                var queryView = _queryViewFinder.FindById(Guid.Parse(param.ViewId));
                                if (queryView != null)
                                {
                                    //if (!queryView.IsDefault && queryView.IsAuthorization)
                                    {
                                    }

                                    FetchDescriptor fetch = new FetchDescriptor
                                    {
                                        //Page = model.Page,
                                        //PageSize = model.PageSize,
                                        //FetchConfig = queryView.FetchConfig,
                                        //GetAll = !model.PagingEnabled
                                    };

                                    //排序,过滤
                                    var relationship = _relationShipFinder.FindByName(param.RelationshipName);
                                    var filter       = new FilterExpression();
                                    var condition    = new ConditionExpression(relationship.ReferencingAttributeName, ConditionOperator.Equal, recordId.Value);
                                    filter.AddCondition(condition);
                                    fetch.Filter = filter;
                                    fetch.User   = User;
                                    var datas = _fetchService.Execute(fetch);
                                    //_aggregateRoot.grids.Add("", datas.Items);
                                }
                            }
                        }
                    }
                }
            }
            return(_aggregateRoot);
        }
        private async Task UpdateSystemFormXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, SystemForm systemForm)
        {
            {
                string fieldTitle = SystemForm.Schema.Headers.formxml;

                string formXml = systemForm.FormXml;

                if (!string.IsNullOrEmpty(formXml))
                {
                    commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

                    string fileNameBackUp = EntityFileNameFormatter.GetSystemFormFileName(service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name, fieldTitle + " BackUp", FileExtension.xml);
                    string filePathBackUp = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileNameBackUp));

                    try
                    {
                        formXml = ContentComparerHelper.FormatXmlByConfiguration(
                            formXml
                            , commonConfig
                            , XmlOptionsControls.FormXmlOptions
                            , schemaName: AbstractDynamicCommandXsdSchemas.FormXmlSchema
                            , formId: systemForm.Id
                            , entityName: systemForm.ObjectTypeCode
                            );

                        File.WriteAllText(filePathBackUp, formXml, new UTF8Encoding(false));

                        this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, SystemForm.Schema.EntitySchemaName, systemForm.Name, fieldTitle, filePathBackUp);
                    }
                    catch (Exception ex)
                    {
                        this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
                    }
                }
                else
                {
                    this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, SystemForm.Schema.EntitySchemaName, systemForm.Name, fieldTitle);
                    this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                }
            }

            var newText = doc.ToString(SaveOptions.DisableFormatting);

            var updateEntity = new SystemForm
            {
                Id = systemForm.Id,
            };

            updateEntity.Attributes[SystemForm.Schema.Attributes.formxml] = newText;

            await service.UpdateAsync(updateEntity);

            var repositoryPublish = new PublishActionsRepository(service);

            _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingSystemFormFormat3, service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name);
            await repositoryPublish.PublishDashboardsAsync(new[] { systemForm.Id });

            if (systemForm.ObjectTypeCode.IsValidEntityName())
            {
                _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingEntitiesFormat2, service.ConnectionData.Name, systemForm.ObjectTypeCode);
                await repositoryPublish.PublishEntitiesAsync(new[] { systemForm.ObjectTypeCode });
            }

            service.TryDispose();
        }
        public void ProcessAddControlOnFormAction()
        {
            var  pluginContext = this.PluginContext;
            var  ctrl          = this.control;
            Guid formId;

            if (!Guid.TryParse(ctrl.FormId, out formId))
            {
                throw new ArgumentException(nameof(ctrl.FormId));
            }

            ctrl.EntityLogicalName = ctrl.EntityLogicalName.Trim().ToLowerInvariant();
            var orgCtx = pluginContext.OrgCtx;

            var formXmlString =
                orgCtx.SystemFormSet.Where(r => r.FormId == formId && r.ObjectTypeCode == ctrl.EntityLogicalName)
                .Select(r => r.FormXml)
                .FirstOrDefault();

            if (string.IsNullOrWhiteSpace(formXmlString))
            {
                throw new NullReferenceException(nameof(formXmlString));
            }

            ctrl.TabName             = ctrl.TabName.Trim().ToLowerInvariant();
            ctrl.WebResource         = ctrl.WebResource.Trim();
            ctrl.FormId              = ctrl.FormId.Trim().ToLowerInvariant();
            ctrl.ItemSetName         = ctrl.ItemSetName.Trim();
            ctrl.NewSectionLabel     = ctrl.NewSectionLabel.Trim();
            ctrl.NewSectionName      = ctrl.NewSectionName.Trim();
            ctrl.SavingAttributeName = ctrl.SavingAttributeName.Trim().ToLowerInvariant();

            var formXml = XDocument.Parse(formXmlString);

            this.ValidateSectionName(formXml, ctrl.NewSectionName);

            // ReSharper disable PossibleNullReferenceException
            var xTabs = formXml.Root.Element("tabs").Elements("tab").ToList();
            // ReSharper restore PossibleNullReferenceException
            var xTab = xTabs.FirstOrDefault(
                r =>
            {
                var xAttribute = r.Attribute("name");
                return(xAttribute != null &&
                       xAttribute.Value.Equals(ctrl.TabName, StringComparison.InvariantCultureIgnoreCase));
            });

            if (xTab == null)
            {
                xTab = xTabs.FirstOrDefault(
                    r =>
                {
                    var xAttribute = r.Attribute("id");
                    return(xAttribute != null &&
                           xAttribute.Value.Equals(ctrl.TabName, StringComparison.InvariantCultureIgnoreCase));
                });
            }

            if (xTab == null)
            {
                throw new InvalidPluginExecutionException($"{ctrl.TabName} tab is not found.");
            }

            var xColumns       = xTab.Elements("columns").Elements("column");
            var controlSection = this.BuildControlSection();

            const int AddBefore = 10;
            const int AddFirst  = 30;

            var location = ctrl.NewSectionLocation;

            if (location == AddFirst)
            {
                // ReSharper disable PossibleNullReferenceException
                var xFirstColumn   = xColumns.FirstOrDefault();
                var columnSections = xFirstColumn.Element("sections");
                columnSections.Add(controlSection);
                // ReSharper restore PossibleNullReferenceException
            }
            else
            {
                var sectionName = ctrl.NearSectionName;
                if (string.IsNullOrWhiteSpace(sectionName))
                {
                    throw new NullReferenceException(nameof(sectionName));
                }

                sectionName = sectionName.Trim();
                var section = formXml.XPathSelectElement($@"//section[@name=""{sectionName}""]");
                if (section == null)
                {
                    section = formXml.XPathSelectElement($@"//section[@id=""{sectionName}""]");
                    if (section == null)
                    {
                        throw new InvalidPluginExecutionException($"The '{sectionName}' section is not found on the form.");
                    }
                }

                if (location == AddBefore)
                {
                    section.AddBeforeSelf(controlSection);
                }
                else
                {
                    section.AddAfterSelf(controlSection);
                }
            }

            var form = new SystemForm
            {
                FormId  = formId,
                FormXml = formXml.ToString()
            };

            pluginContext.Service.Update(form);
            MetadataUtils.PublishEntity(pluginContext.Service, this.control.EntityLogicalName);
        }
        private async Task GetCurrentEntityDescription(IOrganizationServiceExtented service, CommonConfiguration commonConfig, SystemForm systemForm)
        {
            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string fileName = EntityFileNameFormatter.GetSystemFormFileName(service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name, EntityFileNameFormatter.Headers.EntityDescription, FileExtension.txt);
            string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

            try
            {
                await EntityDescriptionHandler.ExportEntityDescriptionAsync(filePath, systemForm, service.ConnectionData);

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionExportedEntityDescriptionFormat3
                                                   , service.ConnectionData.Name
                                                   , systemForm.LogicalName
                                                   , filePath
                                                   );
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);

            service.TryDispose();
        }
Ejemplo n.º 30
0
        public IActionResult GetCompleteInfo(EntityFormModel args)
        {
            string nonePermissionFields = null, form = null, records = null;

            if (args.EntityId.Equals(Guid.Empty) && args.EntityName.IsEmpty())
            {
                return(NotFound());
            }
            var entity = args.EntityId.Equals(Guid.Empty) ? _entityFinder.FindByName(args.EntityName) : _entityFinder.FindById(args.EntityId);

            if (entity == null)
            {
                return(NotFound());
            }
            args.EntityId   = entity.EntityId;
            args.EntityName = entity.Name;
            EditRecordModel m = new EditRecordModel
            {
                EntityMetaData     = entity,
                EntityId           = args.EntityId,
                RelationShipName   = args.RelationShipName,
                ReferencedRecordId = args.ReferencedRecordId
            };

            if (args.RecordId.HasValue && !args.RecordId.Value.Equals(Guid.Empty))
            {
                var record = _dataFinder.RetrieveById(entity.Name, args.RecordId.Value);
                if (record == null || record.Count == 0)
                {
                    return(NotFound());
                }
                var fileAttributes = _attributeFinder.FindByEntityId(entity.EntityId).Where(n => n.DataFormat.IsCaseInsensitiveEqual("fileupload"));
                foreach (var item in fileAttributes)
                {
                    if (record.GetStringValue(item.Name).IsNotEmpty())
                    {
                        record[item.Name] = string.Empty;
                    }
                    else
                    {
                        record.Remove(item.Name);
                    }
                }
                m.Entity    = record;
                m.RecordId  = args.RecordId;
                m.FormState = FormState.Update;
                if (m.Entity.GetIntValue("statecode", -1) == 0)
                {
                    m.FormState = FormState.Disabled;
                    //model.ReadOnly = true;
                }
            }
            else if (args.CopyId.HasValue && !args.CopyId.Value.Equals(Guid.Empty))
            {
                var record = _dataFinder.RetrieveById(entity.Name, args.CopyId.Value);
                if (record == null || record.Count == 0)
                {
                    return(NotFound());
                }
                var fileAttributes = _attributeFinder.FindByEntityId(entity.EntityId).Where(n => n.DataFormat.IsCaseInsensitiveEqual("fileupload"));
                foreach (var item in fileAttributes)
                {
                    record.Remove(item.Name);
                }
                record.RemoveKeys(AttributeDefaults.SystemAttributes);
                m.Entity = record;
                //m.RecordId = model.RecordId;
                m.FormState = FormState.Create;
            }
            else
            {
                //ViewData["record"] = "{}";
                m.FormState = FormState.Create;
            }
            m.ReadOnly = args.ReadOnly;
            var        isCreate   = !args.RecordId.HasValue || args.RecordId.Value.Equals(Guid.Empty);
            SystemForm formEntity = null;

            //workflow
            if (!isCreate && m.EntityMetaData.WorkFlowEnabled && m.Entity.GetGuidValue("workflowid").Equals(Guid.Empty))
            {
                var processState = m.Entity.GetIntValue("processstate", -1);
                if (processState == (int)WorkFlowProcessState.Processing)// || processState == (int)WorkFlowProcessState.Passed)
                {
                    m.ReadOnly  = true;
                    m.FormState = FormState.ReadOnly;
                    var instances             = _workFlowInstanceService.Query(n => n.Take(1).Where(f => f.EntityId == m.EntityId.Value && f.ObjectId == m.RecordId.Value).Sort(s => s.SortDescending(f => f.CreatedOn)));
                    WorkFlowInstance instance = null;
                    if (instances.NotEmpty())
                    {
                        instance = instances.First();
                    }
                    if (instance != null)
                    {
                        var processInfo = _workFlowProcessFinder.GetCurrentStep(instance.WorkFlowInstanceId, CurrentUser.SystemUserId);
                        if (processInfo != null)
                        {
                            if (!processInfo.FormId.Equals(Guid.Empty))
                            {
                                formEntity = _systemFormFinder.FindById(processInfo.FormId);
                            }
                        }
                    }
                }
                m.WorkFlowProcessState = processState;
            }
            if (formEntity == null)
            {
                if (args.FormId.HasValue && !args.FormId.Value.Equals(Guid.Empty))
                {
                    formEntity = _systemFormFinder.FindById(args.FormId.Value);
                    if (formEntity.StateCode != RecordState.Enabled)
                    {
                        formEntity = null;
                    }
                }
                else
                {
                    //获取实体默认表单
                    formEntity = _systemFormFinder.FindEntityDefaultForm(args.EntityId);
                }
            }
            if (formEntity == null)
            {
                return(JError(T["notfound_defaultform"]));
            }
            m.FormInfo = formEntity;
            m.FormId   = formEntity.SystemFormId;
            FormBuilder formBuilder = new FormBuilder(formEntity.FormConfig);

            _formService.Init(formEntity);
            //表单可用状态
            if (!isCreate && m.FormState != FormState.Disabled && formBuilder.Form.FormRules.NotEmpty())
            {
                if (_systemFormStatusSetter.IsDisabled(formBuilder.Form.FormRules, m.Entity))
                {
                    m.FormState = FormState.Disabled;
                }
            }
            //获取所有字段信息
            m.AttributeList = _formService.AttributeMetaDatas;
            //获取字段权限
            if (!CurrentUser.IsSuperAdmin && m.AttributeList.Count(n => n.AuthorizationEnabled) > 0)
            {
                var securityFields = m.AttributeList.Where(n => n.AuthorizationEnabled).Select(f => f.AttributeId)?.ToList();
                if (securityFields.NotEmpty())
                {
                    //无权限的字段
                    var noneRead = _systemUserPermissionService.GetNoneReadFields(CurrentUser.SystemUserId, securityFields);
                    var noneEdit = _systemUserPermissionService.GetNoneEditFields(CurrentUser.SystemUserId, securityFields);
                    //移除无读取权限的字段内容
                    if (m.Entity.NotEmpty())
                    {
                        foreach (var item in noneRead)
                        {
                            m.Entity.Remove(m.AttributeList.Find(n => n.AttributeId == item).Name);
                        }
                    }
                    var obj = new { noneread = noneRead, noneedit = noneEdit };
                    nonePermissionFields = obj.SerializeToJson();
                }
            }
            else
            {
                nonePermissionFields = "[]";
            }
            var _form = formBuilder.Form;

            m.Form = _form;
            form   = _formService.Form.SerializeToJson(false);
            //buttons
            var buttons = _ribbonbuttonFinder.Find(m.EntityId.Value, RibbonButtonArea.Form);

            if (formEntity.IsCustomButton && formEntity.CustomButtons.IsNotEmpty())
            {
                List <Guid> buttonid = new List <Guid>();
                buttonid = buttonid.DeserializeFromJson(formEntity.CustomButtons);
                buttons.RemoveAll(x => !buttonid.Contains(x.RibbonButtonId));
            }
            if (buttons.NotEmpty())
            {
                buttons         = buttons.OrderBy(x => x.DisplayOrder).ToList();
                m.RibbonButtons = buttons;
                _ribbonButtonStatusSetter.Set(m.RibbonButtons, m.FormState, m.Entity);
            }
            if (isCreate)
            {
                var rep = _roleObjectAccessEntityPermissionService.FindUserPermission(m.EntityMetaData.Name, CurrentUser.LoginName, AccessRightValue.Create);
                m.HasBasePermission = rep != null && rep.AccessRightsMask != EntityPermissionDepth.None;
            }
            else
            {
                var rep = _roleObjectAccessEntityPermissionService.FindUserPermission(m.EntityMetaData.Name, CurrentUser.LoginName, AccessRightValue.Update);
                m.HasBasePermission = rep != null && rep.AccessRightsMask != EntityPermissionDepth.None;
            }
            m.SnRule = _serialNumberRuleFinder.FindByEntityId(args.EntityId);
            if (m.SnRule != null && m.Entity.NotEmpty() && args.CopyId.HasValue)
            {
                m.Entity.SetAttributeValue(m.SnRule.AttributeName, null);
            }
            records                  = m.Entity.SerializeToJson();
            m.StageId                = args.StageId;
            m.BusinessFlowId         = args.BusinessFlowId;
            m.BusinessFlowInstanceId = args.BusinessFlowInstanceId;

            return(JOk(new { EditRecord = m, NonePermissionFields = nonePermissionFields, Form = form, Record = records }));
        }
Ejemplo n.º 31
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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // 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;
            }
        }