public static bool UpdateAndPublishSingle(CrmServiceClient client, List <Entity> webResources)
        {
            //CRM 2011 < UR12
            try
            {
                OrganizationRequestCollection requests = CreateUpdateRequests(webResources);

                foreach (OrganizationRequest request in requests)
                {
                    client.Execute(request);
                    OutputLogger.WriteToOutputWindow(Resource.Message_UploadedWebResource, MessageType.Info);
                }

                string            publishXml     = CreatePublishXml(webResources);
                PublishXmlRequest publishRequest = CreatePublishRequest(publishXml);

                client.Execute(publishRequest);

                OutputLogger.WriteToOutputWindow(Resource.Message_PublishedWebResources, MessageType.Info);

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorUpdatingPublishingWebResources, ex);

                return(false);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Deletes the custom entity record that was created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the entity created in this sample.</param>
        /// </summary>
        public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these entity records deleted? (y/n)");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }

            if (deleteRecords)
            {
                var deleteOneToManyRelationshipRequest =
                    new DeleteRelationshipRequest
                {
                    Name = "new_account_contact"
                };

                service.Execute(deleteOneToManyRelationshipRequest);

                var deleteManyToManyRelationshipRequest =
                    new DeleteRelationshipRequest
                {
                    Name = "new_accounts_contacts"
                };

                service.Execute(deleteManyToManyRelationshipRequest);
                Console.WriteLine("Entity Relationships have been deleted.");
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user to delete
        /// the records created in this sample.</param>
        /// </summary>
        public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these entity records to be deleted? (y/n)");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }

            if (deleteRecords)
            {
                DeleteAttributeRequest delSeriesAttribute = new DeleteAttributeRequest
                {
                    LogicalName       = "new_customappseriesattribute",
                    EntityLogicalName = RecurringAppointmentMaster.EntityLogicalName
                };
                service.Execute(delSeriesAttribute);

                DeleteAttributeRequest delInstanceAttribute = new DeleteAttributeRequest
                {
                    LogicalName       = "new_customappinstanceattribute",
                    EntityLogicalName = Appointment.EntityLogicalName
                };
                service.Execute(delInstanceAttribute);

                // Publish all the changes to the solution.
                PublishAllXmlRequest delRequest = new PublishAllXmlRequest();
                service.Execute(delRequest);

                Console.WriteLine("Entity records have been deleted.");
            }
        }
Ejemplo n.º 4
0
        public static bool UpdateAndPublishSingle(CrmServiceClient client, List <Entity> webResources)
        {
            //CRM 2011 < UR12
            try
            {
                OrganizationRequestCollection requests = CreateUpdateRequests(webResources);

                foreach (OrganizationRequest request in requests)
                {
                    client.Execute(request);
                    OutputLogger.WriteToOutputWindow("Uploaded Web Resource", MessageType.Info);
                }

                string            publishXml     = CreatePublishXml(webResources);
                PublishXmlRequest publishRequest = CreatePublishRequest(publishXml);

                client.Execute(publishRequest);

                OutputLogger.WriteToOutputWindow("Published Web Resource(s)", MessageType.Info);

                return(true);
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                OutputLogger.WriteToOutputWindow("Error Updating And Publishing Web Resource(s) To CRM: " +
                                                 crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error);
                return(false);
            }
            catch (Exception ex)
            {
                OutputLogger.WriteToOutputWindow("Error Updating And Publishing Web Resource(s) To CRM: " +
                                                 ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error);
                return(false);
            }
        }
Ejemplo n.º 5
0
        protected static void AtualizaCrmOrigem(EntityCollection colecaoEntidades)
        {
            ExecuteMultipleRequest request = new ExecuteMultipleRequest()
            {
                Requests = new OrganizationRequestCollection(),
                Settings = new ExecuteMultipleSettings
                {
                    ContinueOnError = false, ReturnResponses = true
                }
            };

            foreach (var entidade in colecaoEntidades.Entities)
            {
                UpdateRequest updateRequest = new UpdateRequest {
                    Target = entidade
                };
                request.Requests.Add(updateRequest);
            }
            ExecuteMultipleResponse resposta = (ExecuteMultipleResponse)serviceProxyOrigem.Execute(request);
            int cont = 0;

            foreach (var item in resposta.Responses)
            {
                if (item.Fault != null)
                {
                    Console.WriteLine($"ERRO na entidade nº: {cont}!\n{item.Fault}");
                }
                cont++;
            }
            Console.WriteLine($"{cont} entidades atualizadas na origem!");
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Enable auditing on an entity.
        /// </summary>
        /// <param name="entityLogicalName">The logical name of the entity.</param>
        /// <param name="flag">True to enable auditing, otherwise false.</param>
        /// <returns>The previous value of the IsAuditEnabled attribute.</returns>
        private static bool EnableEntityAuditing(CrmServiceClient service, string entityLogicalName, bool flag)
        {
            // Retrieve the entity metadata.
            var entityRequest = new RetrieveEntityRequest
            {
                LogicalName   = entityLogicalName,
                EntityFilters = EntityFilters.Entity
            };

            var entityResponse =
                (RetrieveEntityResponse)service.Execute(entityRequest);

            // Enable auditing on the entity. By default, this also enables auditing
            // on all the entity's attributes.
            EntityMetadata entityMetadata = entityResponse.EntityMetadata;

            bool oldValue = entityMetadata.IsAuditEnabled.Value;

            entityMetadata.IsAuditEnabled = new BooleanManagedProperty(flag);

            var updateEntityRequest = new UpdateEntityRequest {
                Entity = entityMetadata
            };

            var updateEntityResponse =
                (UpdateEntityResponse)service.Execute(updateEntityRequest);

            return(oldValue);
        }
        private void AddUserToQueue(Entity user, Guid queueId)
        {
            var addPrincipalToQueueRequest = new AddPrincipalToQueueRequest
            {
                Principal = user,
                QueueId   = queueId
            };

            _client.Execute(addPrincipalToQueueRequest);
        }
        private List <string> GetAllEntitySchemas()
        {
            var request = new RetrieveAllEntitiesRequest
            {
                EntityFilters         = EntityFilters.Entity,
                RetrieveAsIfPublished = true
            };
            var response = (RetrieveAllEntitiesResponse)crmServiceClient.Execute(request);

            return(response.EntityMetadata.OrderBy(x => x.SchemaName).Select(x => x.SchemaName).ToList <string>());
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Retrieve the default business unit needed to create the team.
            var queryDefaultBusinessUnit = new QueryExpression
            {
                EntityName = BusinessUnit.EntityLogicalName,
                ColumnSet  = new ColumnSet("businessunitid"),
                Criteria   = new FilterExpression()
            };

            // Execute the request.
            queryDefaultBusinessUnit.Criteria.AddCondition("parentbusinessunitid",
                                                           ConditionOperator.Null);

            var defaultBusinessUnit = (BusinessUnit)service.RetrieveMultiple(
                queryDefaultBusinessUnit).Entities[0];

            // Get the GUID of the current user.
            var who     = new WhoAmIRequest();
            var whoResp = (WhoAmIResponse)service.Execute(who);

            userId = whoResp.UserId;

            // Instantiate a role entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation to determine
            // which attributes must be set for each entity.
            var setupRole = new Role
            {
                Name           = "ABC Management Role",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName,
                                                     defaultBusinessUnit.Id)
            };

            //Create a role record.
            roleId = service.Create(setupRole);
            Console.WriteLine("Created Role.");

            // Assign User to Managers role.
            var associate = new AssociateRequest()
            {
                Target          = new EntityReference(SystemUser.EntityLogicalName, userId),
                RelatedEntities = new EntityReferenceCollection()
                {
                    new EntityReference(Role.EntityLogicalName, roleId),
                },
                Relationship = new Relationship("systemuserroles_association")
            };

            // Execute the request.
            service.Execute(associate);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Delete all records created in this sample.
                // Delete the secured custom field #1.
                DeleteAttributeRequest deleteRequest = new DeleteAttributeRequest()
                {
                    EntityLogicalName = Account.EntityLogicalName,
                    LogicalName       = "secret_phone",
                    RequestId         = _secretPhoneId
                };
                service.Execute(deleteRequest);
                // Delete the secured custom field #2.
                deleteRequest = new DeleteAttributeRequest()
                {
                    EntityLogicalName = Account.EntityLogicalName,
                    LogicalName       = "secret_home",
                    RequestId         = _secretHomeId
                };
                service.Execute(deleteRequest);

                // Delete the account record.
                service.Delete(Account.EntityLogicalName, _accountRecordId);

                // We don't need to delete POAA records, because
                // they were deleted when we deleted the account record.

                Console.WriteLine("Entity record(s) have been deleted.");
            }
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            Console.WriteLine("Please check the app.config to add credentials and organization url");
            string connectionString = ConfigurationManager.ConnectionStrings["CrmDefaultConnection"].ToString();
            var    serviceClient    = new CrmServiceClient(connectionString);

            serviceClient.OrganizationServiceProxy.Timeout = new TimeSpan(1, 30, 0);
            if (!serviceClient.IsReady)
            {
                throw new Exception("Cannot connect to organization!, Please check the app.config to add credentials and organization url");
            }

            Console.WriteLine("Connected to {0}", serviceClient.ConnectedOrgFriendlyName);
            Console.WriteLine("Do you want to import the solution Synchronously or Asynchronously ?\n 1 - Sync \n 2 - Async");
            string input = Console.ReadLine();
            double d;

            if (Double.TryParse(input, out d))
            {
                if (d == 1)//Synchronous
                {
                    Stopwatch stopWatch = new Stopwatch();
                    stopWatch.Start();
                    var importSolutionResponse = (ImportSolutionResponse)serviceClient.Execute(ImportSolution(serviceClient));
                    var est = importSolutionResponse.Results;
                    stopWatch.Stop();
                    Console.WriteLine("RunTime " + stopWatch.Elapsed);
                    Console.ReadKey();
                }
                else if (d == 2)//Asynchronous
                {
                    Stopwatch stopWatch = new Stopwatch();
                    stopWatch.Start();
                    ExecuteAsyncRequest request = new ExecuteAsyncRequest();
                    request.Request = ImportSolution(serviceClient);
                    ExecuteAsyncResponse response = (ExecuteAsyncResponse)serviceClient.Execute(request);
                    stopWatch.Stop();
                    Console.WriteLine("RunTime " + stopWatch.Elapsed);
                    Console.ReadKey();
                }
                else
                {
                    Console.WriteLine("Invalid option - bye");
                    Console.ReadKey();
                }
            }
        }
        public void Deploy(bool publish, bool force, List <string> explicitExtensions)
        {
            if (File.Exists(Path.Combine(this.source, "package.crmpkg")))
            {
                Load();
                string currentDirectory = Directory.GetCurrentDirectory();
                Directory.SetCurrentDirectory(this.source);
                List <Guid> source = Deploy(solution.Files, force, explicitExtensions);
                Directory.SetCurrentDirectory(currentDirectory);

                Log.Information("Saving Post Deploy Package Changes... ");
                solution.Save();

                if (!publish || source == null || source.Count() <= 0 || !Connect())
                {
                    return;
                }

                try
                {
                    Log.Information("Publishing changes, {0} to update... ", source.Count());

                    var sources = string.Join(Environment.NewLine, source.Select(s => $"<webresource>{s.ToString("B")}</webresource>"));

                    PublishXmlRequest publishXmlRequest = new PublishXmlRequest()
                    {
                        ParameterXml = $"<importexportxml><webresources>{sources}</webresources></importexportxml>"
                    };

                    if (connection.IsReady)
                    {
                        PublishXmlResponse publishXmlResponse = (PublishXmlResponse)connection.Execute(publishXmlRequest);
                    }
                    else
                    {
                        Log.Error(connection.LastCrmError);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed");
                }
            }
            else
            {
                Log.Information("The package definition does not exist. Please create a deployment package before continuing.");
            }
        }
        private int InsertOptionSetValue(string label, int?value)
        {
            var request = new InsertOptionValueRequest
            {
                Label = new Label(label, LanguageCode)
            };

            if (value.HasValue)
            {
                request.Value = value;
            }
            if (isGlobalOptionSet)
            {
                request.OptionSetName = optionSetName;
            }
            else
            {
                request.EntityLogicalName    = EntityLogicalName;
                request.AttributeLogicalName = AttributeLogicalName;
            }
            Log.Debug("Adding option '{label}' ({request})", label, Newtonsoft.Json.JsonConvert.SerializeObject(request));
            var response = (InsertOptionValueResponse)CrmServiceClient.Execute(request);

            return(response.NewOptionValue);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") ||
                                 answer.StartsWith("Y") ||
                                 answer == String.Empty);
            }

            if (deleteRecords)
            {
                service.Delete(Account.EntityLogicalName, accountId);
                UnpublishDuplicateRuleRequest unpublishRequest = new UnpublishDuplicateRuleRequest
                {
                    DuplicateRuleId = ruleId
                };
                service.Execute(unpublishRequest);
                service.Delete(DuplicateRule.EntityLogicalName, ruleId);
                service.Delete(Account.EntityLogicalName, dupAccountId);
                Console.WriteLine("Entity records have been deleted.");
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// This method creates a Quick Campaign for a set of accounts selected by a query
        /// </summary>
        /// <param name="activityEntity">
        /// An object that indicates activity type for the quick campaign and
        /// contains values for each of activity that will be created
        /// </param>
        /// <param name="query">
        /// A query that provides a list of accounts for which
        /// the quick campaign is distributed.
        /// </param>
        /// <param name="ownershipOption">
        /// Specifies who will own the activities created by the Quick Campaign
        ///	The PropagationOwnershipOptions enum is used to specify value for this parameter
        ///	</param>
        /// <param name="isPropagate">
        /// Specifies whether the operation is to be executed.
        /// This input is often 'true' for Quick Campaign
        /// </param>
        /// <returns></returns>
        public static Guid CreateAndRetrieveQuickCampaignForQueryExpression(CrmServiceClient service, Entity emailActivityEntity,
                                                                            QueryExpression query, PropagationOwnershipOptions ownershipOption, bool isPropagate)
        {
            // create the bulkoperation
            var request = new PropagateByExpressionRequest()
            {
                Activity           = emailActivityEntity,
                ExecuteImmediately = false, // Default value.
                FriendlyName       = "Query Based Quick Campaign",
                OwnershipOptions   = ownershipOption,
                QueryExpression    = query,
                Owner             = new EntityReference("systemuser", _currentUser),
                PostWorkflowEvent = true,
                SendEmail         = false,
                TemplateId        = Guid.Empty
            };

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

            Guid bulkOpId = response.BulkOperationId;

            System.Console.WriteLine(
                "Quick Campaign with following name has been created. "
                + "Please verify manually: \n"
                + request.FriendlyName + "\nPress enter to continue....");
            System.Console.ReadLine();
            return(bulkOpId);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a new queue instance.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            var whoRequest = new WhoAmIRequest();

            _currentUser = ((WhoAmIResponse)service.Execute(whoRequest)).UserId;

            //Create an activity objects which will act like a template during QC distrbution.
            //The activities created by QC will create activities with content that this activity has
            _templateEmailActivity = new Email()
            {
                Subject = "qcCreatedEmailActivity"
            };

            _templateLetterActivity = new Letter()
            {
                Subject = "qcCreatedLetterActivity"
            };

            // Create accounts on which we want to run QC
            _accountIdArray = new Guid[5];
            for (int i = 0; i < 5; i++)
            {
                var acct = new Account()
                {
                    Name = "Account For Quick Campaign " + i.ToString()
                };
                _accountIdArray[i] = service.Create(acct);
                Console.WriteLine("Created {0}.", acct.Name);
            }
        }
Ejemplo n.º 17
0
        public override void Execute()
        {
            var conversion = (FetchXmlToQueryExpressionResponse)CrmServiceClient.Execute(new FetchXmlToQueryExpressionRequest()
            {
                FetchXml = FetchXml
            });
            var query       = conversion.Query;
            int recordCount = 0;

            Log.Information("Retrieving records");
            EntityCollection results;

            do
            {
                results      = CrmServiceClient.RetrieveMultiple(query);
                recordCount += results.Entities.Count;
                Log.Information("Got {recordCount} records", recordCount);
                foreach (var e in results.Entities)
                {
                    Row row = new Row();
                    foreach (var kvp in e.Attributes)
                    {
                        row.Add(kvp.Key, ConvertCrmValue(kvp.Value));
                    }
                    Output.AddRow(row);
                }
                ((QueryExpression)query).PageInfo.PageNumber++;
                ((QueryExpression)query).PageInfo.PagingCookie = results.PagingCookie;
            } while (results.MoreRecords);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Deletes the custom entity record that was created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the entity created in this sample.</param>
        /// </summary>
        public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these entity records deleted? (y/n)");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }

            if (deleteRecords)
            {
                // Deactivate and delete workflow
                SetStateRequest deactivateRequest = new SetStateRequest
                {
                    EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId),
                    State         = new OptionSetValue((int)WorkflowState.Draft),
                    Status        = new OptionSetValue((int)workflow_statuscode.Draft)
                };
                service.Execute(deactivateRequest);
                service.Delete(Workflow.EntityLogicalName, _workflowId);
                Console.WriteLine("The workflow has been deactivated, and deleted.");
            }
        }
        /// <summary>
        /// Downloads the CRM Solution
        /// </summary>
        /// <param name="crmServiceClient">CRM Service Client</param>
        /// <param name="crmSolutionName">CRM Solution Name</param>
        /// <param name="filePath">File Path</param>
        /// <param name="isManaged">Defines if the Solution should be downloaded Managed</param>
        public void DownloadSolution(CrmServiceClient crmServiceClient, string crmSolutionName, string filePath, bool isManaged = false)
        {
            ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest
            {
                Managed      = isManaged,
                SolutionName = crmSolutionName
            };

            ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)crmServiceClient.Execute(exportSolutionRequest);

            byte[] exportXml = exportSolutionResponse.ExportSolutionFile;

            string filename;

            if (isManaged)
            {
                filename = Path.Combine(filePath, crmSolutionName + "_managed.zip");
            }
            else
            {
                filename = Path.Combine(filePath, crmSolutionName + ".zip");
            }

            File.WriteAllBytes(filename, exportXml);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Calls the FulfillSalesOrderRequest and closes it as completed
        /// </summary>
        private static void CloseSalesOrder(CrmServiceClient service)
        {
            if (!_salesOrderId.HasValue)
            {
                return;
            }

            // Close the sales order with a status of Complete
            int newStatus = (int)salesorder_statuscode.Complete;
            var request   = new FulfillSalesOrderRequest
            {
                OrderClose = new OrderClose
                {
                    SalesOrderId = new EntityReference
                    {
                        LogicalName = SalesOrder.EntityLogicalName, Id = _salesOrderId.Value
                    }
                },
                Status = new OptionSetValue(newStatus)
            };

            Console.WriteLine(String.Concat("Executing FullfillSalesOrderRequest on sales order: ",
                                            _salesOrderId.Value, ",\n\t new status: ",
                                            GetLabelForStatus(SalesOrder.EntityLogicalName, "statuscode", newStatus, service)));

            service.Execute(request);

            // Validate that the sales order is complete
            var salesOrder = service.Retrieve(SalesOrder.EntityLogicalName, _salesOrderId.Value,
                                              new ColumnSet("statuscode")).ToEntity <SalesOrder>();

            Console.WriteLine(String.Concat("Validation of closed sales order: ", _salesOrderId.Value,
                                            ",\n\t status: ", salesOrder.FormattedValues["statuscode"]));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty);
            }

            if (deleteRecords)
            {
                // Delete the account record only if the row version matches.
                EntityReference accountToDelete = new EntityReference("account", accountId);
                accountToDelete.RowVersion = accountRowVersion;


                DeleteRequest request = new DeleteRequest()
                {
                    Target = accountToDelete,
                    ConcurrencyBehavior = ConcurrencyBehavior.IfRowVersionMatches
                };

                service.Execute(request);
                Console.WriteLine("Entity records have been deleted.");
            }
        }
