Esempio n. 1
2
        /// <summary>
        /// Pre-Validation method will default the values of contact preference fields
        /// </summary>
        private static void PreValidateContactCreate(IPluginExecutionContext context, IOrganizationService service)
        {
            Entity contactEntity = (Entity)context.InputParameters["Target"];
            OptionSetValue doNotAllow = new OptionSetValue(1);

            contactEntity.SetAttribute("donotemail", doNotAllow);
            contactEntity.SetAttribute("donotpostalmail", doNotAllow);
            contactEntity.SetAttribute("donotbulkemail", doNotAllow);
            contactEntity.SetAttribute("donotfax", doNotAllow);

            // Get a count of child phone call entities associated with this Contact
            QueryExpression query = new QueryExpression();
            query.EntityName = "phonecall";
            query.ColumnSet = new ColumnSet(allColumns: true);
            query.Criteria = new FilterExpression();
            query.Criteria.AddCondition(new ConditionExpression("regardingobjectid", ConditionOperator.Equal, context.PrimaryEntityId));

            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            IEnumerable<Entity> results = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;
            if (results.Any())
            {
                // Do not default contact preference for phone if there are already some associated phone calls
                // Why? Because! Testing!
                contactEntity.SetAttribute("donotphone", doNotAllow);
            }
        }
Esempio n. 2
1
        private static Guid FindPluginAssembly(OrganizationService service, string assemblyName)
        {
            var query = new QueryExpression
            {
                EntityName = "pluginassembly",
                ColumnSet = null,
                Criteria = new FilterExpression()
            };
            query.Criteria.AddCondition("name", ConditionOperator.Equal, assemblyName);

            var request = new RetrieveMultipleRequest
            {
                Query = query
            };

            var response = (RetrieveMultipleResponse)service.Execute(request);

            if (response.EntityCollection.Entities.Count == 1)
            {
                var id = response.EntityCollection[0].GetAttributeValue<Guid>("pluginassemblyid");
                _logger.Log(LogLevel.Debug, () => string.Format("Found id {0} for assembly", id));

                return id;
            }

            return Guid.Empty;
        }
        public static void When_a_query_by_attribute_is_executed_when_one_attribute_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            var account = new Account() {Id = Guid.NewGuid(), Name = "Test"};
            var account2 = new Account() { Id = Guid.NewGuid(), Name = "Other account!" };
            context.Initialize(new List<Entity>()
            {
                account, account2
            });

            var service = context.GetFakedOrganizationService();

            QueryByAttribute query = new QueryByAttribute();
            query.Attributes.AddRange(new string[] { "name" });
            query.ColumnSet = new ColumnSet(new string[] { "name" });
            query.EntityName = Account.EntityLogicalName;
            query.Values.AddRange(new object[] { "Test" });

            //Execute using a request to test the OOB (XRM) message contracts
            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            Collection<Entity> entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;

            Assert.True(entityList.Count == 1);
            Assert.Equal(entityList[0]["name"].ToString(), "Test");
        }
        /// <summary>
        /// Gets the entity.
        /// </summary>
        /// <param name="logicalName">Name of the logical.</param>
        /// <param name="fieldName">Name of the field.</param>
        /// <param name="value">The value.</param>
        /// <param name="onlyActive">if set to <c>true</c> [only active].</param>
        /// <param name="columns">The columns.</param>
        public override ICrmEntity GetEntity(string logicalName, string fieldName, string value, bool onlyActive, string[] columns)
        {
            var filters = new List <ConditionExpression> {
                new ConditionExpression {
                    AttributeName = fieldName, Operator = ConditionOperator.Equal, Values = new object[] { value }
                }
            };

            if (onlyActive)
            {
                filters.Add(new ConditionExpression {
                    AttributeName = "statecode", Operator = ConditionOperator.Equal, Values = new object[] { "Active" }
                });
            }

            var filterExpression = new FilterExpression {
                FilterOperator = LogicalOperator.And, Conditions = filters.ToArray()
            };

            var request = new RetrieveMultipleRequest
            {
                Query =
                    new QueryExpression
                {
                    ColumnSet = columns == null ? (ColumnSetBase) new AllColumns() : new ColumnSet {
                        Attributes = columns
                    },
                    EntityName = logicalName,
                    PageInfo   = new PagingInfo {
                        Count = 1, PageNumber = 1
                    },
                    Criteria = filterExpression
                },
                ReturnDynamicEntities = true
            };

            var response = (RetrieveMultipleResponse)this.crmService.Execute(request);

            var businessEntityCollection = response.BusinessEntityCollection;

            if (businessEntityCollection == null || businessEntityCollection.BusinessEntities == null || businessEntityCollection.BusinessEntities.Length <= 0)
            {
                return(null);
            }

            var dynamicEntity = businessEntityCollection.BusinessEntities[0] as DynamicEntity;

            return(dynamicEntity == null ? null : new CrmEntityAdapter(this, dynamicEntity));
        }
        public static List <ViewDetail> GetListViews(IOrganizationService service, string entityLogicalName, int entityTypeCode, bool systemView)
        {
            // Retrieve Views
            QueryExpression mySavedQuery = new QueryExpression
            {
                ColumnSet  = new ColumnSet("savedqueryid", "name", "querytype", "isdefault", "returnedtypecode", "fetchxml"),
                EntityName = "savedquery",
                Criteria   = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "querytype",
                            Operator      = ConditionOperator.Equal,
                            Values        = { 0 }
                        },
                        new ConditionExpression
                        {
                            AttributeName = "returnedtypecode",
                            Operator      = ConditionOperator.Equal,
                            Values        = { entityTypeCode }
                        },
                        new ConditionExpression
                        {
                            AttributeName = "isquickfindquery",
                            Operator      = ConditionOperator.Equal,
                            Values        = { false }
                        }
                    }
                }
            };


            RetrieveMultipleRequest retrieveSavedQueriesRequest = new RetrieveMultipleRequest {
                Query = mySavedQuery
            };

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

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

            return(savedQueries.Select(x => new ViewDetail
            {
                Name = x.GetAttributeValue <string>("name"),
                FetchXML = x.GetAttributeValue <string>("fetchxml"),
                Savedqueryid = x.Id
            }).ToList());
        }
Esempio n. 6
0
        public List <T> ListarAtivosVencidosCumpridos(Intelbras.CRM2013.Domain.Enum.CompromissoPrograma.TipoMonitoramento tipoMonitoramento, Domain.Model.StatusCompromissos cumprido, Domain.Model.StatusCompromissos cumpridoForaPrazo)
        {
            var query = GetQueryExpression <T>(true);

            string strFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='itbc_compdocanal'>
                                <attribute name='itbc_compdocanalid' />
                                <attribute name='itbc_name' />
                                <attribute name='itbc_validade' />
                                <attribute name='itbc_statuscompromissosid' />
                                <attribute name='itbc_compdoprogid' />
                                <attribute name='itbc_canalid' />
                                <attribute name='itbc_businessunitid' />
                                <order attribute='itbc_name' descending='false' />
                                <filter type='and'>
                                  <condition attribute='statuscode' operator='eq' value='1' />
                                  <filter type='or'>
                                    <condition attribute='itbc_validade' operator='on-or-before' value='{3}' />
                                    <condition attribute='itbc_validade' operator='null' />
                                  </filter>
                                  <filter type='or'>
                                    <condition attribute='itbc_statuscompromissosid' operator='null' />
                                    <condition attribute='itbc_statuscompromissosid' operator='in'>
                                      <value uiname='Cumprido' uitype='itbc_statuscompromissos'>{1}</value>
                                      <value uiname='Cumprido Fora do Prazo' uitype='itbc_statuscompromissos'>{2}</value>
                                    </condition>
                                  </filter>
                                </filter>
                                <link-entity name='itbc_compromissos' from='itbc_compromissosid' to='itbc_compdoprogid' alias='aa'>
                                  <filter type='and'>
                                    <condition attribute='itbc_tipodemonitoramento' operator='eq' value='{0}' />
                                  </filter>
                                </link-entity>
                              </entity>
                            </fetch>";

            strFetchXml = string.Format(strFetchXml,
                                        (int)tipoMonitoramento,
                                        cumprido.ID.Value,
                                        cumpridoForaPrazo.ID.Value,
                                        DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd"));

            RetrieveMultipleRequest retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(strFetchXml.ToString())
            };

            return((List <T>) this.RetrieveMultiple(retrieveMultiple.Query).List);
        }
Esempio n. 7
0
        private Dictionary <string, OrganizationRequest> GetQueryOrgRequests(Dictionary <string, QueryExpression> queriesToBeProcessed)
        {
            Dictionary <string, OrganizationRequest> orgRequests = new Dictionary <string, OrganizationRequest>();


            foreach (var queryToBeProcessed in queriesToBeProcessed)
            {
                RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest {
                    Query = queryToBeProcessed.Value
                };
                orgRequests.Add(queryToBeProcessed.Key, retrieveMultipleRequest);
            }

            return(orgRequests);
        }
Esempio n. 8
0
 public RetrieveMultipleResponse <TicketSearchResult> RetrieveMultiple(RetrieveMultipleRequest <TicketSpecification> request)
 {
     return(AllTickets()
            .Satisfy(request.Specification)
            .Select(t => new TicketSearchResult()
     {
         AssignedTo = t.AssignedTo,
         IsOpen = t.IsOpen,
         TicketId = t.TicketId,
         TicketTypeId = t.TicketTypeId,
         Title = t.Title
     })
            .SatisfyPaging(request.PageIndex, request.PageSize)
            .ToResponse(request.PageSize));
 }
Esempio n. 9
0
        public List <MetaDetalhadadaUnidadeporProduto> ListarValoresPorUnidadeNegocio(Guid unidadeNegocioId, int ano, Domain.Enum.OrcamentodaUnidadeDetalhadoporProduto.Mes mes)
        {
            var lista = new List <MetaDetalhadadaUnidadeporProduto>();

            string fetch = @"<fetch aggregate='true' no-lock='true' >
                              <entity name='itbc_potencialdetalhadosuper_produto' >
                                <attribute name='itbc_potencialplanejado' alias='valor_planejado' aggregate='sum' />
                                <attribute name='itbc_potencialrealizado' alias='valor_realizado' aggregate='sum' />
                                <attribute name='itbc_produtoid' alias='produto' groupby='true' />
                                <attribute name='itbc_qtdeplanejada' alias='quantidade_planejada' aggregate='sum' />
                                <attribute name='itbc_qtderealizada' alias='quantidade_realizada' aggregate='sum' />
                                <filter type='and' >
                                  <condition attribute='itbc_ano' operator='eq' value='{0}' />
                                  <condition attribute='itbc_mes' operator='eq' value='{2}' />
                                  <condition attribute='itbc_unidade_negociosid' operator='eq' value='{1}' />
                                </filter>
                              </entity>
                            </fetch>";

            fetch = string.Format(fetch, ano, unidadeNegocioId, (int)mes);

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(fetch)
            };

            EntityCollection collection = ((RetrieveMultipleResponse)this.Execute(retrieveMultiple)).EntityCollection;

            foreach (var item in collection.Entities)
            {
                var produto = ((EntityReference)((AliasedValue)item.Attributes["produto"]).Value);

                var potencial = new MetaDetalhadadaUnidadeporProduto(OrganizationName, IsOffline, Provider)
                {
                    MetaPlanejada = ((Money)((AliasedValue)item.Attributes["valor_planejado"]).Value).Value,
                    MetaRealizada = ((Money)((AliasedValue)item.Attributes["valor_realizado"]).Value).Value,
                    QtdePlanejada = (decimal)((AliasedValue)item.Attributes["quantidade_planejada"]).Value,
                    QtdeRealizada = (decimal)((AliasedValue)item.Attributes["quantidade_realizada"]).Value,
                    Mes           = (int)mes,
                    Ano           = ano,
                    Produto       = new SDKore.DomainModel.Lookup(produto.Id, produto.Name, produto.LogicalName)
                };

                lista.Add(potencial);
            }

            return(lista);
        }
