Esempio n. 1
0
        private Guid?GetExistingRoleId()
        {
            var roles = CrmSvc.GetEntityDataBySearchParams("role", new List <CrmServiceClient.CrmSearchFilter>
            {
                new CrmServiceClient.CrmSearchFilter
                {
                    SearchConditions = new List <CrmServiceClient.CrmFilterConditionItem>
                    {
                        new CrmServiceClient.CrmFilterConditionItem
                        {
                            FieldName     = "name",
                            FieldOperator = ConditionOperator.Equal,
                            FieldValue    = ProposalManagerApplicationName
                        }
                    }
                }
            }, CrmServiceClient.LogicalSearchOperator.None, new List <string> {
                "roleid"
            });

            if (roles != null)
            {
                return(roles.Any() ? (Guid?)roles.First().Value["roleid"] : null);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 2
0
        private void SetUpPermissions()
        {
            if (GetExistingUser() == null)
            {
                var roleId     = GetRoleId();
                var privileges = GetPrivilegeRecords();

                var addPrivilegesRoleRequest = new AddPrivilegesRoleRequest
                {
                    RoleId     = roleId,
                    Privileges =
                        (
                            from p in privileges
                            select new RolePrivilege(RequiredPrivileges[(string)p.Value["name"]], (Guid)p.Value["privilegeid"], BusinessUnitId.Value)
                        ).ToArray()
                };
                CrmSvc.ExecuteCrmOrganizationRequest(addPrivilegesRoleRequest);

                var user = CreateProposalManagerUser();
                PackageLog.Log("User created...");
                PackageLog.Log(user.ToString());

                CrmSvc.Associate(
                    "systemuser",
                    user,
                    new Relationship("systemuserroles_association"),
                    new EntityReferenceCollection {
                    new EntityReference("role", roleId)
                });
            }
        }
Esempio n. 3
0
        private void CreateSharePointLinks()
        {
            var defaultSiteId = CrmSvc.CreateNewRecord("sharepointsite", new Dictionary <string, CrmDataTypeWrapper>
            {
                { "name", new CrmDataTypeWrapper("Default Site", CrmFieldType.String) },
                { "absoluteurl", new CrmDataTypeWrapper($"https://{SharePointDomain.Value}", CrmFieldType.String) }
            });
            var proposalManagerSiteId = CrmSvc.CreateNewRecord("sharepointsite", new Dictionary <string, CrmDataTypeWrapper>
            {
                { "name", new CrmDataTypeWrapper("Proposal Manager Site", CrmFieldType.String) },
                { "parentsite", new CrmDataTypeWrapper(defaultSiteId, CrmFieldType.Lookup, "sharepointsite") },
                { "relativeurl", new CrmDataTypeWrapper($"sites/{ProposalManagerSharePointSiteName.Value}", CrmFieldType.String) }
            });
            var proposalManagerSiteDriveId = CrmSvc.CreateNewRecord("sharepointdocumentlocation", new Dictionary <string, CrmDataTypeWrapper>
            {
                { "name", new CrmDataTypeWrapper("Proposal Manager Site Drive", CrmFieldType.String) },
                { "parentsiteorlocation", new CrmDataTypeWrapper(proposalManagerSiteId, CrmFieldType.Lookup, "sharepointsite") },
                { "relativeurl", new CrmDataTypeWrapper(DriveName.Value, CrmFieldType.String) }
            });

            CrmSvc.CreateNewRecord("sharepointdocumentlocation", new Dictionary <string, CrmDataTypeWrapper>
            {
                { "name", new CrmDataTypeWrapper("Proposal Manager Temporary Folder", CrmFieldType.String) },
                { "parentsiteorlocation", new CrmDataTypeWrapper(proposalManagerSiteDriveId, CrmFieldType.Lookup, "sharepointdocumentlocation") },
                { "relativeurl", new CrmDataTypeWrapper("TempFolder", CrmFieldType.String) }
            });
        }
Esempio n. 4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="otc">Object Type Code of the entity.</param>
 /// <returns></returns>
 private Guid GetCreateFilterIdByOtc(int otc) => (Guid)CrmSvc.GetEntityDataBySearchParams("sdkmessagefilter", new List <CrmServiceClient.CrmSearchFilter>
 {
     new CrmServiceClient.CrmSearchFilter
     {
         FilterOperator   = LogicalOperator.And,
         SearchConditions = new List <CrmServiceClient.CrmFilterConditionItem>
         {
             new CrmServiceClient.CrmFilterConditionItem
             {
                 FieldName     = "sdkmessageid",
                 FieldOperator = ConditionOperator.Equal,
                 FieldValue    = CreateMessageId.Value
             },
             new CrmServiceClient.CrmFilterConditionItem
             {
                 FieldName     = "primaryobjecttypecode",
                 FieldOperator = ConditionOperator.Equal,
                 FieldValue    = otc
             },
             new CrmServiceClient.CrmFilterConditionItem
             {
                 FieldName     = "secondaryobjecttypecode",
                 FieldOperator = ConditionOperator.Equal,
                 FieldValue    = "none"
             }
         }
     }
 }, CrmServiceClient.LogicalSearchOperator.None, new List <string> {
     "sdkmessagefilterid"
 }).Single().Value["sdkmessagefilterid"];
Esempio n. 5
0
 /// <summary>
 ///
 /// </summary>
 /// <returns>The created user id.</returns>
 private Guid CreateProposalManagerUser() => CrmSvc.CreateNewRecord("systemuser", new Dictionary <string, CrmDataTypeWrapper>
 {
     { "firstname", new CrmDataTypeWrapper(ProposalManagerApplicationName, CrmFieldType.String) },
     { "lastname", new CrmDataTypeWrapper("Application", CrmFieldType.String) },
     { "businessunitid", new CrmDataTypeWrapper(BusinessUnitId.Value, CrmFieldType.Lookup, "businessunit") },
     { "applicationid", new CrmDataTypeWrapper(ProposalManagerApplicationId.Value, CrmFieldType.UniqueIdentifier) },
     { "internalemailaddress", new CrmDataTypeWrapper($"{Guid.NewGuid()}@{TenantDomain.Value}", CrmFieldType.String) }
 });
Esempio n. 6
0
        private bool IsRoleAssignedToUser(Guid sytemUserId, Guid roleId)
        {
            try
            {
                // Establish a SystemUser link for a query.
                LinkEntity systemUserLink = new LinkEntity()
                {
                    LinkFromEntityName    = "systemuserroles",
                    LinkFromAttributeName = "systemuserid",
                    LinkToEntityName      = "systemuserroles",
                    LinkToAttributeName   = "systemuserid",
                    LinkCriteria          =
                    {
                        Conditions =
                        {
                            new ConditionExpression(
                                "systemuserid", ConditionOperator.Equal, sytemUserId)
                        }
                    }
                };

                // Build the query.
                QueryExpression linkQuery = new QueryExpression()
                {
                    EntityName   = "role",
                    ColumnSet    = new ColumnSet("roleid"),
                    LinkEntities =
                    {
                        new LinkEntity()
                        {
                            LinkFromEntityName    = "role",
                            LinkFromAttributeName = "roleid",
                            LinkToEntityName      = "systemuserroles",
                            LinkToAttributeName   = "roleid",
                            LinkEntities          = { systemUserLink }
                        }
                    },
                    Criteria =
                    {
                        Conditions =
                        {
                            new ConditionExpression("roleid", ConditionOperator.Equal, roleId)
                        }
                    }
                };

                // Retrieve matching roles.
                EntityCollection matchEntities = CrmSvc.RetrieveMultiple(linkQuery);

                return(matchEntities.Entities.Count > 0);
            }
            catch
            {
                return(false);
            }
        }
        /// <summary>
        /// Called after Import completes.
        /// </summary>
        /// <returns>true, if solution deployed and schema imported successfully, exception otherwise</returns>
        public override bool AfterPrimaryImport()
        {
            OrganizationRequest request = new OrganizationRequest()
            {
                RequestName = "ImportCardTypeSchema"
            };

            request["SolutionUniqueName"] = "ExtensibilityExample";
            CrmSvc.Execute(request);
            return(true);
        }
Esempio n. 8
0
 private void AssignRoleToUser(Guid appUserId, Guid roleId)
 {
     // Associate the user with the role if the role isn't already assigned to the user
     if (roleId != Guid.Empty && appUserId != Guid.Empty && !IsRoleAssignedToUser(appUserId, roleId))
     {
         CrmSvc.Associate(
             "systemuser",
             appUserId,
             new Relationship("systemuserroles_association"),
             new EntityReferenceCollection()
         {
             new EntityReference("role", roleId)
         });
     }
 }
Esempio n. 9
0
 private Guid GetIdByName(string entityName, string recordName) => (Guid)CrmSvc.GetEntityDataBySearchParams(entityName, new List <CrmServiceClient.CrmSearchFilter>
 {
     new CrmServiceClient.CrmSearchFilter
     {
         SearchConditions = new List <CrmServiceClient.CrmFilterConditionItem>
         {
             new CrmServiceClient.CrmFilterConditionItem
             {
                 FieldName     = "name",
                 FieldOperator = ConditionOperator.Equal,
                 FieldValue    = recordName
             }
         }
     }
 }, CrmServiceClient.LogicalSearchOperator.None, new List <string> {
     $"{entityName}id"
 }).Single().Value[$"{entityName}id"];
Esempio n. 10
0
        private bool BulkDeleteJobExists()
        {
            QueryExpression bulkExpression = new QueryExpression()
            {
                EntityName = "asyncoperation",
                ColumnSet  = new ColumnSet(new string[] { "asyncoperationid", "name" }),
                Criteria   =
                {
                    Conditions =
                    {
                        new ConditionExpression("operationtype", ConditionOperator.Equal,      13),
                        new ConditionExpression("name",          ConditionOperator.Equal, jobName),
                    }
                }
            };

            return(CrmSvc.RetrieveMultiple(bulkExpression).Entities.Count > 0);
        }
Esempio n. 11
0
        /// <summary>
        /// Returns the version of specified solution if present.
        /// </summary>
        private int[] GetSolutionVersion(string solutionName)
        {
            FilterExpression filter = new FilterExpression(LogicalOperator.And);

            filter.AddCondition(new ConditionExpression("uniquename", ConditionOperator.Equal, solutionName));
            QueryExpression query = new QueryExpression
            {
                EntityName = "solution",
                ColumnSet  = new ColumnSet("uniquename", "version"),
                Criteria   = filter,
                PageInfo   = new PagingInfo()
                {
                    ReturnTotalRecordCount = true
                }
            };
            EntityCollection stuff = CrmSvc.RetrieveMultiple(query);

            foreach (var i in stuff.Entities)
            {
                PackageLog.Log($"Name: {i.GetAttributeValue<string>("uniquename").ToString()} Version: {i.GetAttributeValue<string>("version")}");
            }
            if (stuff.TotalRecordCount < 1)
            {
                return(null);
            }
            string version = stuff.Entities.First().GetAttributeValue <string>("version");

            if (string.IsNullOrEmpty(version))
            {
                return(null);
            }
            string[] versions = version.Split('.');

            PackageLog.Log($"NonprofitCore - Major:{versions[0]} Minor:{versions[1]} Build:{versions[2]} Revision:{versions[3]}");
            int[] versionNumbers = new int[4];
            int.TryParse(versions[0], out versionNumbers[0]);
            int.TryParse(versions[1], out versionNumbers[1]);
            int.TryParse(versions[2], out versionNumbers[2]);
            int.TryParse(versions[3], out versionNumbers[3]);

            return(versionNumbers);
        }
Esempio n. 12
0
        private void CreateBulkDeleteJob(int months)
        {
            if (!BulkDeleteJobExists())
            {
                string frequency =
                    String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                  "FREQ=DAILY;INTERVAL={0};", DailyInterval);


                QueryExpression query = new QueryExpression
                {
                    EntityName = "msdyn_analysisresult",
                    ColumnSet  = new ColumnSet("msdyn_name"),
                    Criteria   = new FilterExpression
                    {
                        Conditions =
                        {
                            new ConditionExpression
                            {
                                AttributeName = "createdon",
                                Operator      = ConditionOperator.OlderThanXMonths,
                                Values        = { months }
                            }
                        }
                    }
                };

                BulkDeleteRequest bulkDeleteRequest =
                    new BulkDeleteRequest
                {
                    JobName               = jobName,
                    QuerySet              = new QueryExpression[] { query },
                    StartDateTime         = DateTime.Now.Date,
                    RecurrencePattern     = frequency,
                    SendEmailNotification = false,
                    ToRecipients          = new Guid[] { },
                    CCRecipients          = new Guid[] { }
                };

                CrmSvc.Execute(bulkDeleteRequest);
            }
        }
Esempio n. 13
0
 private Dictionary <string, Dictionary <string, object> > GetPrivilegeRecords() =>
 CrmSvc.GetEntityDataBySearchParams("privilege", new List <CrmServiceClient.CrmSearchFilter>
 {
     new CrmServiceClient.CrmSearchFilter
     {
         FilterOperator   = LogicalOperator.Or,
         SearchConditions =
             (
                 from rp in RequiredPrivileges
                 select new CrmServiceClient.CrmFilterConditionItem
         {
             FieldName = "name",
             FieldOperator = ConditionOperator.Equal,
             FieldValue = rp.Key
         }
             ).ToList()
     }
 }, CrmServiceClient.LogicalSearchOperator.None, new List <string> {
     "privilegeid", "name"
 });
Esempio n. 14
0
        private Guid CreateUser(ApplicationUser appUser)
        {
            QueryExpression businessUnitQuery = new QueryExpression
            {
                EntityName = "businessunit",
                ColumnSet  = new ColumnSet("businessunitid"),
                Criteria   =
                {
                    Conditions =
                    {
                        new ConditionExpression("parentbusinessunitid",
                                                ConditionOperator.Null)
                    }
                }
            };


            EntityCollection defaultBusinessUnits = CrmSvc.RetrieveMultiple(businessUnitQuery);
            var defaultBusinessUnit = defaultBusinessUnits.Entities[0] ?? null;

            if (defaultBusinessUnit != null)
            {
                Entity systemUser = new Entity("systemuser");
                systemUser["firstname"]            = appUser.FirstName;
                systemUser["lastname"]             = appUser.LastName;
                systemUser["internalemailaddress"] = appUser.InternalEmailAddress;
                systemUser["applicationid"]        = appUser.Id;
                systemUser["businessunitid"]       = new EntityReference
                {
                    LogicalName = "businessunit",
                    Name        = "businessunit",
                    Id          = defaultBusinessUnit.Id
                };

                return(CrmSvc.Create(systemUser));
            }

            return(Guid.Empty);
        }
        /// <summary>
        /// Called after Import completes.
        /// </summary>
        /// <returns></returns>
        public override bool AfterPrimaryImport()
        {
            var version = CrmSvc.ConnectedOrgVersion;

            //Enable all the steps in the plugin assembly
            if (CrmSvc != null && CrmSvc.IsReady)
            {
                var assemblyname = "CrmAsyncRequestResponseSample.Plugins";

                // Create the QueryExpression object to retrieve plug-in type
                var query = new QueryExpression();
                query.EntityName = "plugintype";
                query.Criteria.AddCondition("assemblyname", ConditionOperator.Equal, assemblyname);
                var retrievedPluginType = CrmSvc.RetrieveMultiple(query)[0];

                var pluginTypeId = (Guid)retrievedPluginType.Attributes["plugintypeid"];

                query = new QueryExpression();

                // Set the properties of the QueryExpression object.
                query.EntityName = "sdkmessageprocessingstep";
                query.ColumnSet  = new ColumnSet(new[] { "sdkmessageprocessingstepid", "statecode" });
                query.Criteria.AddCondition(new ConditionExpression("plugintypeid", ConditionOperator.Equal, pluginTypeId));
                var retrievedSteps = CrmSvc.RetrieveMultiple(query);

                foreach (var step in retrievedSteps.Entities)
                {
                    // Enable the step by setting it's state code
                    step.Attributes["statecode"]  = new OptionSetValue(0); // 0 = Enabled
                    step.Attributes["statuscode"] = new OptionSetValue(1); // 1 = Enabled
                    CrmSvc.Update(step);
                }

                return(true); // Do nothing here/
            }

            return(false);
        }
Esempio n. 16
0
        private Guid?GetExistingUser()
        {
            var users = CrmSvc.GetEntityDataBySearchParams("systemuser", new List <CrmServiceClient.CrmSearchFilter>
            {
                new CrmServiceClient.CrmSearchFilter
                {
                    SearchConditions = new List <CrmServiceClient.CrmFilterConditionItem>
                    {
                        new CrmServiceClient.CrmFilterConditionItem
                        {
                            FieldName     = "applicationid",
                            FieldOperator = ConditionOperator.Equal,
                            FieldValue    = ProposalManagerApplicationId.Value
                        }
                    }
                }
            }, CrmServiceClient.LogicalSearchOperator.None, new List <string> {
                "systemuserid"
            });

            if (users != null)
            {
                if (users.Any())
                {
                    PackageLog.Log("PM user already created. Id: " + users.First().Value["systemuserid"].ToString());
                    return((Guid?)users.First().Value["systemuserid"]);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Esempio n. 17
0
        private Guid CreateOrGetApplicationUser(ApplicationUser appUser)
        {
            QueryExpression appUserQuery = new QueryExpression
            {
                EntityName = "systemuser",
                ColumnSet  = new ColumnSet("systemuserid"),
                Criteria   =
                {
                    Conditions =
                    {
                        new ConditionExpression("applicationid", ConditionOperator.Equal, appUser.Id)
                    }
                }
            };

            EntityCollection appUsers = CrmSvc.RetrieveMultiple(appUserQuery);

            if (appUsers != null && appUsers.Entities.Count > 0)
            {
                return(appUsers.Entities[0].Id);
            }

            return(CreateUser(appUser));
        }
        private void EnablePluginSteps()
        {
            LogStart("EnablePluginSteps");

            var assemblyname = "FedBizApps.RequestManagement.Plugins";

            // Create the QueryExpression object to retrieve plug-in type
            var query = new QueryExpression {
                EntityName = "plugintype"
            };

            query.Criteria.AddCondition("assemblyname", ConditionOperator.Equal, assemblyname);
            var retrievedPluginType = CrmSvc.RetrieveMultiple(query)[0];

            var pluginTypeId = (Guid)retrievedPluginType.Attributes["plugintypeid"];

            query = new QueryExpression
            {
                EntityName = "sdkmessageprocessingstep",
                ColumnSet  = new ColumnSet(new[] { "sdkmessageprocessingstepid", "statecode" })
            };

            // Set the properties of the QueryExpression object.
            query.Criteria.AddCondition(new ConditionExpression("plugintypeid", ConditionOperator.Equal, pluginTypeId));
            var retrievedSteps = CrmSvc.RetrieveMultiple(query);

            foreach (var step in retrievedSteps.Entities)
            {
                // Enable the step by setting it's state code
                step.Attributes["statecode"]  = new OptionSetValue(0); // 0 = Enabled
                step.Attributes["statuscode"] = new OptionSetValue(1); // 1 = Enabled
                CrmSvc.Update(step);
            }

            LogEnd("EnablePluginSteps");
        }
Esempio n. 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="entityOtc"></param>
        /// <param name="executionMode"></param>
        /// <returns>The secret used to secure the webhook.</returns>
        private string SetUpWebhook(string entityName, int entityOtc, ExecutionMode executionMode)
        {
            var secret = GenerateSecret();
            var opportunitiesServiceEndpointId = CrmSvc.CreateNewRecord("serviceendpoint", new Dictionary <string, CrmDataTypeWrapper>
            {
                { "name", new CrmDataTypeWrapper($"Proposal Manager {entityName}", CrmFieldType.String) },
                { "url", new CrmDataTypeWrapper($"{ProposalManagerApplicationUrl.Value}/api/webhooks/incoming/dynamicscrm/{entityName}", CrmFieldType.String) },
                { "contract", new CrmDataTypeWrapper(WebhookContractEnumValue, CrmFieldType.Picklist) },
                { "authtype", new CrmDataTypeWrapper(WebhookKeyAuthTypeEnumValue, CrmFieldType.Picklist) },
                { "authvalue", new CrmDataTypeWrapper(secret, CrmFieldType.String) }
            });

            /*var filterId = GetCreateFilterIdByOtc(entityOtc);
             * CrmSvc.CreateNewRecord("sdkmessageprocessingstep", new Dictionary<string, CrmDataTypeWrapper>
             * {
             *  { "sdkmessageid", new CrmDataTypeWrapper(CreateMessageId.Value, CrmFieldType.Lookup, "sdkmessage") },
             *  { "sdkmessagefilterid", new CrmDataTypeWrapper(filterId, CrmFieldType.Lookup, "sdkmessagefilter") },
             *  { "plugintypeid", new CrmDataTypeWrapper(filterId, CrmFieldType.Lookup, "sdkmessagefilter") },
             *  { "mode", new CrmDataTypeWrapper(executionMode, CrmFieldType.Picklist) },
             *  { "stage", new CrmDataTypeWrapper(PostOperationStage, CrmFieldType.Picklist) }
             * });
             * //throw new Exception(CrmSvc.LastCrmError);*/
            return(secret);
        }
Esempio n. 20
0
 /// <summary>
 ///
 /// </summary>
 /// <returns>The created role id.</returns>
 private Guid CreateRole() => CrmSvc.CreateNewRecord("role", new Dictionary <string, CrmDataTypeWrapper>
 {
     { "name", new CrmDataTypeWrapper(ProposalManagerApplicationName, CrmFieldType.String) },
     { "businessunitid", new CrmDataTypeWrapper(BusinessUnitId.Value, CrmFieldType.Lookup, "businessunit") }
 });