Ejemplo n.º 22
0
        public static List <string> GetAllDataSource(CrmServiceClient crmServiceClient)
        {
            var list             = new List <string>();
            var filterExpression = new MetadataFilterExpression();

            filterExpression.Conditions.Add(new MetadataConditionExpression("DataProviderId", MetadataConditionOperator.Equals, Guid.Parse("B2112A7E-B26C-42F7-9B63-9A809A9D716F")));
            var propertiesExpression = new MetadataPropertiesExpression(new string[7]
            {
                "DataProviderId",
                "LogicalName",
                "SchemaName",
                "MetadataId",
                "DisplayName",
                "ExternalName",
                "DisplayCollectionName"
            });
            var entityQueryExpression = new EntityQueryExpression
            {
                Criteria = new MetadataFilterExpression()
            };

            entityQueryExpression.Criteria   = filterExpression;
            entityQueryExpression.Properties = propertiesExpression;
            var request = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression
            };
            var response = (RetrieveMetadataChangesResponse)crmServiceClient.Execute(request);

            foreach (EntityMetadata entityMetadata in response.EntityMetadata)
            {
                list.Add(entityMetadata.LogicalName);
            }
            return(list);
        }
Ejemplo n.º 23
0
        public static List <string> GetSdkMessages(CrmServiceClient service, string logicalName)
        {
            var request = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = logicalName
            };
            var response  = (RetrieveEntityResponse)service.Execute(request);
            var fetchData = new
            {
                primaryobjecttypecode         = response.EntityMetadata.ObjectTypeCode,
                iscustomprocessingstepallowed = "1"
            };
            var fetchXml = $@"