Esempio n. 10
0
        public List <PotencialdoKAporProduto> ListarValoresPorUnidadeNegocio(Guid unidadeNegocioId, int ano, Domain.Enum.OrcamentodaUnidadeDetalhadoporProduto.Mes mes)
        {
            var lista = new List <PotencialdoKAporProduto>();

            string fetch = @"<fetch aggregate='true' no-lock='true' returntotalrecordcount='true' >
                              <entity name='itbc_metadetalhadadokaporproduto' >
                                <attribute name='itbc_metaplanejada' alias='valor_planejado' aggregate='sum' />
                                <attribute name='itbc_qtdeplanejada' alias='quantidade_planejada' aggregate='sum' />
                                <attribute name='itbc_metarealizada' alias='valor_realizado' aggregate='sum' />
                                <attribute name='itbc_qtderealizada' alias='quantidade_realizado' aggregate='sum' />
                                <filter type='and' >
                                    <condition attribute='itbc_mes' operator='eq' value='{2}' />
                                </filter>
                                <link-entity name='itbc_metadokaporproduto' from='itbc_metadokaporprodutoid' to='itbc_metadokaporprodutoid' link-type='inner' alias='prod' >
                                  <attribute name='itbc_metadokaporprodutoid' alias='id' groupby='true' />
                                  <filter type='and' >
                                    <condition attribute='itbc_ano' operator='eq' value='{0}' />
                                    <condition attribute='itbc_unidade_negociosid' operator='eq' value='{1}' />
                                  </filter>
                                </link-entity>
                              </entity>
                            </fetch>";

            fetch = string.Format(fetch, ano, unidadeNegocioId, mes);

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(fetch)
            };

            EntityCollection collection = ((RetrieveMultipleResponse)this.Execute(retrieveMultiple)).EntityCollection;

            foreach (var item in collection.Entities)
            {
                var potencialProduto = new PotencialdoKAporProduto(OrganizationName, IsOffline, Provider)
                {
                    ID = (Guid)((AliasedValue)(item.Attributes["id"])).Value,
                    PotencialPlanejado = ((Money)((AliasedValue)item.Attributes["valor_planejado"]).Value).Value,
                    PotencialRealizado = ((Money)((AliasedValue)item.Attributes["valor_realizado"]).Value).Value,
                    QtdePlanejada      = (decimal)((AliasedValue)(item.Attributes["quantidade_planejada"])).Value,
                    QtdeRealizada      = (decimal)((AliasedValue)(item.Attributes["quantidade_realizado"])).Value
                };

                lista.Add(potencialProduto);
            }

            return(lista);
        }
        public static void When_a_query_on_lookup_is_executed_with_name_suffixed_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            var user    = new SystemUser {
                Id = Guid.NewGuid(), ["fullname"] = "User"
            };
            var user2 = new SystemUser {
                Id = Guid.NewGuid(), ["fullname"] = "Other user!"
            };
            var account = new Account()
            {
                Id = Guid.NewGuid(), Name = "Test", ["createdby"] = new EntityReference(user.LogicalName, user.Id)
                {
                    Name = user.FullName
                }
            };
            var account2 = new Account()
            {
                Id = Guid.NewGuid(), Name = "Other account!", ["createdby"] = new EntityReference(user.LogicalName, user2.Id)
                {
                    Name = user2.FullName
                }
            };

            context.Initialize(new List <Entity>()
            {
                user, user2, account, account2
            });

            var service = context.GetFakedOrganizationService();

            QueryExpression query = new QueryExpression();

            query.ColumnSet  = new ColumnSet(new string[] { "name" });
            query.EntityName = Account.EntityLogicalName;
            query.Criteria   = new FilterExpression {
                Conditions = { new ConditionExpression("createdbyname", ConditionOperator.Equal, "User") }
            };

            //Execute using a request to test the OOB (XRM) message contracts
            RetrieveMultipleRequest request = new RetrieveMultipleRequest();

            request.Query = query;
            Collection <Entity> entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;

            Assert.True(entityList.Count == 1);
            Assert.Equal(entityList[0]["name"].ToString(), "Test");
        }
Esempio n. 12
0
        public static DynamicEntity SelectLead(CrmService service, Dictionary <string, string> attributeDetails)
        {
            DynamicEntity de = null;

            try
            {
                var conditionExpressions = new List <ConditionExpression>();
                foreach (KeyValuePair <string, string> attr in attributeDetails)
                {
                    var queryCondition = new ConditionExpression
                    {
                        AttributeName = attr.Key,
                        Operator      = ConditionOperator.Equal,
                        Values        = new object[] { attr.Value }
                    };
                    conditionExpressions.Add(queryCondition);
                }

                var filterExpression = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions     = conditionExpressions.ToArray()
                };

                var queryExpression = new QueryExpression
                {
                    EntityName = EntityName.lead.ToString(),
                    ColumnSet  = new AllColumns(),
                    Criteria   = filterExpression
                };

                var request = new RetrieveMultipleRequest {
                    Query = queryExpression, ReturnDynamicEntities = true
                };

                var response = (RetrieveMultipleResponse)service.Execute(request);

                if (response.BusinessEntityCollection.BusinessEntities.Length > 0)
                {
                    de = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0];
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(de);
        }
Esempio n. 13
0
        public void Execute(IServiceProvider serviceProvider)
        {
            //https://msdn.microsoft.com/en-us/library/gg509027.aspx
            //When you use the Update method or UpdateRequest message, do not set the OwnerId attribute on a record unless the owner has actually changed.
            //When you set this attribute, the changes often cascade to related entities, which increases the time that is required for the update operation.
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            tracingService.Trace("Starting SendApplicationInsights at " + DateTime.Now.ToString());
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Obtain the organization service reference.
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            Entity entity = (Entity)context.InputParameters["Target"];

            //Check to see if this is a create of a new employee booking.
            if (context.MessageName == "Create")
            {
                QueryExpression query = new QueryExpression();
                query.ColumnSet  = new ColumnSet(true);
                query.EntityName = "incident";

                //FilterExpression fe = new FilterExpression();
                //fe.FilterOperator = LogicalOperator.And;
                //ConditionExpression ceArea = new ConditionExpression();
                //ceArea.AttributeName = "msft_areaid";
                //ceArea.Operator = ConditionOperator.Equal;
                //ceArea.Values.Add(((EntityReference)entity.Attributes["msft_areaid"]).Id);

                //fe.AddCondition(ceArea);

                //query.Criteria = new FilterExpression();
                //query.Criteria = fe;
                ////Order by Start Arrival Time ascending
                //query.AddOrder("msft_arrivaltimestart", OrderType.Ascending);
                query.NoLock = false;
                RetrieveMultipleRequest request = new RetrieveMultipleRequest();
                request.Query = query;

                tracingService.Trace("Executing the Query for entity {0}", query.EntityName);
                Collection <Entity> entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;
                tracingService.Trace("Returned the Query Response for entity {0}", query.EntityName);
                //Thread.Sleep(180000);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Creates and executes a RetrieveMultipleRequest to CRM
        /// </summary>
        /// <param name="service">The CRM Service</param>
        /// <param name="query">The query to be executed</param>
        /// <param name="totalCount">The total number of records found</param>
        /// <returns>A list of entities retrieved from CRM</returns>
        public static List<Entity> ExecuteQueryExpression(IOrganizationService service, QueryExpression query, out int totalCount)
        {
            RetrieveMultipleRequest multipleRequest = new RetrieveMultipleRequest();
            multipleRequest.Query = query;

            RetrieveMultipleResponse response = (RetrieveMultipleResponse)Execute(service, multipleRequest);
            totalCount = response.EntityCollection.TotalRecordCount;

            List<Entity> dynamicEntities = new List<Entity>();
            foreach (Entity businessEntity in response.EntityCollection.Entities)
            {
                dynamicEntities.Add(businessEntity);
            }

            return dynamicEntities;
        }
Esempio n. 15
0
        public List <MetadoCanalporProduto> ListarValoresPorUnidadeNegocio(Guid unidadeNegocioId, int ano, Guid canalId)
        {
            var lista = new List <MetadoCanalporProduto>();

            string fetch = @"<fetch aggregate='true' no-lock='true' >
                              <entity name='itbc_metadetalhadadocanalporproduto' >
                                <attribute name='itbc_qtderealizada' alias='quantidade_realizado' aggregate='sum' />
                                <attribute name='itbc_metarealizada' alias='valor_realizado' aggregate='sum' />
                                <attribute name='itbc_qtdeplanejada' alias='quantidade_planejada' aggregate='sum' />
                                <attribute name='itbc_metaplanejada' alias='valor_planejado' aggregate='sum' />
                                <filter type='and' >
                                  <condition attribute='itbc_ano' operator='eq' value='{0}' />
                                  <condition attribute='itbc_unidade_negocio' operator='eq' value='{1}' />
                                  <condition attribute='itbc_canalid' operator='eq' value='{2}' />
                                </filter>
                                <link-entity name='itbc_metadocanalporproduto' from='itbc_metadocanalporprodutoid' to='itbc_metadocanalporprodutoid' >
                                  <attribute name='itbc_metadocanalporprodutoid' alias='id' groupby='true' />
                                </link-entity>
                              </entity>
                            </fetch>";


            fetch = string.Format(fetch, ano, unidadeNegocioId, canalId);

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(fetch)
            };

            EntityCollection collection = ((RetrieveMultipleResponse)this.Execute(retrieveMultiple)).EntityCollection;

            foreach (var item in collection.Entities)
            {
                var meta = new MetadoCanalporProduto(OrganizationName, IsOffline, Provider)
                {
                    ID            = (Guid)((AliasedValue)(item.Attributes["id"])).Value,
                    MetaPlanejada = ((Money)((AliasedValue)item.Attributes["valor_planejado"]).Value).Value,
                    MetaRealizada = ((Money)((AliasedValue)item.Attributes["valor_realizado"]).Value).Value
                                    //qu = (decimal)((AliasedValue)(item.Attributes["quantidade_planejada"])).Value,
                                    //QtdeRealizada = (decimal)((AliasedValue)(item.Attributes["quantidade_realizado"])).Value
                };

                lista.Add(meta);
            }

            return(lista);
        }
Esempio n. 16
0
        public IEnumerable <new_incidentservice> GetAll()
        {
            int fetchCount = 1000;
            // Initialize the page number.
            int pageNumber = 1;
            // Specify the current paging cookie. For retrieving the first page,
            // pagingCookie should be null.
            List <new_incidentservice> new_incidentservices = new List <new_incidentservice>();
            string pagingCookie = null;

            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                    <entity name='new_incidentservice'>
                   <all-attributes /> 
                    <filter type='and'>
                      <condition attribute='statecode' operator='eq' value='0' />
                    </filter>
                  </entity>
                 </fetch>";

            while (true)
            {
                string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);
                RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };

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

                foreach (var c in returnCollection.Entities)
                {
                    var ins = c.ToEntity <new_incidentservice>();
                    new_incidentservices.Add(ins);
                }

                // Check for morerecords, if it returns 1.
                if (returnCollection.MoreRecords)
                {
                    pageNumber++;// Increment the page number to retrieve the next page.
                }
                else
                {
                    break; // If no more records in the result nodes, exit the loop.
                }
            }
            return(new_incidentservices);
        }
        public T ObterPorCompCanal(Guid CompromissosDoCanalId)
        {
            var query = GetQueryExpression <T>(true);

            RetrieveMultipleRequest retrieveMultiple;
            StringBuilder           strFetchXml = new StringBuilder();

            strFetchXml.Append("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>                                             ");
            strFetchXml.Append("  <entity name='itbc_compromissos'>                                                                                              ");
            strFetchXml.Append("<attribute name='itbc_compromissosid' />        ");
            strFetchXml.Append("<attribute name='itbc_name' />                  ");
            strFetchXml.Append("<attribute name='createdon' />                  ");
            strFetchXml.Append("<attribute name='itbc_tipodemonitoramento' />   ");
            strFetchXml.Append("<attribute name='statecode' />                  ");
            strFetchXml.Append("<attribute name='overriddencreatedon' />        ");
            strFetchXml.Append("<attribute name='statuscode' />                 ");
            strFetchXml.Append("<attribute name='modifiedonbehalfby' />         ");
            strFetchXml.Append("<attribute name='modifiedby' />                 ");
            strFetchXml.Append("<attribute name='itbc_descricaoid' />           ");
            strFetchXml.Append("<attribute name='modifiedon' />                 ");
            strFetchXml.Append("<attribute name='createdonbehalfby' />          ");
            strFetchXml.Append("<attribute name='createdby' />                  ");
            strFetchXml.Append("<attribute name='itbc_codigo' />                ");
            strFetchXml.Append("    <order attribute='itbc_name' descending='false' />                                                                           ");
            strFetchXml.Append("    <link-entity name='itbc_compdocanal' from='itbc_compdoprogid' to='itbc_compromissosid' alias='ae'>                           ");
            strFetchXml.Append("      <filter type='and'>                                                                                                        ");
            strFetchXml.AppendFormat("        <condition attribute='itbc_compdocanalid' operator='eq' uitype='itbc_compdocanal' value='{0}' />        ", CompromissosDoCanalId);
            strFetchXml.Append("      </filter>                                                                                                                  ");
            strFetchXml.Append("    </link-entity>                                                                                                               ");
            strFetchXml.Append("  </entity>                                                                                                                      ");
            strFetchXml.Append("</fetch>                                                                                                                         ");

            // Build fetch request and obtain results.
            retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(strFetchXml.ToString())
            };

            var colecao = this.RetrieveMultiple(retrieveMultiple.Query);

            if (colecao.List.Count == 0)
            {
                return(default(T));
            }

            return(colecao.List[0]);
        }
Esempio n. 18
0
        public List<Solution> GetSolutions()
        {
            List<Solution> orgs = new List<Solution>();

            QueryExpression query = new QueryExpression("solution");
            query.ColumnSet = new ColumnSet(true);

            RetrieveMultipleRequest req = new RetrieveMultipleRequest();
            req.Query = query;

            RetrieveMultipleResponse response = (RetrieveMultipleResponse)CrmService.Execute(req);
            foreach (Entity org in response.EntityCollection.Entities)
            {
                orgs.Add(new Solution() { Id=org.Id, Name=org["uniquename"] as string});
            }
            return orgs;
        }