<fetch>
  <entity name='sdkmessage'>
    <attribute name='name' />
    <link-entity name='sdkmessagefilter' from='sdkmessageid' to='sdkmessageid'>
      <filter type='and'>
        <condition attribute='primaryobjecttypecode' operator='eq' value='{fetchData.primaryobjecttypecode}'/>
        <condition attribute='iscustomprocessingstepallowed' operator='eq' value='{fetchData.iscustomprocessingstepallowed}'/>
      </filter>
    </link-entity>
  </entity>
</fetch>";
            var rows     = service.RetrieveMultiple(new FetchExpression(fetchXml));
            var messages = (from entity in rows.Entities
                            select entity["name"].ToString()
                            ).ToList();

            messages.Sort();
            return(messages);
        }
Ejemplo n.º 24
0
        public static List <int> GetProvisionedLanguages(CrmServiceClient service)
        {
            var request  = new RetrieveProvisionedLanguagesRequest();
            var response = (RetrieveProvisionedLanguagesResponse)service.Execute(request);

            return(response.RetrieveProvisionedLanguages.ToList());
        }
        public override void Execute()
        {
            bool needsPublishing = false;

            while (Input.HasRowsAvailable)
            {
                var row = Input.RemoveRow();
                if (!row.ContainsKey(LabelKey))
                {
                    throw new StepException($"The current row does not contain a field '{LabelKey}'");
                }
                var label = row[LabelKey] as string;
                if (string.IsNullOrEmpty(label))
                {
                    continue;
                }
                if (!options.ContainsValue(label))
                {
                    // create option set value
                    int?optionValue = null;
                    if (OptionValuePrefix != 0)
                    {
                        optionValue = GetFirstAvailableOptionSetValue();
                    }
                    optionValue = InsertOptionSetValue(label, optionValue);
                    options.Add(optionValue.Value, label);
                    row[LabelKey + "$value"] = optionValue;
                    Output.AddRow(row);
                    needsPublishing = true;
                }
                else
                {
                    // add existing option set value to output
                    var optionValue = options.FirstOrDefault(kvp => kvp.Value == label).Key;
                    row[LabelKey + "$value"] = optionValue;
                    Output.AddRow(row);
                }
            }
            if (needsPublishing)
            {
                if (isGlobalOptionSet)
                {
                    Log.Information("Publishing option set {optionSetName}", optionSetName);
                    CrmServiceClient.Execute(new PublishXmlRequest()
                    {
                        ParameterXml =
                            $@"<importexportxml>
 <optionsets>
  <optionset>{optionSetName}</optionset>
 </optionsets>
</importexportxml>"
                    });
                }
                else
                {
                    Log.Information("Publishing entity {EntityLogicalName}", EntityLogicalName);
                    CrmServiceClient.PublishEntity(EntityLogicalName);
                }
            }
        }
        private string ConnectToCrm(string connectionString)
        {
            try
            {
                CrmServiceClient client = new CrmServiceClient(connectionString);

                WhoAmIRequest  wRequest  = new WhoAmIRequest();
                WhoAmIResponse wResponse = (WhoAmIResponse)client.Execute(wRequest);
                _logger.WriteToOutputWindow("Connected To CRM Organization: " + wResponse.OrganizationId, Logger.MessageType.Info);
                _logger.WriteToOutputWindow("Version: " + client.ConnectedOrgVersion, Logger.MessageType.Info);

                OrgId = wResponse.OrganizationId.ToString();

                Globals globals = _dte.Globals;
                globals["CurrentConnection" + _windowType] = client;

                if (client.ConnectedOrgVersion != null)
                {
                    return(client.ConnectedOrgVersion.ToString());
                }

                _logger.WriteToOutputWindow("Error Connecting To CRM: Unable to determine org. version", Logger.MessageType.Error);
                return(null);
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Connecting To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return(null);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Connecting To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return(null);
            }
        }
Ejemplo n.º 27
0
        public static bool ImportSolution(CrmServiceClient client, string path)
        {
            var solutionBytes = FileSystem.GetFileBytes(path);

            if (solutionBytes == null)
            {
                return(false);
            }

            try
            {
                var request = new ImportSolutionRequest
                {
                    CustomizationFile = solutionBytes,
                    OverwriteUnmanagedCustomizations = true,
                    PublishWorkflows = true,
                    ImportJobId      = Guid.NewGuid()
                };

                client.Execute(request);

                ExLogger.LogToFile(Logger, $"{Resource.Message_ImportedSolution}: {path}", LogLevel.Info);
                OutputLogger.WriteToOutputWindow($"{Resource.Message_ImportedSolution}: {path}", MessageType.Info);

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorImportingSolution, ex);

                return(false);
            }
        }
Ejemplo n.º 28
0
        private void Do(object sender, ElapsedEventArgs e)
        {
            try
            {
                var currentUser = (WhoAmIResponse)_service.Execute(new WhoAmIRequest());
                Console.WriteLine($"User ID: {currentUser.UserId}");
                Console.WriteLine($"Organization ID: {currentUser.OrganizationId}");
            }
            catch (Exception ex)
            {
                lock (_lock)
                {
                    Console.WriteLine(ex.GetType());
                    var ee  = ex.InnerException;
                    var tab = "  - ";
                    while (ee != null)
                    {
                        Console.WriteLine(tab + ee.GetType());
                        ee  = ee.InnerException;
                        tab = "  " + tab;
                    }

                    // При потере соединения с CRM будут возникать следующие ошибки:
                    // System.ServiceModel.CommunicationException
                    //     - System.Net.WebException
                    //         - System.IO.IOException
                    //             - System.Net.Sockets.SocketException
                    // System.ServiceModel.EndpointNotFoundException
                    //     -System.Net.WebException
                    //         - System.Net.Sockets.SocketException
                }
            }
        }