Esempio n. 19
0
        private void buttonExecFetch_Click(object sender, EventArgs e)
        {
            // exec the fetch and bind to the grid
            if (XmlViewerCRMDataGrid.IsValidXml)
            {
                var fetchReq = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(XmlViewerCRMDataGrid.Text)
                };

                var fetchResult = Service.Execute(fetchReq) as RetrieveMultipleResponse;

                CrmGridView.DataSource = fetchResult.EntityCollection;

                MessageBox.Show(fetchResult.EntityCollection.EntityName);
            }
        }
        public static void FakeRetrieveMultiple(XrmFakedContext context, IOrganizationService fakedService)
        {
            //refactored from RetrieveMultipleExecutor
            A.CallTo(() => fakedService.RetrieveMultiple(A <QueryBase> ._))
            .ReturnsLazily((QueryBase req) =>
            {
                var request = new RetrieveMultipleRequest()
                {
                    Query = req
                };

                var executor = new RetrieveMultipleRequestExecutor();
                var response = executor.Execute(request, context) as RetrieveMultipleResponse;

                return(response.EntityCollection);
            });
        }
        public static List <ViewDetail> GetListUserViews(IOrganizationService service, string entityLogicalName, int entityTypeCode)
        {
            WhoAmIRequest  systemUserRequest  = new WhoAmIRequest();
            WhoAmIResponse systemUserResponse = (WhoAmIResponse)service.Execute(systemUserRequest);
            Guid           userId             = systemUserResponse.UserId;

            var query = new QueryExpression
            {
                EntityName = "userquery",
                ColumnSet  = new ColumnSet("userqueryid", "name", "fetchxml"),
                Criteria   = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions     =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "returnedtypecode",
                            Operator      = ConditionOperator.Equal,
                            Values        = { entityTypeCode }
                        },
                        new ConditionExpression
                        {
                            AttributeName = "owninguser",
                            Operator      = ConditionOperator.Equal,
                            Values        = { userId         }
                        }
                    }
                }
            };

            RetrieveMultipleRequest retrieveSavedQueriesRequest = new RetrieveMultipleRequest {
                Query = query
            };

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

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

            return(savedQueries.Select(x => new ViewDetail
            {
                Name = x.GetAttributeValue <string>("name"),
                FetchXML = x.GetAttributeValue <string>("fetchxml"),
                Savedqueryid = x.Id
            }).ToList());
        }
        /// <summary>
        /// Query CRM to get Portal Search Enabled entities
        /// </summary>
        /// <returns>
        /// The search enabled entities.
        /// </returns>
        public HashSet <string> GetPortalSearchEnabledEntities()
        {
            this.SearchEnabledEntities = new HashSet <string>();
            this.SearchSavedQueries    = new HashSet <SearchSavedQuery>();

            FilterExpression filterExpression = new FilterExpression();

            filterExpression.AddCondition("name", ConditionOperator.Equal, this.GetSearchSavedQueryViewName());
            filterExpression.AddCondition("componentstate", ConditionOperator.Equal, 0);
            QueryExpression query = new QueryExpression()
            {
                EntityName = "savedquery",
                ColumnSet  = new ColumnSet("returnedtypecode", "savedqueryidunique"),
                Criteria   = filterExpression
            };
            var request = new RetrieveMultipleRequest()
            {
                Query = query
            };
            var response = (RetrieveMultipleResponse)this.OrganizationServiceContext.Execute(request);
            var entities = response.EntityCollection.Entities;

            foreach (Entity entity in entities)
            {
                var savedQueryItem = new SearchSavedQuery(entity);
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Entity {0} has Portal Search View Present in CRM ", savedQueryItem.EntityName));
                this.SearchEnabledEntities.Add(savedQueryItem.EntityName);
                this.SearchSavedQueries.Add(savedQueryItem);
            }

            // These entities are not searchable but changes to them can invalidate certain searchable entities
            List <string> searchAffectingEntities = new List <string>()
            {
                "adx_webpageaccesscontrolrule",
                "adx_communityforumaccesspermission",
                "connection",
                "adx_contentaccesslevel",
                "adx_knowledgearticlecontentaccesslevel",
                "adx_webpageaccesscontrolrule_webrole",
                "adx_website",
                "savedquery"
            };

            searchAffectingEntities.ForEach(x => this.SearchEnabledEntities.Add(x));
            return(this.SearchEnabledEntities);
        }
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            if (crmWorkflowContext == null)
            {
                throw new ArgumentNullException("crmWorkflowContext");
            }



            var tracingService = executionContext.GetExtension <ITracingService>();
            var service        = crmWorkflowContext.OrganizationService;
            var context        = crmWorkflowContext.WorkflowExecutionContext;
            var appLineId      = context.PrimaryEntityId;
            var appId          = GetApplication.Get <EntityReference>(executionContext).Id;

            tracingService.Trace("inside GetMainActivityForApplication ");

            var fetchXml = @"<fetch >
                  <entity name='defra_applicationline'>
                    <attribute name='defra_applicationlineid' />
                    <attribute name='defra_name' />
                    <attribute name='defra_standardruleid' />
                    <attribute name='defra_linetype' />
                    <attribute name='defra_itemid' />
                    <attribute name='defra_item_type' />
                    <attribute name='defra_value' />
                    <order attribute='defra_value' descending='true' />
                    <filter type='and'>
                      <condition attribute='defra_applicationid' operator='eq'  uitype='defra_application' value='{" + appId + @"}' />
                     <condition attribute='statecode' value='0' operator='eq'/>
                    </filter>
                  </entity>
                </fetch>";

            tracingService.Trace(fetchXml);
            RetrieveMultipleRequest fetchRequest = new RetrieveMultipleRequest
            {
                Query = new FetchExpression(fetchXml)
            };

            var result = ((RetrieveMultipleResponse)service.Execute(fetchRequest)).EntityCollection.Entities.FirstOrDefault().ToEntityReference();

            MianActivity.Set(executionContext, result);
            tracingService.Trace("GetMainActivityForApplication done");
        }
Esempio n. 24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="entityLogicalName"></param>
        /// <returns></returns>
        public static List <Dynamics365Workflow> GetWorkflows(Dynamics365Connection connection, string entityLogicalName)
        {
            ConnectionCache            cache     = new ConnectionCache(connection);
            string                     cacheKey  = string.Format("GetOnDemandWorkflows:{0}", entityLogicalName);
            List <Dynamics365Workflow> workflows = (List <Dynamics365Workflow>)cache[cacheKey];

            if (workflows == default(List <Dynamics365Workflow>))
            {
                workflows = new List <Dynamics365Workflow>();

                QueryExpression workflowQuery = new QueryExpression("workflow")
                {
                    ColumnSet = new ColumnSet(true)
                };

                using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy)
                {
                    workflowQuery.Criteria.AddCondition(new ConditionExpression("category", ConditionOperator.Equal, 0));  // workflow
                    workflowQuery.Criteria.AddCondition(new ConditionExpression("primaryentity", ConditionOperator.Equal, entityLogicalName));
                    workflowQuery.Criteria.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, 1)); // activated
                    workflowQuery.Criteria.AddCondition(new ConditionExpression("type", ConditionOperator.Equal, 1));      // definition
                    workflowQuery.Criteria.AddCondition(new ConditionExpression("ondemand", ConditionOperator.Equal, true));

                    RetrieveMultipleRequest workflowRequest = new RetrieveMultipleRequest()
                    {
                        Query = workflowQuery
                    };
                    RetrieveMultipleResponse workflowResponse = (RetrieveMultipleResponse)proxy.Execute(workflowRequest);

                    foreach (Microsoft.Xrm.Sdk.Entity workflowMetadata in workflowResponse.EntityCollection.Entities)
                    {
                        workflows.Add(new Dynamics365Workflow()
                        {
                            ID   = workflowMetadata.Id,
                            Name = workflowMetadata.Attributes["name"].ToString()
                        });
                    }
                }

                workflows.Sort((workflow1, workflow2) => workflow1.Name.CompareTo(workflow2.Name));
                cache[cacheKey] = workflows;
            }

            return(workflows);
        }
Esempio n. 25
0
        /// <summary>
        /// Method to Get a Record and return
        /// it in the form of a Dynamic Entity Object
        /// to the calling function
        /// </summary>
        /// <param name="poGuid"></param>
        /// <param name="psEntityName"></param>
        /// <param name="psAttributeName"></param>
        /// <param name="poService"></param>
        /// <param name="paColumnSet"></param>
        /// <returns></returns>
        public static DynamicEntity GetDynamicEntityBasedOnGuid(Guid poGuid, string psEntityName, string psAttributeName, CrmService poService, ArrayList paColumnSet)
        {
            CrmService      loService       = poService;
            QueryExpression loQuery         = new QueryExpression();
            DynamicEntity   loDynamicEntity = null;
            ColumnSet       loColSet        = new ColumnSet();

            foreach (string lsColumnItem in paColumnSet)
            {
                loColSet.AddColumn(lsColumnItem);
            }

            try
            {
                ConditionExpression loCondition = new ConditionExpression(psAttributeName, ConditionOperator.Equal, poGuid);
                FilterExpression    loFilter    = new FilterExpression();

                loQuery.EntityName = psEntityName;
                loQuery.ColumnSet  = loColSet;
                loFilter.Conditions.Add(loCondition);

                loQuery.Criteria = loFilter;

                RetrieveMultipleRequest loRetrieve = new RetrieveMultipleRequest();

                loRetrieve.Query = loQuery;
                loRetrieve.ReturnDynamicEntities = true;
                RetrieveMultipleResponse loResponse = (RetrieveMultipleResponse)loService.Execute(loRetrieve);

                if (loResponse.BusinessEntityCollection.BusinessEntities.Count > 0)
                {
                    loDynamicEntity = (DynamicEntity)loResponse.BusinessEntityCollection.BusinessEntities[0];
                }
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                MessageBox.Show("Error: " + ex.Detail.InnerXml.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message.ToString());
            }

            return(loDynamicEntity);
        }
Esempio n. 26
0
        /// <summary>
        /// Returns a list of entities
        /// </summary>
        /// <param name="service">OrganizationServiceProxy</param>
        /// <param name="EntityName">The name of the entity</param>
        /// <param name="Columns">An array of strings with column names.  Send an empty string array to return all columns </param>
        /// <param name="Filter">A filterexpression object.</param>
        /// <returns></returns>
        private EntityCollection Query(IOrganizationService service, String EntityName, String[] Columns, FilterExpression Filter)
        {
            QueryExpression GetCustomersQuery = new QueryExpression()
            {
                EntityName = EntityName,
                ColumnSet  = Columns.Length == 0 ? new ColumnSet(true) : new ColumnSet(Columns),
                Criteria   = Filter
            };

            int    page   = 1;
            string cookie = "";

            EntityCollection Entities = new EntityCollection();

            while (true)
            {
                GetCustomersQuery.PageInfo = new PagingInfo()
                {
                    Count        = 5000,
                    PageNumber   = page,
                    PagingCookie = cookie
                };
                RetrieveMultipleRequest GetCustomersQueryRequest = new RetrieveMultipleRequest()
                {
                    Query = GetCustomersQuery
                };
                RetrieveMultipleResponse GetCustomersQueryResponse = (RetrieveMultipleResponse)service.Execute(GetCustomersQueryRequest);


                //Loop through each result and put it into objects and a list.
                foreach (Entity e in GetCustomersQueryResponse.EntityCollection.Entities)
                {
                    Entities.Entities.Add(e);
                }

                page++;
                cookie = GetCustomersQueryResponse.EntityCollection.PagingCookie;
                if (!GetCustomersQueryResponse.EntityCollection.MoreRecords)
                {
                    break;
                }
            }

            return(Entities);
        }
Esempio n. 27
0
        public MetadaUnidade ObterValoresPor(Guid unidadeNegocioId, int ano)
        {
            string fetch = @"<fetch aggregate='true' no-lock='true' >
                              <entity name='itbc_metadokaporsegmento' >
                                <attribute name='itbc_metaplanejada' alias='valor_planejado' aggregate='sum' />
                                <attribute name='itbc_metarealizada' alias='valor_realizado' aggregate='sum' />
                                <filter type='and' >
                                  <condition attribute='itbc_ano' operator='eq' value='{0}' />
                                  <condition attribute='itbc_unidadedenegocioid' operator='eq' value='{1}' />
                                </filter>
                              </entity>
                            </fetch>";

            fetch = string.Format(fetch, ano, unidadeNegocioId);

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(fetch)
            };

            EntityCollection collection = ((RetrieveMultipleResponse)this.Execute(retrieveMultiple)).EntityCollection;

            if (collection.Entities.Count > 0)
            {
                var item = collection.Entities[0];

                var metaDaUnidade = new MetadaUnidade(OrganizationName, IsOffline, Provider);

                if (item.Attributes.Contains("valor_planejado"))
                {
                    metaDaUnidade.MetaPlanejada = ((Money)((AliasedValue)item.Attributes["valor_planejado"]).Value).Value;
                }
                if (item.Attributes.Contains("valor_realizado"))
                {
                    metaDaUnidade.MetaRealizada = ((Money)((AliasedValue)item.Attributes["valor_realizado"]).Value).Value;
                }


                return(metaDaUnidade);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 28
0
        public T ObterPorSegmento(Guid segmnetoId)
        {
            var query = GetQueryExpression <T>(true);

            RetrieveMultipleRequest retrieveMultiple;

            StringBuilder strFetchXml = new StringBuilder();

            strFetchXml.Append("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>                                        ");
            strFetchXml.Append("  <entity name='itbc_metakeyaccount'>                                                                                       ");
            strFetchXml.Append("    <attribute name='itbc_ano' />                                                                                           ");
            strFetchXml.Append("    <attribute name='itbc_unidadedenegocioid' />                                                                            ");
            strFetchXml.Append("    <attribute name='itbc_trimestre' />                                                                                     ");
            strFetchXml.Append("    <attribute name='itbc_metarealizada' />                                                                                 ");
            strFetchXml.Append("    <attribute name='itbc_metaplanejada' />                                                                                 ");
            strFetchXml.Append("    <attribute name='itbc_contact' />                                                                                       ");
            strFetchXml.Append("    <attribute name='itbc_metakeyaccountid' />                                                                              ");
            strFetchXml.Append("    <order attribute='itbc_ano' descending='false' />                                                                       ");
            strFetchXml.Append("    <link-entity name='itbc_metatrimestreka' from='itbc_metadokarepresentanteid' to='itbc_metakeyaccountid' alias='ae'>     ");
            strFetchXml.Append("      <link-entity name='itbc_metadokaporsegmento' from='itbc_metatrimestrekaid' to='itbc_metatrimestrekaid' alias='af'>    ");
            strFetchXml.Append("        <filter type='and'>                                                                                                 ");
            strFetchXml.AppendFormat("          <condition attribute='itbc_segmentoid' operator='eq' uitype='itbc_segmento' value='{0}' />                        ", segmnetoId);
            strFetchXml.Append("        </filter>                                                                                                           ");
            strFetchXml.Append("      </link-entity>                                                                                                        ");
            strFetchXml.Append("    </link-entity>                                                                                                          ");
            strFetchXml.Append("  </entity>                                                                                                                 ");
            strFetchXml.Append("</fetch>                                                                                                                    ");



            // Build fetch request and obtain results.
            retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(strFetchXml.ToString())
            };

            var lst = this.RetrieveMultiple(retrieveMultiple.Query).List;

            if (lst.Count > 0)
            {
                return(this.RetrieveMultiple(retrieveMultiple.Query).List[0]);
            }

            return(default(T));
        }
Esempio n. 29
0
        public IEnumerable <EntityReference> Get(IOrganizationService service, string fetchXml, int fetchCount)
        {
            int pageNumber = 1;
            EntityCollection returnCollection = null;

            while (true)
            {
                // Build fetchXml string with the placeholders.
                var xml = CreateXml(fetchXml, pageNumber, fetchCount);
                xml = xml.RemoveDuplicateAliasJ();
                // Excute the fetch query and get the xml result.
                var fetchRequest1 = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };
                try
                {
                    returnCollection = ((RetrieveMultipleResponse)service.Execute(fetchRequest1)).EntityCollection;
                }
                catch (FaultException <OrganizationServiceFault> ee)
                {
                    // You can handle an exception here or pass it back to the calling method.
                    Log(ee, "FetchExpression:" + xml);
                    break;
                }
                if (returnCollection != null)
                {
                    foreach (Entity entityMember in returnCollection.Entities)
                    {
                        yield return(entityMember.ToEntityReference());
                    }

                    // Check for morerecords, if it returns 1.
                    if (returnCollection.MoreRecords)
                    {
                        pageNumber++;// Increment the page number to retrieve the next page.
                    }
                    else
                    {
                        break; // If no more records in the result nodes, exit the loop.
                    }
                }
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Retrieve all entity records using up to three fields and values
        /// </summary>
        /// <param name="service"></param>
        /// <param name="entityName">Name of the entity (Constants.ENTITYNAME.This)</param>
        /// <param name="entitySearchField1">Name of the 1st entity field to filter by (Constants.ENTITYNAME.FIELD)</param>
        /// <param name="entitySearchFieldValue1">Value for the 1st entity field to filter by</param>
        /// <param name="entitySearchField2">Name of the 2nd entity field to filter by (Constants.ENTITYNAME.FIELD)</param>
        /// <param name="entitySearchFieldValue2">Value for the 2nd entity field to filter by</param>
        /// <param name="entitySearchField3">Name of the 3rd entity field to filter by (Constants.ENTITYNAME.FIELD)</param>
        /// <param name="entitySearchFieldValue3">Value for the 3rd entity field to filter by</param>
        /// <param name="columnSet"></param>
        /// <param name="activeRecordsOnly">Optional - Selects only records with statecode of 0, which is usually active, or open records</param>
        /// <returns></returns>
        static public List <Entity> EntitiesList(IOrganizationService service, string entityName, string entitySearchField1, object entitySearchFieldValue1,
                                                 string entitySearchField2, object entitySearchFieldValue2, string entitySearchField3, object entitySearchFieldValue3, ColumnSet columnSet, bool activeRecordsOnly = false)
        {
            RetrieveMultipleRequest getRequest = new RetrieveMultipleRequest();
            QueryExpression         qex        = new QueryExpression(entityName);

            if (columnSet == null)
            {
                qex.ColumnSet = new ColumnSet(true);                 // They get all
            }
            else
            {
                qex.ColumnSet = columnSet;                 // Give them just what they asked for
            }
            qex.Criteria = new FilterExpression();
            qex.Criteria.FilterOperator = LogicalOperator.And;
            if (entitySearchFieldValue1 != null)
            {
                qex.Criteria.AddCondition(new ConditionExpression(entitySearchField1, ConditionOperator.Equal, entitySearchFieldValue1));
            }
            if (entitySearchFieldValue2 != null)
            {
                qex.Criteria.AddCondition(new ConditionExpression(entitySearchField2, ConditionOperator.Equal, entitySearchFieldValue2));
            }
            if (entitySearchFieldValue3 != null)
            {
                qex.Criteria.AddCondition(new ConditionExpression(entitySearchField3, ConditionOperator.Equal, entitySearchFieldValue3));
            }
            if (activeRecordsOnly)
            {
                qex.Criteria.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, 0));
            }

            getRequest.Query = qex;

            RetrieveMultipleResponse returnValues = (RetrieveMultipleResponse)service.Execute(getRequest);

            if (returnValues.EntityCollection.Entities != null)
            {
                return(returnValues.EntityCollection.Entities.ToList());
            }

            return(null);
        }
Esempio n. 31
0
        public static List <Dynamics365Team> GetTeams(Dynamics365Connection connection)
        {
            ConnectionCache        cache    = new ConnectionCache(connection);
            string                 cacheKey = "GetTeams:{0}";
            List <Dynamics365Team> teams    = (List <Dynamics365Team>)cache[cacheKey];

            if (teams == default(List <Dynamics365Team>))
            {
                teams = new List <Dynamics365Team>();
                QueryExpression teamQuery = new QueryExpression("team")
                {
                    ColumnSet = new ColumnSet(true)
                };

                using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy)
                {
                    if (connection.IsVersionOrAbove(CrmVersion.Crm2013))
                    {
                        teamQuery.Criteria.AddCondition(new ConditionExpression("teamtype", ConditionOperator.Equal, 0));
                    }

                    RetrieveMultipleRequest teamRequest = new RetrieveMultipleRequest()
                    {
                        Query = teamQuery
                    };
                    RetrieveMultipleResponse teamResponse = (RetrieveMultipleResponse)proxy.Execute(teamRequest);

                    foreach (Microsoft.Xrm.Sdk.Entity teamMetadata in teamResponse.EntityCollection.Entities)
                    {
                        teams.Add(new Dynamics365Team()
                        {
                            ID   = teamMetadata.Id,
                            Name = teamMetadata.Attributes["name"].ToString()
                        });
                    }

                    teams.Sort((team1, team2) => team1.Name.CompareTo(team2.Name));
                }

                cache[cacheKey] = teams;
            }

            return(teams);
        }
Esempio n. 32
0
        public IEnumerable<new_incidentservice> GetAll()
        {
            int fetchCount = 1000;
            // Initialize the page number.
            int pageNumber = 1;
            // Specify the current paging cookie. For retrieving the first page,
            // pagingCookie should be null.
            List<new_incidentservice> new_incidentservices = new List<new_incidentservice>();
            string pagingCookie = null;

            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                    <entity name='new_incidentservice'>
                   <all-attributes />
                    <filter type='and'>
                      <condition attribute='statecode' operator='eq' value='0' />
                    </filter>
                  </entity>
                 </fetch>";
            while (true)
            {
                string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);
                RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };

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

                foreach (var c in returnCollection.Entities)
                {
                    var ins = c.ToEntity<new_incidentservice>();
                    new_incidentservices.Add(ins);
                }

                // Check for morerecords, if it returns 1.
                if (returnCollection.MoreRecords)
                    pageNumber++;// Increment the page number to retrieve the next page.
                else
                    break; // If no more records in the result nodes, exit the loop.

            }
            return new_incidentservices;
        }
        /// <summary>
        /// Internal many to many relationship key gathering helper
        /// </summary>
        /// <param name="service"></param>
        /// <param name="primaryAttribute"></param>
        /// <param name="secondaryEntity"></param>
        /// <param name="secondaryAttribute"></param>
        /// <param name="intersection"></param>
        /// <param name="currentEntityName"></param>
        /// <param name="currentRecordId"></param>
        /// <returns></returns>
        private static IList <Guid> GatherKeysInternal(IOrganizationService service, string primaryAttribute, string secondaryEntity, string secondaryAttribute, string intersection, string currentEntityName, Guid currentRecordId)
        {
            var query = new QueryExpression();
            var secondaryToIntersection = new LinkEntity();
            var intersectionToPrimary   = new LinkEntity();
            var primaryCondition        = new ConditionExpression();

            // Chain all links
            query.EntityName = secondaryEntity;
            query.LinkEntities.Add(secondaryToIntersection);
            secondaryToIntersection.LinkEntities.Add(intersectionToPrimary);
            intersectionToPrimary.LinkCriteria.Conditions.Add(primaryCondition);

            // First link
            secondaryToIntersection.LinkToEntityName        = intersection;
            secondaryToIntersection.LinkFromAttributeName   =
                secondaryToIntersection.LinkToAttributeName = secondaryAttribute;

            // Second link
            intersectionToPrimary.LinkToEntityName        = currentEntityName;
            intersectionToPrimary.LinkFromAttributeName   =
                intersectionToPrimary.LinkToAttributeName = primaryAttribute;

            // Condition
            primaryCondition.AttributeName = primaryAttribute;
            primaryCondition.Operator      = ConditionOperator.Equal;
            primaryCondition.Values.Add(currentRecordId.ToString());

            var retrieveRequest = new RetrieveMultipleRequest()
            {
                Query = query
            };

            var list             = new List <Guid>();
            var retrieveResponse = (RetrieveMultipleResponse)service.Execute(retrieveRequest);

            foreach (var entity in retrieveResponse.EntityCollection.Entities)
            {
                list.Add(entity.Id);
            }

            return(list);
        }