Ejemplo n.º 29
0
        public static bool AddWebResourceToSolution(CrmServiceClient client, string uniqueName, Guid webResourceId)
        {
            try
            {
                AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest
                {
                    ComponentType      = 61,
                    SolutionUniqueName = uniqueName,
                    ComponentId        = webResourceId
                };
                AddSolutionComponentResponse response =
                    (AddSolutionComponentResponse)client.Execute(scRequest);

                OutputLogger.WriteToOutputWindow("New Web Resource Added To Solution: " + response.id, MessageType.Info);

                return(true);
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                OutputLogger.WriteToOutputWindow(
                    "Error adding web resource to solution: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error);
                return(false);
            }
            catch (Exception ex)
            {
                OutputLogger.WriteToOutputWindow(
                    "Error adding web resource to solution: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error);
                return(false);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Returns the label for a status option
        /// </summary>
        /// <param name="entity">entity logical name</param>
        /// <param name="attribute">statuscode </param>
        /// <param name="value">numeric value</param>
        /// <returns>user label</returns>
        private static string GetLabelForStatus(string entity, string attribute, int value, CrmServiceClient service)
        {
            // Retrieve the attribute metadata
            var attributeMD = ((RetrieveAttributeResponse)service.Execute(
                                   new RetrieveAttributeRequest
            {
                EntityLogicalName = entity,
                LogicalName = attribute,
                RetrieveAsIfPublished = true,
            })).AttributeMetadata;

            // find the option based on the numeric value and return the label
            if (attributeMD.AttributeType == AttributeTypeCode.Status)
            {
                var options = ((StatusAttributeMetadata)attributeMD).OptionSet.Options;

                var crmOption = options.FirstOrDefault(x => x.Value == value);
                if (crmOption != null)
                {
                    return(crmOption.Label.UserLocalizedLabel.Label);
                }
            }

            return(string.Empty);
        }