Esempio n. 34
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="connection"></param>
        /// <returns></returns>
        private static List <Dynamics365View> GetPersonalViews(Dynamics365Entity entity, IConnection connection)
        {
            ConnectionCache        cache    = new ConnectionCache(connection);
            string                 cacheKey = string.Format("GetPersonalViews:{0}:{1}", typeof(Dynamics365View).Name, entity.LogicalName);
            List <Dynamics365View> views    = (List <Dynamics365View>)cache[cacheKey];

            if (views == null)
            {
                views = new List <Dynamics365View>();
                QueryExpression query = new QueryExpression("userquery");
                query.Criteria.AddCondition("returnedtypecode", ConditionOperator.Equal, entity.ObjectTypeCode);
                query.Criteria.AddCondition("fetchxml", ConditionOperator.NotNull);
                query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
                query.ColumnSet = new ColumnSet(new string[] { "name", "fetchxml" });   // todo - not working?

                RetrieveMultipleRequest request = new RetrieveMultipleRequest()
                {
                    Query = query
                };

                using (OrganizationServiceProxy proxy = ((Dynamics365Connection)connection).OrganizationServiceProxy)
                {
                    RetrieveMultipleResponse response = (RetrieveMultipleResponse)proxy.Execute(request);

                    foreach (Entity viewEntity in response.EntityCollection.Entities)
                    {
                        Dynamics365View view = new Dynamics365View()
                        {
                            ID          = viewEntity.Id,
                            DisplayName = (string)viewEntity.Attributes["name"],
                            FetchXml    = (string)viewEntity.Attributes["fetchxml"]
                        };
                        views.Add(view);
                    }

                    views.Sort((view1, view2) => view1.DisplayName.CompareTo(view2.DisplayName));
                }

                cache[cacheKey] = views;
            }

            return(views);
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var executeFetchRequest = (ExecuteFetchRequest)request;


            if (executeFetchRequest.FetchXml == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "You need to provide FetchXml value");
            }

            var service = ctx.GetFakedOrganizationService();

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(executeFetchRequest.FetchXml)
            };
            var queryResult = (service.Execute(retrieveMultiple) as RetrieveMultipleResponse).EntityCollection;



            XDocument doc = new XDocument(new XElement("resultset",
                                                       new XAttribute("morerecords", Convert.ToInt16(queryResult.MoreRecords))));

            if (queryResult.PagingCookie != null)
            {
                doc.Root.Add(new XAttribute("paging-cookie", queryResult.PagingCookie));
            }

            foreach (var row in queryResult.Entities)
            {
                doc.Root.Add(CreateXmlResult(row, ctx));
            }

            var response = new ExecuteFetchResponse
            {
                Results = new ParameterCollection
                {
                    { "FetchXmlResult", doc.ToString() }
                }
            };

            return(response);
        }
        public List <PotencialdoKAporTrimestre> ListarValoresPorUnidadeNegocio(Guid unidadeNegocioId, int ano)
        {
            var lista = new List <PotencialdoKAporTrimestre>();

            string fetch = @"<fetch aggregate='true' no-lock='true' returntotalrecordcount='true' >
                              <entity name='itbc_metadokaporsegmento' >
                                <attribute name='itbc_metaplanejada' alias='valor_planejado' aggregate='sum' />
                                <attribute name='itbc_metarealizada' alias='valor_realizado' aggregate='sum' />
                                <link-entity name='itbc_metatrimestreka' from='itbc_metatrimestrekaid' to='itbc_metatrimestrekaid' alias='tri' >
                                  <attribute name='itbc_metatrimestrekaid' alias='id' groupby='true' />
                                  <filter type='and' >
                                    <condition attribute='itbc_ano' operator='eq' value='{0}' />
                                    <condition attribute='itbc_unidadenegocioid' operator='eq' value='{1}' />
                                  </filter>
                                </link-entity>
                              </entity>
                            </fetch>";


            fetch = string.Format(fetch, ano, unidadeNegocioId);

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(fetch)
            };

            EntityCollection collection = ((RetrieveMultipleResponse)this.Execute(retrieveMultiple)).EntityCollection;

            foreach (var item in collection.Entities)
            {
                var potencialTrimestre = new PotencialdoKAporTrimestre(OrganizationName, IsOffline, Provider)
                {
                    ID = (Guid)((AliasedValue)(item.Attributes["id"])).Value,
                    PotencialPlanejado = ((Money)((AliasedValue)item.Attributes["valor_planejado"]).Value).Value,
                    PotencialRealizado = ((Money)((AliasedValue)item.Attributes["valor_realizado"]).Value).Value
                };

                lista.Add(potencialTrimestre);
            }

            return(lista);
        }
        public void When_executing_fetchxml_right_result_is_returned()
        {
            //This will test a query expression is generated and executed

            var ctx = new XrmFakedContext();
            ctx.Initialize(new List<Entity>()
            {
                new Contact() {Id = Guid.NewGuid(), FirstName = "Leo Messi", Telephone1 = "123" }, //should be returned
                new Contact() {Id = Guid.NewGuid(), FirstName = "Leo Messi", Telephone1 = "234" }, //should be returned
                new Contact() {Id = Guid.NewGuid(), FirstName = "Leo", Telephone1 = "789" }, //shouldnt
                new Contact() {Id = Guid.NewGuid(), FirstName = "Andrés", Telephone1 = "123" }, //shouldnt
            });

            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='contact'>
                                    <attribute name='fullname' />
                                    <attribute name='telephone1' />
                                    <attribute name='contactid' />
                                        <filter type='and'>
                                            <condition attribute='firstname' operator='like' value='%Leo%' />
                                                <filter type='or'>
                                                    <condition attribute='telephone1' operator='eq' value='123' />
                                                    <condition attribute='telephone1' operator='eq' value='234' />
                                                </filter>
                                        </filter>
                                  </entity>
                            </fetch>";

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(fetchXml)
            };

            var service = ctx.GetFakedOrganizationService();
            var response = service.Execute(retrieveMultiple) as RetrieveMultipleResponse;

            Assert.Equal(2, response.EntityCollection.Entities.Count);

            //Executing the same via ExecuteMultiple returns also the same
            var response2 = service.RetrieveMultiple(retrieveMultiple.Query);
            Assert.Equal(2, response2.Entities.Count);
        }
Esempio n. 38
0
		public PluginInfo[] GetRegisteredPluginAssemblies()
		{
			QueryExpression query = new QueryExpression("pluginassembly");
			query.ColumnSet = new ColumnSet("name", "pluginassemblyid");

			RetrieveMultipleRequest request = new RetrieveMultipleRequest();
			request.Query = query;

			RetrieveMultipleResponse response = (RetrieveMultipleResponse)_service.Execute(request);

			List<PluginInfo> plugins = new List<PluginInfo>();
			foreach (var item in response.EntityCollection.Entities)
			{
				plugins.Add(new PluginInfo
				{
					 ShortName= item["name"] as string,
					 Id=(Guid)item["pluginassemblyid"]
				});
			}
			return plugins.OrderBy(x=>x.ShortName).ToArray();
		}
 public void When_can_execute_is_called_with_an_invalid_request_result_is_false()
 {
     var executor = new AssignRequestExecutor();
     var anotherRequest = new RetrieveMultipleRequest();
     Assert.False(executor.CanExecute(anotherRequest));
 }
        /// <summary>
        /// Gets an array of <c>Key</c> objects that represent the <c>Key</c>s for entities provided by this provider that have been modified since the 
        /// date provided in the modified Date <c>string</c>.
        /// </summary>
        /// <param name="modifiedDate">The <c>DateTime</c> to be used as the modified on criteria for the retrieve request.</param>
        /// <param name="keyPropertyName">The name of the property on the provided entity that hold the primary key.</param>
        /// <returns>An Array of <c>Key</c> objects that correspond to entities that have been modified since the supplied modified Date date.</returns>
        protected Guid[] GetModifiedEntityKeys(DateTime modifiedDate, string keyPropertyName)
        {
            RetrieveMultipleRequest retrieveRequest = new RetrieveMultipleRequest();
            DateTime date = modifiedDate < MinDateTime ? DateTime.SpecifyKind(MinDateTime, DateTimeKind.Utc) : DateTime.SpecifyKind(modifiedDate, DateTimeKind.Utc);
            bool isDynamic = this is DynamicObjectProvider;
            ColumnSet cols = new ColumnSet() { Columns = { keyPropertyName } };
            retrieveRequest.Query = CRM2011AdapterUtilities.GetReaderQueryExpression(this.ProvidedEntityName, date, this.CrmAdapter, isDynamic, cols);

            var retrievedEntities = this.GetKeys(retrieveRequest);

            List<Guid> keyList = new List<Guid>();
            retrievedEntities.ForEach(be => keyList.Add(be.Id));
            return keyList.ToArray();
        }
        /// <summary>
        /// Gets an array of <c>Key</c> objects that represent the <c>Key</c>s for entities provided by this provider that have been deleted since the 
        /// date provided in the modifiedDate <c>string</c>.
        /// </summary>
        /// <param name="modifiedDate">The <c>string</c> representation of a <c>DateTime</c> to be used as the modified on criteria for the retrieve request.</param>
        /// <returns>An <c>ICollection</c> of <c>Key</c> objects that correspond to entities that have been deleted since the supplied modifiedDate date.</returns>
        protected ICollection GetDeletedEntityKeys(DateTime modifiedDate)
        {
            RetrieveMultipleRequest retrieveRequest = new RetrieveMultipleRequest();
            var query = new QueryExpression("audit");
            query.ColumnSet = new ColumnSet(true);
            query.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.GreaterEqual, modifiedDate));
            query.Criteria.AddCondition(new ConditionExpression("operation", ConditionOperator.Equal, 3));
            query.Criteria.AddCondition(new ConditionExpression("action", ConditionOperator.Equal, 3));
            query.Criteria.AddCondition(new ConditionExpression("objecttypecode", ConditionOperator.Equal, this.ProvidedEntityName));
            query.PageInfo = new PagingInfo();
            query.PageInfo.Count = 5000;
            query.PageInfo.PageNumber = 1;
            query.PageInfo.PagingCookie = null;

            retrieveRequest.Query = query;
            var retrievedEntities = this.GetKeys(retrieveRequest);

            List<string> keyList = new List<string>();
            retrievedEntities.ForEach(be => keyList.Add(((EntityReference)be.Attributes["objectid"]).Id.ToString()));
            return keyList;
        }
Esempio n. 42
0
 public EntityCollection RetrieveMultiple(QueryBase query)
 {
     var request = new RetrieveMultipleRequest
     {
         Query = query
     };
     return ((RetrieveMultipleResponse) Execute(request)).EntityCollection;
 }
        /// <summary>
        /// Gets a list of entity keys for entities that have been disassociated.
        /// </summary>
        /// <param name="request">The CRM <c>RetrieveMultipleRequest</c> that contains the request object for the entity keys to be retrieved.</param>
        /// <returns>A <c>List</c> of CRM <c>Entiy</c> objects.</returns>
        private List<Entity> GetDissassociateRelationshipKeys(RetrieveMultipleRequest request)
        {
            List<Entity> retrievedEntities = new List<Entity>();
            while (true)
            {
                RetrieveMultipleResponse retrieveResponse = (RetrieveMultipleResponse)this.CallCrmExecuteWebMethod(request);
                var results = retrieveResponse.EntityCollection;
                if (results != null)
                {
                    retrievedEntities.AddRange(retrieveResponse.EntityCollection.Entities.ToList());
                }

                if (results.MoreRecords)
                {
                    ((QueryExpression)request.Query).PageInfo.PageNumber++;
                    ((QueryExpression)request.Query).PageInfo.PagingCookie = results.PagingCookie;
                }
                else
                {
                    break;
                }
            }

            return retrievedEntities;
        }
        public void When_executing_fetchxml_with_count_attribute_only_that_number_of_results_is_returned()
        {
            //This will test a query expression is generated and executed

            var ctx = new XrmFakedContext();

            //Arrange
            var contactList = new List<Entity>();
            for(var i=0; i < 20; i++)
            {
                contactList.Add(new Contact() { Id = Guid.NewGuid() });
            }
            ctx.Initialize(contactList);

            //Act
            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' count='7'>
                              <entity name='contact'>
                                    <attribute name='fullname' />
                                    <attribute name='telephone1' />
                                    <attribute name='contactid' /> 
                                  </entity>
                            </fetch>";


            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(fetchXml)
            };

            var service = ctx.GetFakedOrganizationService();
            var response = service.Execute(retrieveMultiple) as RetrieveMultipleResponse;

            Assert.Equal(7, response.EntityCollection.Entities.Count);
        }
        public void When_querying_the_same_entity_records_with_joins_no_collection_modified_exception_is_thrown()
        {
            var fakedContext = new XrmFakedContext { };
            var service = fakedContext.GetFakedOrganizationService();

            var entityAccount = new Account { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!", LogicalName = "account" };
            var entityContact = new Contact { Id = Guid.NewGuid(), ParentCustomerId = entityAccount.ToEntityReference() };

            var entityBusinessUnit = new BusinessUnit { Name = "TestBU", BusinessUnitId = Guid.NewGuid() };

            var initiatingUser = new SystemUser
            {
                Id = Guid.NewGuid(),
                FirstName = "TestUser",
                DomainName = "TestDomain",
                BusinessUnitId = entityBusinessUnit.ToEntityReference()
            };

            fakedContext.Initialize(new List<Entity>() {
               entityBusinessUnit,entityAccount,entityContact,initiatingUser
            });


            var fetchXml = @"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                      <entity name='systemuser'>
                        <attribute name='fullname' />
                         <attribute name='systemuserid' />
                         <attribute name='businessunitid' />
                         <filter type='and'>
                          <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='#userId#' />
                         </filter>
                            <link-entity name='businessunit' from='businessunitid' to='businessunitid' alias='bu' intersect='true' >
                                <attribute name='name' />
                            </link-entity>
                      </entity>
                    </fetch>
                ";

            var UserRequest = new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml.Replace("#userId#", initiatingUser.Id.ToString())) };
            var response = ((RetrieveMultipleResponse)service.Execute(UserRequest));

            var entities = response.EntityCollection.Entities;
            Assert.True(entities.Count == 1);
            Assert.True(entities[0].Attributes.ContainsKey("bu.name"));
            Assert.IsType<AliasedValue>(entities[0]["bu.name"]);
            Assert.Equal("TestBU", (entities[0]["bu.name"] as AliasedValue).Value.ToString());
        }
Esempio n. 46
0
        /// <summary>
        /// Create a view.
        /// Retrieve Views
        /// Deactivate a view
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        /// <param name="promptForReactivate">When True, the user will be prompted to reactivate
        /// a view that was deactivated.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete, bool promptForReactivate)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

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

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

                    SavedQuery sq = new SavedQuery
                    {
                        Name = "A New Custom Public View",
                        Description = "A Saved Query created in code",
                        ReturnedTypeCode = "opportunity",
                        FetchXml = fetchXml,
                        LayoutXml = layoutXml,
                        QueryType = 0
                    };
                    
                    _customViewId = _serviceProxy.Create(sq);
                    Console.WriteLine("A new view with the name {0} was created.", sq.Name);
                    //</snippetWorkWithViews1>

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

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

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

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

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

                    RetrieveMultipleRequest retrieveOpportuntiesViewRequest = new RetrieveMultipleRequest { Query = ClosedOpportunitiesViewQuery };

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

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

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


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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// Gets an instance of the <c>customeraddress</c> class.
        /// </summary>
        /// <param name="addressIntegrationKeyValue">The value of the address's dynamics_integrationkey property to query for.</param>
        /// <param name="parentKey">The parent of this address to use when querying for the existence of this address instance.</param>
        /// <param name="adapter">An instance of the <c>CRM2011Adapter</c> class to use when calling CRM.</param>
        /// <param name="addressIntegrationKeyProperty">The key attribute on the <c>customeraddress</c> that the supplied value is for.</param>
        /// <returns>A new instance with it's dynamics_integrationkey initialized to the value supplied or an existing instance.</returns>
        public static Entity GetDynamicAddressInstance(string addressIntegrationKeyValue, Guid parentKey, DynamicCrmAdapter adapter, string addressIntegrationKeyProperty)
        {
            if (parentKey == null || adapter == null)
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage)) { ExceptionId = AdapterException.SystemExceptionGuid };
            }

            if (string.IsNullOrEmpty(addressIntegrationKeyProperty))
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.AddressIntegrationKeyPropertyInvalidMessage)) { ExceptionId = ErrorCodes.AddressIntegrationKeyPropertyException };
            }

            RetrieveMultipleRequest retrieveRequest = new RetrieveMultipleRequest();
            KeyValuePair<string, string>[] propertyValues = new KeyValuePair<string, string>[2];
            propertyValues[0] = new KeyValuePair<string, string>(addressIntegrationKeyProperty, addressIntegrationKeyValue);
            propertyValues[1] = new KeyValuePair<string, string>("parentid", parentKey.ToString());
            retrieveRequest.Query = CRM2011AdapterUtilities.GetMultipartQueryExpression(LogicalOperator.And, "customeraddress", propertyValues);
            RetrieveMultipleResponse retrieveResponse = (RetrieveMultipleResponse)adapter.OrganizationService.Execute(retrieveRequest);
            Entity returnedEntity = null;

            if (retrieveResponse.EntityCollection.Entities.Count == 1)
            {
                returnedEntity = retrieveResponse.EntityCollection.Entities[0] as Entity;
                returnedEntity[CRM2011AdapterUtilities.IsNew] = false;
                return returnedEntity;
            }
            else if (retrieveResponse.EntityCollection.Entities.Count < 1)
            {
                // this is a new entity instance and we need to map the provided data onto the DynamicsEntity
                returnedEntity = new Entity() { LogicalName = "customeraddress" };
                if (addressIntegrationKeyProperty.Equals("customeraddressid", StringComparison.OrdinalIgnoreCase))
                {
                    returnedEntity[addressIntegrationKeyProperty] = new Guid(addressIntegrationKeyValue);
                }
                else
                {
                    returnedEntity[addressIntegrationKeyProperty] = addressIntegrationKeyValue;
                }

                returnedEntity[CRM2011AdapterUtilities.IsNew] = true;
                return returnedEntity;
            }
            else
            {
                throw new AdapterException(
                    string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.MultipleDynamicEntitiesReturnedExceptionMessage,
                    "customeraddress",
                    addressIntegrationKeyProperty,
                    addressIntegrationKeyValue))
                {
                    ExceptionId = ErrorCodes.MultipleCustomerAddressResult
                };
            }
        }
		/// <summary>
		/// This method first connects to the Organization service. Afterwards,
		/// basic Fetch queries are performed.
		/// </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
			{
				//<snippetRetrieveMultipleConditionOperatorsFetch1>
				// 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();

                    _service = (IOrganizationService)_serviceProxy;

					CreateRequiredRecords();

					#region SQL Query Translated to Fetch
                    //<snippetRetrieveMultipleConditionOperatorsFetch2>
					// Build the following SQL query using QueryExpression:
					//
					//		SELECT contact.fullname, contact.address1_telephone1
					//		FROM contact
					//			LEFT OUTER JOIN account
					//				ON contact.parentcustomerid = account.accountid
					//				AND
					//				account.name = 'Litware, Inc.'
					//		WHERE (contact.address1_stateorprovince = 'WA'
					//		AND
					//			contact.address1_city in ('Redmond', 'Bellevue', 'Kirkland', 'Seattle')
					//		AND 
					//			contact.address1_telephone1 like '(206)%'
					//			OR
					//			contact.address1_telephone1 like '(425)%'
					//		AND
					//			DATEDIFF(DAY, contact.createdon, GETDATE()) > 0
					//		AND
					//			DATEDIFF(DAY, contact.createdon, GETDATE()) < 30
					//		AND
					//			contact.emailaddress1 Not NULL
					//			   )

					String fetchXml = @"<fetch mapping=""logical"" count=""50"" version=""1.0"">
											<entity name=""contact"">
												<attribute name=""address1_telephone1"" />
												<attribute name=""contactid"" />
												<attribute name=""firstname"" />
												<attribute name=""lastname"" />
												<filter>
													<condition attribute=""address1_stateorprovince"" operator=""eq"" value=""WA"" />
													<condition attribute=""address1_city"" operator=""in"">
														<value>Redmond</value>
														<value>Bellevue</value>
														<value>Kirkland</value>
														<value>Seattle</value>
													</condition>
													<condition attribute=""createdon"" operator=""last-x-days"" value=""30"" />
													<condition attribute=""emailaddress1"" operator=""not-null"" />
													<filter type=""or"">
														<condition attribute=""address1_telephone1"" operator=""like"" value=""(206)%"" />
														<condition attribute=""address1_telephone1"" operator=""like"" value=""(425)%"" />
													</filter>
												</filter>
												<link-entity name=""account"" from=""accountid"" to=""parentcustomerid"">
													<filter>
														<condition attribute=""name"" operator=""eq"" value=""Litware, Inc."" />
													</filter>
												</link-entity>
											</entity>
										</fetch>";

					// Build fetch request and obtain results.
                    RetrieveMultipleRequest efr = new RetrieveMultipleRequest()
                    {
                        Query = new FetchExpression(fetchXml)
                    };

                    EntityCollection entityResults = ((RetrieveMultipleResponse)_service.Execute(efr)).EntityCollection;
 

					// Display the results.
					Console.WriteLine("List all contacts matching specified parameters");
					Console.WriteLine("===============================================");
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Contact ID: {0}", e.Id);
                    }


					Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //</snippetRetrieveMultipleConditionOperatorsFetch2>
					#endregion

					#region Find all orders fulfilled in the last fiscal period
                    //<snippetRetrieveMultipleConditionOperatorsFetch3>
					fetchXml = @"<fetch>
									<entity name='salesorder'>
										<attribute name='name'/>
										<filter type='and'>
											<condition attribute='datefulfilled' 
												operator='last-fiscal-period'/>
										</filter>
									</entity>
								</fetch>";

					// Build fetch request and obtain results.
					efr = new RetrieveMultipleRequest()
					{
                        Query = new FetchExpression(fetchXml)
					};
                    entityResults = ((RetrieveMultipleResponse)_service.Execute(efr)).EntityCollection;
 
					// Display results.
					Console.WriteLine("List all orders fulfilled in the last fiscal period");
					Console.WriteLine("===================================================");
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Fetch Retrieved: {0}", e.Attributes["name"]);
                    }

					Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //</snippetRetrieveMultipleConditionOperatorsFetch3>
					#endregion

					#region Find all Opportunities with estimated close date in next 3 fiscal years
                    //<snippetRetrieveMultipleConditionOperatorsFetch4>
					fetchXml = @"<fetch>
									<entity name='opportunity'>
											<attribute name='name'/>
											<filter type='and'>
													<condition attribute='estimatedclosedate'
															   operator='next-x-fiscal-years'
															   value='3'/>
											</filter>
									</entity>
								</fetch>";

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

										// Display results.
					Console.WriteLine("List all opportunities with estimated close date in next 3 fiscal years");
					Console.WriteLine("=======================================================================");
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Fetch Retrieved: {0}", e.Attributes["name"]);
                    };
                    
					Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //</snippetRetrieveMultipleConditionOperatorsFetch4>
					#endregion

					#region Find all Orders fulfilled in fiscal year 2008
                    //<snippetRetrieveMultipleConditionOperatorsFetch5>
					fetchXml = @"<fetch>
									<entity name='salesorder'>
											<attribute name='name'/>
											<filter type='and'>
													<condition attribute='datefulfilled'
															   operator='in-fiscal-year'
															   value='2008'/>
											</filter>
									</entity>
								</fetch>";

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

					
					// Display results.
					Console.WriteLine("List all orders fulfilled in fiscal year 2008");
					Console.WriteLine("=============================================");
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Fetch Retrieved: {0}", e.Attributes["name"]);
                    }
					Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //</snippetRetrieveMultipleConditionOperatorsFetch5>
					#endregion

					#region Find all Orders fulfilled in period 3 of any fiscal year
                    //<snippetRetrieveMultipleConditionOperatorsFetch6>
					fetchXml = @"<fetch>
									<entity name='salesorder'>
											<attribute name='name'/>
											<filter type='and'>
													<condition attribute='datefulfilled'
															   operator='in-fiscal-period'
															   value='3'/>
											</filter>
									</entity>
								</fetch>";

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

					
					// Display results.
					Console.WriteLine("List all orders fulfilled in period 3 of any fiscal year");
					Console.WriteLine("========================================================");
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Fetch Retrieved: {0}", e.Attributes["name"]);
                    }
					Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //</snippetRetrieveMultipleConditionOperatorsFetch6>
					#endregion

					#region Find all Orders fulfilled in period 3 of fiscal year 2008
                    //<snippetRetrieveMultipleConditionOperatorsFetch7>
					fetchXml = @"<fetch>
									<entity name='salesorder'>
											<attribute name='name'/>
											<filter type='and'>
													<condition attribute='datefulfilled' operator='in-fiscal-period-and-year'>
															<value>3</value>
															<value>2008</value>
													</condition>
											</filter>
									</entity>
								</fetch>";

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

					
					// Display results.
					Console.WriteLine("List all orders fulfilled in period 3 of fiscal year 2008");
					Console.WriteLine("=========================================================");
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Fetch Retrieved: {0}", e.Attributes["name"]);
                    }
					Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //</snippetRetrieveMultipleConditionOperatorsFetch7>
					#endregion

					// Note: the following two queries use aggregation which is only
					// possible to perform in Fetch, not in QueryExpression or LINQ.

					#region Sum the total amount of all orders, grouped by year
                    //<snippetRetrieveMultipleConditionOperatorsFetch8>
					fetchXml = @"<fetch aggregate='true'>
									<entity name='salesorder'>
										<attribute name='totalamount' aggregate='sum' alias='total'/>
										<attribute name='datefulfilled' groupby='true' dategrouping='fiscal-year' alias='datefulfilled'/>
									</entity>
								 </fetch>";

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

					// Display results.
					Console.WriteLine("List totals of all orders grouped by year");
					Console.WriteLine("=========================================");
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Fetch Retrieved Total: {0}", e.FormattedValues["total"]);
                    } 
                    
 					Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //</snippetRetrieveMultipleConditionOperatorsFetch8>
					#endregion

					#region Sum the total amount of all Orders grouped by period and year
                    //<snippetRetrieveMultipleConditionOperatorsFetch9>
					fetchXml = @"<fetch aggregate='true'>
									<entity name='salesorder'>
										<attribute name='totalamount' aggregate='sum' alias='total'/>
										<attribute name='datefulfilled' groupby='true' dategrouping='fiscal-period' alias='datefulfilled'/>
									</entity>
								 </fetch>";

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

					
					// Display results.
					Console.WriteLine("List total of all orders grouped by period and year");
					Console.WriteLine("===================================================");
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Fetch Retrieved: {0}", e.FormattedValues["total"]);
                    }
					Console.WriteLine("<End of Listing>");
                    Console.WriteLine();
                    //</snippetRetrieveMultipleConditionOperatorsFetch9>
					#endregion

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

			// Catch any service fault exceptions that Microsoft Dynamics CRM throws.
			catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
			{
				// You can handle an exception here or pass it back to the calling method.
				throw;
			}
		}
        public IEnumerable<EntityReference> Get(IOrganizationService service, string fetchXml, int fetchCount)
        {
            int pageNumber = 1;
            EntityCollection returnCollection = null;
            while (true)
            {
                // Build fetchXml string with the placeholders.
                var xml = CreateXml(fetchXml, pageNumber, fetchCount);
                xml = xml.RemoveDuplicateAliasJ();
                // Excute the fetch query and get the xml result.
                var fetchRequest1 = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };
                try
                {
                    returnCollection = ((RetrieveMultipleResponse)service.Execute(fetchRequest1)).EntityCollection;
                }
                catch (FaultException<OrganizationServiceFault> ee)
                {
                    // You can handle an exception here or pass it back to the calling method.
                    Log(ee, "FetchExpression:" + xml);
                    break;
                }
                if (returnCollection != null)
                {
                    foreach (Entity entityMember in returnCollection.Entities)
                        yield return entityMember.ToEntityReference();

                    // Check for morerecords, if it returns 1.
                    if (returnCollection.MoreRecords)
                        pageNumber++;// Increment the page number to retrieve the next page.

                    else
                        break; // If no more records in the result nodes, exit the loop.
                }
            }
        }
        /// <summary>
        /// Exports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="DataExportReportFileName">Name of the data export report file.</param>
        private void Export(MSCRMDataExportProfile profile, string DataExportReportFileName)
        {
            try
            {
                DataExportReport report = new DataExportReport(DataExportReportFileName);
                //Get Data Export Report
                if (File.Exists(DataExportReportFileName))
                {
                    report = ReadReport(DataExportReportFileName);
                }

                //Set Data export folder
                string dataExportFolder = Folder + "\\" + profile.ProfileName + "\\Data";
                if (!Directory.Exists(dataExportFolder))
                {
                    Directory.CreateDirectory(dataExportFolder);
                }

                MSCRMConnection connection = profile.getSourceConneciton();
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                profile.TotalExportedRecords = 0;
                //Mesure export time
                DateTime exportStartDT = DateTime.Now;

                LogManager.WriteLog("Start exporting data from " + connection.ConnectionName);

                //Set the number of records per page to retrieve.
                //This value should not be bigger than 5000 as this is the limit of records provided by the CRM
                int fetchCount = 5000;
                // Initialize the file number.
                int fileNumber = 1;
                // Initialize the number of records.
                int recordsCount = 0;
                // Specify the current paging cookie. For retrieving the first page, pagingCookie should be null.
                string pagingCookie = null;
                string entityName = "";

                DateTime now = DateTime.Now;
                string fileName = Folder + "\\" + profile.ProfileName + "\\Data\\ExportedData";
                string fileExtension = profile.ExportFormat.ToLower();
                if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                    fileExtension = "xml";

                fileName += now.Year + "-" + now.Month + "-" + now.Day + "-" + now.Hour + "-" + now.Minute + "-" + now.Second + "." + fileExtension;
                this.ExportedDataFileName = fileName;

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

                    StringReader stringReader = new StringReader(profile.FetchXMLQuery);
                    XmlTextReader reader = new XmlTextReader(stringReader);
                    // Load document
                    XmlDocument doc = new XmlDocument();
                    doc.Load(reader);
                    XmlNodeList xnl = doc.ChildNodes[0].ChildNodes[0].ChildNodes;

                    List<string> columns = new List<string>();
                    List<string> DisplayedColumns = new List<string>();
                    foreach (XmlNode sm in xnl)
                    {
                        if (sm.Name == "attribute")
                        {
                            columns.Add(sm.Attributes[0].Value);
                            if (profile.ExportFormat.ToLower() == "csv")
                                DisplayedColumns.Add(profile.DataSeparator + sm.Attributes[0].Value + profile.DataSeparator);
                            else if (profile.ExportFormat.ToLower() == "xml")
                                DisplayedColumns.Add(sm.Attributes[0].Value);
                            else if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                                DisplayedColumns.Add(sm.Attributes[0].Value);
                        }
                        else if (sm.Name == "link-entity")
                        {
                            //Linked entity
                            string linkedEntityAlias = sm.Attributes.GetNamedItem("alias").Value;
                            string linkedAttributeyName = sm.Attributes.GetNamedItem("to").Value;
                            XmlNodeList xnlLinkedEntity = sm.ChildNodes;
                            foreach (XmlNode linkedAttribute in xnlLinkedEntity)
                            {
                                //Check if this is not a filter
                                if (linkedAttribute.Name == "filter")
                                    continue;

                                columns.Add(linkedEntityAlias + "." + linkedAttribute.Attributes[0].Value);
                                if (profile.ExportFormat.ToLower() == "csv")
                                    DisplayedColumns.Add(profile.DataSeparator + linkedAttributeyName + "_" + linkedAttribute.Attributes[0].Value + profile.DataSeparator);
                                else if (profile.ExportFormat.ToLower() == "xml")
                                    DisplayedColumns.Add(linkedAttributeyName + "_" + linkedAttribute.Attributes[0].Value);
                                else if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                                    DisplayedColumns.Add(linkedAttributeyName + "_" + linkedAttribute.Attributes[0].Value);
                            }
                        }
                    }

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

                    EntityCollection returnCollection = ((RetrieveMultipleResponse)_serviceProxy.Execute(fetchRequest)).EntityCollection;
                    recordsCount += returnCollection.Entities.Count;
                    if (recordsCount > 0)
                    {
                        if (profile.ExportFormat.ToLower() == "csv")
                            WriteCSV(returnCollection, fileName, columns, DisplayedColumns, profile);
                        else if (profile.ExportFormat.ToLower() == "xml")
                            WriteXML(returnCollection, fileName, columns, DisplayedColumns, profile);
                        else if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                            WriteXMLSpreadsheet2003(returnCollection, fileName, columns, DisplayedColumns, profile);
                    }
                    // Check for more records, if it returns 1.
                    if (returnCollection.MoreRecords)
                    {
                        // Increment the page number to retrieve the next page.
                        fileNumber++;
                        pagingCookie = returnCollection.PagingCookie;
                    }
                    else
                    {
                        // If no more records in the result nodes, exit the loop.
                        break;
                    }
                }

                Encoding encoding = GetEncoding(profile.Encoding);

                if (profile.ExportFormat.ToLower() == "xml")
                {
                    using (var writer = new StreamWriter(fileName, true, encoding))
                    {
                        writer.WriteLine("</Records>");
                        writer.Flush();
                    }
                }
                else if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                {
                    using (var writer = new StreamWriter(fileName, true, encoding))
                    {
                        writer.WriteLine("</Table></Worksheet></Workbook>\n");
                        writer.Flush();
                    }
                }

                LogManager.WriteLog("Exported " + recordsCount + " " + entityName + " records.");

                report.TotalExportedRecords = recordsCount;
                ExportedRecordsNumber = recordsCount;
                //Delete file if  no record found
                if (recordsCount < 1)
                    File.Delete(fileName);

                WriteReport(report, DataExportReportFileName);

                TimeSpan exportTimeSpan = DateTime.Now - exportStartDT;
                LogManager.WriteLog("Export finished for " + profile.ProfileName + ". Exported " + recordsCount + " records in " + exportTimeSpan.ToString().Substring(0, 10));
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                throw;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                else
                    LogManager.WriteLog("Error:" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// Retrieves entity relationships
        /// </summary>
        /// <param name="entityRelationshipName">The name of the relationship.</param>
        /// <param name="entity1Name">The name of the first entity in the relationship.</param>
        /// <param name="entity1IntersectAtt">The name of the first entity's intersecting CRM attribute.</param>
        /// <returns>A CRM <c>RetrieveMultipleResponse</c> that contains the matching relationships.</returns>
        private RetrieveMultipleResponse AssociatedRetrival(string entityRelationshipName, string entity1Name, string entity1IntersectAtt)
        {
            // Setup Fetch XML.
            StringBuilder linkFetch = new StringBuilder();
            linkFetch.Append("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"true\">");
            linkFetch.Append("<entity name=\"" + entity1Name + "\">");
            linkFetch.Append("<all-attributes />");
            linkFetch.Append("<link-entity name=\"" + entityRelationshipName + "\" from=\"" + entity1IntersectAtt + "\" to=\"" + entity1IntersectAtt + "\" visible=\"false\" intersect=\"true\" alias=\"aa\">");
            linkFetch.Append("<all-attributes />");
            linkFetch.Append("</link-entity>");
            linkFetch.Append("</entity>");
            linkFetch.Append("</fetch>");

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

            var entityMetaDataResponse = this.CrmAdapter.OrganizationService.Execute(efr) as RetrieveMultipleResponse;
            return entityMetaDataResponse;
        }
        /// <summary>
        /// Exports the entity.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="fetchXml">The fetch fetchXML query.</param>
        /// <param name="RelationshipSchemaName">Name of the relationship schema.</param>
        /// <returns>The number of exported record for the Entity</returns>
        public int ExportEntity(NtoNAssociationsTransportProfile profile, string fetchXml, string RelationshipSchemaName)
        {
            //Set the number of records per page to retrieve.
            //This value should not be bigger than 5000 as this is the limit of records provided by the CRM
            int fetchCount = 5000;
            // Initialize the file number.
            int fileNumber = 1;
            // Initialize the number of records.
            int recordCount = 0;
            // Specify the current paging cookie. For retrieving the first page, pagingCookie should be null.
            string pagingCookie = null;
            string entityName = "";

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

                // Execute the fetch query and get the xml result.

                RetrieveMultipleRequest fetchRequest = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };

                EntityCollection returnCollection = ((RetrieveMultipleResponse)_serviceProxy.Execute(fetchRequest)).EntityCollection;
                recordCount += returnCollection.Entities.Count;
                if (recordCount > 0)
                {
                    string entityFolderName = Folder + "\\" + profile.ProfileName + "\\Data\\" + RelationshipSchemaName;
                    entityName = returnCollection.EntityName;
                    if (!Directory.Exists(entityFolderName))
                        Directory.CreateDirectory(entityFolderName);
                    List<Type> knownTypes = new List<Type>();
                    knownTypes.Add(typeof(Entity));
                    int fileCpt = 1000000 + fileNumber;
                    string filename = entityFolderName + "\\" + fileCpt + ".xml";
                    FileStream writer = new FileStream(filename, FileMode.Create);
                    DataContractSerializer ser = new DataContractSerializer(typeof(EntityCollection), knownTypes);
                    ser.WriteObject(writer, returnCollection);
                    writer.Close();
                }
                // Check for more records, if it returns 1.
                if (returnCollection.MoreRecords)
                {
                    // Increment the page number to retrieve the next page.
                    fileNumber++;
                    pagingCookie = returnCollection.PagingCookie;
                }
                else
                {
                    // If no more records in the result nodes, exit the loop.
                    break;
                }
            }

            if (recordCount > 0)
            {
                //Save Exported Entites number
                foreach (SelectedNtoNRelationship ee in profile.SelectedNtoNRelationships)
                {
                    if (RelationshipSchemaName == ee.RelationshipSchemaName)
                    {
                        ee.ExportedRecords = recordCount;
                    }
                }

                profile.TotalExportedRecords += recordCount;
                UpdateProfile(profile);
            }
            LogManager.WriteLog("Exported " + recordCount + " " + entityName + " records.");

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

                    _service = (IOrganizationService)_serviceProxy;

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

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

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

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

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

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

                        EntityCollection returnCollection = ((RetrieveMultipleResponse)_service.Execute(fetchRequest1)).EntityCollection;
                        
                        foreach (var c in returnCollection.Entities)
                        {
                            System.Console.WriteLine("{0}.\t{1}\t\t{2}", ++recordCount, c.Attributes["name"], c.Attributes["emailaddress1"] );
                        }                        
                        
                        // Check for morerecords, if it returns 1.
                        if (returnCollection.MoreRecords)
                        {
                            Console.WriteLine("\n****************\nPage number {0}\n****************", pageNumber);
                            Console.WriteLine("#\tAccount Name\t\t\tEmail Address");
                            
                            // Increment the page number to retrieve the next page.
                            pageNumber++;

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

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
            return;
        }
 private RetrieveMultipleRequest GetRetrieveMultipleRequest(CrmDbCommand command, CommandBehavior behavior)
 {
     var entityName = command.CommandText;
     if (entityName.Contains(" "))
     {
         throw new ArgumentException("When CommandType is TableDirect, CommandText should be the name of an entity.");
     }
     var request = new RetrieveMultipleRequest()
     {
         Query = new QueryExpression(entityName) { ColumnSet = new ColumnSet(true), PageInfo = new PagingInfo() { ReturnTotalRecordCount = true } }
     };
     return request;
 }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// records are retrieved from the systemuserroles intersect table via three
        /// methods: Query Expression, Fetch, and LINQ.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

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

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

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

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

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

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

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

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

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

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

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

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

                    #endregion
                    //</snippetRetrieveRecordsFromAnIntersectTable3>
                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, an 
        /// authorization profile is created, and associated to a team. Then an entity
        /// is created and permissions for the entity are assigned to the profile. These
        /// permissions are then retrieved.
        /// </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
            {
                //<snippetRetrieveSecuredFieldsForAUser1>
                // 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();

                    CreateRequiredRecords();

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

                    // Add team to profile.
                    AssociateRequest teamToProfile = new AssociateRequest()
                    {
                        Target = new EntityReference(FieldSecurityProfile.EntityLogicalName,
                            _profileId),
                        RelatedEntities = new EntityReferenceCollection()
                        {
                            new EntityReference(Team.EntityLogicalName, _teamId)
                        },
                        Relationship = new Relationship("teamprofiles_association")
                    };
                    _serviceProxy.Execute(teamToProfile);

                    // Add user to the profile.
                    AssociateRequest userToProfile = new AssociateRequest()
                    {
                        Target = new EntityReference(FieldSecurityProfile.EntityLogicalName,
                            _profileId),
                        RelatedEntities = new EntityReferenceCollection()
                        {
                            new EntityReference(SystemUser.EntityLogicalName, _userId)
                        },
                        Relationship = new Relationship("systemuserprofiles_association")
                    };
                    _serviceProxy.Execute(userToProfile);

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

                    // Add privileges for the Tweet entity to the Marketing Role.
                    RolePrivilege[] privileges = new RolePrivilege[3];

                    // SDK: prvCreateActivity
                    privileges[0] = new RolePrivilege();
                    privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}");
                    privileges[0].Depth = PrivilegeDepth.Global;

                    // SDK: prvReadActivity
                    privileges[1] = new RolePrivilege();
                    privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}");
                    privileges[1].Depth = PrivilegeDepth.Global;

                    // SDK: prvWriteActivity
                    privileges[2] = new RolePrivilege();
                    privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}");
                    privileges[2].Depth = PrivilegeDepth.Global;

                    // Create and execute the request.
                    AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest()
                    {
                        RoleId = _roleId,
                        Privileges = privileges
                    };
                    AddPrivilegesRoleResponse response =
                        (AddPrivilegesRoleResponse)_serviceProxy.Execute(request);

                    // Create custom identity attribute.
                    CreateAttributeRequest attrReq = new CreateAttributeRequest()
                    {
                        Attribute = new StringAttributeMetadata()
                        {
                            LogicalName = "new_identity",
                            DisplayName = new Label("Identity", 1033),
                            SchemaName = "New_Identity",
                            MaxLength = 500,
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(
                                AttributeRequiredLevel.Recommended),
                            IsSecured = true
                        },
                        EntityName = "new_tweet"
                    };
                    CreateAttributeResponse identityAttributeResponse =
                        (CreateAttributeResponse)_serviceProxy.Execute(attrReq);
                    _identityId = identityAttributeResponse.AttributeId;
                    Console.Write("Identity Created, ");

                    // Create custom message attribute.
                    attrReq = new CreateAttributeRequest()
                    {
                        Attribute = new StringAttributeMetadata()
                        {
                            LogicalName = "new_message",
                            DisplayName = new Label("Message", 1033),
                            SchemaName = "New_Message",
                            MaxLength = 140,
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(
                                AttributeRequiredLevel.Recommended),
                            IsSecured = true
                        },
                        EntityName = "new_tweet"
                    };
                    CreateAttributeResponse messageAttributeResponse =
                        (CreateAttributeResponse)_serviceProxy.Execute(attrReq);
                    _messageId = messageAttributeResponse.AttributeId;
                    Console.Write("Message Created, ");

                    // Create field permission object for Identity.
                    FieldPermission identityPermission = new FieldPermission();
                    identityPermission.AttributeLogicalName = "new_identity";
                    identityPermission.EntityName = "new_tweet";
                    identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed);
                    identityPermission.FieldSecurityProfileId = new EntityReference(
                        FieldSecurityProfile.EntityLogicalName, _profileId);
                    _identityPermissionId = _serviceProxy.Create(identityPermission);
                    Console.Write("Permission Created, ");

                    // Create list for storing retrieved profiles.
                    List<Guid> profileIds = new List<Guid>();

                    // Build query to obtain the field security profiles.
                    QueryExpression qe = new QueryExpression()
                    {
                        EntityName = FieldSecurityProfile.EntityLogicalName,
                        ColumnSet = new ColumnSet("fieldsecurityprofileid"),
                        LinkEntities =
                        {
                            new LinkEntity
                            {
                                LinkFromEntityName = FieldSecurityProfile.EntityLogicalName,
                                LinkToEntityName = SystemUser.EntityLogicalName,
                                LinkCriteria = 
                                {
                                    Conditions = 
                                    {
                                        new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId)
                                    }
                                }
                            }
                        }
                    };

                    // Execute the query and obtain the results.
                    RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest()
                    {
                        Query = qe
                    };

                    EntityCollection bec = ((RetrieveMultipleResponse)_serviceProxy.Execute(
                        rmRequest)).EntityCollection;

                    // Extract profiles from query result.
                    foreach (FieldSecurityProfile profileEnt in bec.Entities)
                    {
                        profileIds.Add(profileEnt.FieldSecurityProfileId.Value);
                    }
                    Console.Write("Profiles Retrieved, ");

                    // Retrieve attribute permissions of a FieldSecurityProfile.
                    DataCollection<Entity> dc;

                    // Retrieve the attributes.
                    QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName);
                    qba.AddAttributeValue("fieldsecurityprofileid", _profileId);
                    qba.ColumnSet = new ColumnSet("attributelogicalname");

                    dc = _serviceProxy.RetrieveMultiple(qba).Entities;
                    Console.Write("Attributes Retrieved. ");

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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// Retrieves the associations that have been deleted using the audit functionality in CRM.
        /// </summary>
        /// <param name="modifiedDate">The <see cref="DateTime"/> to check for disassociations for in the audit history.</param>
        /// <returns>An <see cref="ICollection"/> of the entities that have been disassociated.</returns>
        private ICollection GetDissassociateRelationship(DateTime modifiedDate)
        {
            RetrieveMultipleRequest retrieveRequest = new RetrieveMultipleRequest();
            var query = new QueryExpression("audit");
            query.ColumnSet = new ColumnSet(true);
            query.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.GreaterEqual, modifiedDate));
            query.Criteria.AddCondition(new ConditionExpression("action", ConditionOperator.Equal, 34));
            query.PageInfo = new PagingInfo();
            query.PageInfo.Count = 5000;
            query.PageInfo.PageNumber = 1;
            query.PageInfo.PagingCookie = null;

            retrieveRequest.Query = query;
            var retrievedEntities = this.GetDissassociateRelationshipKeys(retrieveRequest);

            var entitysMetaDataRequest = new RetrieveAllEntitiesRequest();
            entitysMetaDataRequest.EntityFilters = EntityFilters.Relationships;
            entitysMetaDataRequest.RetrieveAsIfPublished = true;
            var entitysMetaDataResponse = this.CrmAdapter.OrganizationService.Execute(entitysMetaDataRequest) as RetrieveAllEntitiesResponse;

            List<ManyToManyRelationshipMetadata> entityMToMRelationships = new List<ManyToManyRelationshipMetadata>();
            foreach (EntityMetadata crmMetadata in entitysMetaDataResponse.EntityMetadata)
            {
                entityMToMRelationships = (from meta in crmMetadata.ManyToManyRelationships
                                           where meta.SchemaName == this.ProvidedEntityName
                                           select meta).ToList();

                if (entityMToMRelationships.Count > 0)
                {
                    break;
                }
            }

            if (entityMToMRelationships.Count > 0)
            {
                string strEntityRelationshipName = entityMToMRelationships[0].IntersectEntityName;
                string entity1Name = entityMToMRelationships[0].Entity1LogicalName;
                string entity1IntersectAtt = entityMToMRelationships[0].Entity1IntersectAttribute;
                string entity2Name = entityMToMRelationships[0].Entity2LogicalName;
                string entity2IntersectAtt = entityMToMRelationships[0].Entity2IntersectAttribute;

                List<RelationshipData> keyList = new List<RelationshipData>();
                foreach (Entity crmEntity in retrievedEntities)
                {
                    string transactionID = crmEntity.Attributes["transactionid"].ToString();
                    var retrievedTransactionEntities = (from meta in retrievedEntities
                                                        where meta.Attributes["transactionid"].ToString() == transactionID.ToString()
                                                        select meta).ToList();

                    Dictionary<string, object> entityDictionary = new Dictionary<string, object>();
                    if (retrievedTransactionEntities.Count < 2)
                    {
                        continue;
                    }

                    bool entity1NameID = false;
                    bool entity2NameID = false;
                    foreach (Entity crmTransEntity in retrievedTransactionEntities)
                    {
                        EntityReference objectID = (EntityReference)crmTransEntity.Attributes["objectid"];

                        if (objectID.LogicalName == entity1Name)
                        {
                            entityDictionary.Add(entity1IntersectAtt, objectID.Id.ToString());
                            entity1NameID = true;
                        }

                        if (objectID.LogicalName == entity2Name)
                        {
                            entityDictionary.Add(entity2IntersectAtt, objectID.Id.ToString());
                            entity2NameID = true;
                        }
                    }

                    if (!entity1NameID || !entity2NameID)
                    {
                        continue;
                    }

                    entityDictionary.Add("ProvidedEntityName", this.ProvidedEntityName);
                    entityDictionary.Add("EntityRelationshipName", strEntityRelationshipName);
                    entityDictionary.Add("Entity1Name", entity1Name);
                    entityDictionary.Add("Entity1IntersectAtt", entity1IntersectAtt);
                    entityDictionary.Add("Entity2Name", entity2Name);
                    entityDictionary.Add("Entity2IntersectAtt", entity2IntersectAtt);

                    RelationshipData relationshipData = new RelationshipData();
                    relationshipData.ReturnedDictionary = entityDictionary;
                    keyList.Add(relationshipData);
                }

                return keyList;
            }

            return null;
        }
        private void GetDataSet()
        {
            if (OnPageComplete != null)
                OnPageComplete(this);

			if (query is QueryExpression)
			{

				RetrieveMultipleRequest req = new RetrieveMultipleRequest();
				((QueryExpression)query).PageInfo = new PagingInfo();
				((QueryExpression)query).PageInfo.PageNumber = page++;
				((QueryExpression)query).PageInfo.Count = rowsPerPage;
				req.Query = query;
				response = (RetrieveMultipleResponse)proxy.Execute(req);
			}

			if (query is FetchExpression)
			{
				string strXml = CreateXml(((FetchExpression)query).Query, null, page++, rowsPerPage);
				((FetchExpression)query).Query = strXml;
				RetrieveMultipleRequest req = new RetrieveMultipleRequest();
				req.Query = query;
				response = (RetrieveMultipleResponse)proxy.Execute(req);
			}
        }
Esempio n. 59
0
        /// <summary>
        /// This method is used to find a record and return the GUID of records matching the criteria
        /// </summary>
        /// <param name="entityName_">CRM name of the entity you want to look for</param>
        /// <param name="primarykeyName">The attribute name containing the GUID for the entity (contactid,campaignid,...) that will be returned in an array</param>
        ///<param name="stringParams">The ArrayList containing the attributes names and their values. The research only work with string type attributes. You can use % to replace characters. A logical AND is used to concatenate the parameters in the search</param>
        public ArrayList findEntity(string entityName_, string primarykeyName, ArrayList stringParams, string attribute_order)
        {
            ArrayList arrayResults = new ArrayList();
            try
            {
                isconnected();

                ColumnSet cols = new ColumnSet();
                createStringConditionExpression(stringParams);
                cols.Attributes.Add(primarykeyName);

                m_filterExpression.FilterOperator = LogicalOperator.And;
                OrderExpression oe = new OrderExpression();
                oe.AttributeName = attribute_order;
                oe.OrderType = OrderType.Descending;
                QueryExpression query = new QueryExpression();
                query.EntityName = entityName_;
                query.ColumnSet = cols;
                query.Criteria = m_filterExpression;
                query.Orders.Add(oe);

                RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
                retrieve.Query = query;
                retrieve.ReturnDynamicEntities = true;

                RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)m_crmService.Execute(retrieve);
                int i = 0;
                foreach (DynamicEntity rec in retrieved.BusinessEntityCollection.BusinessEntities)
                {
                    Microsoft.Crm.Sdk.Key sp = (Microsoft.Crm.Sdk.Key)rec.Properties[primarykeyName];
                    arrayResults.Add(sp.Value);
                    i++;
                }
                if (i == 0) throw new entitynotfoundException();
                return arrayResults;
            }
            catch (SoapException ex)
            {
                throw new InvalidPluginExecutionException("!SoapException!\n" + ex.Detail.SelectSingleNode("//description").InnerText);
            }
            catch (entitynotfoundException)
            {
                throw new entitynotfoundException();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Esempio n. 60
0
		protected override void Execute(CodeActivityContext executionContext)
		{
			//Create the tracing service
			ITracingService tracingService = executionContext.GetExtension<ITracingService>();

			//Create the context
			IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
			IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
			IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

			tracingService.Trace("Creating Account");

			Account entity = new Account();
			entity.Name = AccountName.Get<string>(executionContext);
			Guid entityId = service.Create(entity);

			tracingService.Trace("Account created with Id {0}", entityId.ToString());

			tracingService.Trace("Create a task for the account");
			Task newTask = new Task();
			newTask.Subject = TaskSubject.Get<string>(executionContext);
			newTask.RegardingObjectId = new EntityReference(Account.EntityLogicalName, entityId);

			Guid taskId = service.Create(newTask);

			tracingService.Trace("Task has been created");

			tracingService.Trace("Retrieve the task using QueryByAttribute");
			QueryByAttribute query = new QueryByAttribute();
			query.Attributes.AddRange(new string[] { "regardingobjectid" });
			query.ColumnSet = new ColumnSet(new string[] { "subject" });
			query.EntityName = Task.EntityLogicalName;
			query.Values.AddRange(new object[] { entityId });

			tracingService.Trace("Executing the Query for entity {0}", query.EntityName);

			//Execute using a request to test the OOB (XRM) message contracts
			RetrieveMultipleRequest request = new RetrieveMultipleRequest();
			request.Query = query;
			Collection<Entity> entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;

			//Execute a request from the CRM message assembly
			tracingService.Trace("Executing a WhoAmIRequest");
			service.Execute(new WhoAmIRequest());

			if (1 != entityList.Count)
			{
				tracingService.Trace("The entity list was too long");
				throw new InvalidPluginExecutionException("Query did not execute correctly");
			}
			else
			{
				tracingService.Trace("Casting the Task from RetrieveMultiple to strong type");
				Task retrievedTask = (Task)entityList[0];

				if (retrievedTask.ActivityId != taskId)
				{
					throw new InvalidPluginExecutionException("Incorrect task was retrieved");
				}

				tracingService.Trace("Retrieving the entity from IOrganizationService");

				//Retrieve the task using Retrieve
				retrievedTask = (Task)service.Retrieve(Task.EntityLogicalName, retrievedTask.Id, new ColumnSet("subject"));
				if (!string.Equals(newTask.Subject, retrievedTask.Subject, StringComparison.Ordinal))
				{
					throw new InvalidPluginExecutionException("Task's subject did not get retrieved correctly");
				}

				//Update the task
				retrievedTask.Subject = UpdatedTaskSubject.Get<string>(executionContext);
				service.Update(retrievedTask);
			}
		}