Exemplo n.º 1
0
        /// <summary>
        /// 查找列权限
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="FieldName"></param>
        /// <returns></returns>
        public static FieldPermission GetFieldsPermission(string TableName, string FieldName)
        {
            if (Yqun.Common.ContextCache.ApplicationContext.Current.IsAdministrator)
            {
                return(null);
            }

            FieldPermission Result = null;

            foreach (Role role in Yqun.Common.ContextCache.ApplicationContext.Current.Roles)
            {
                foreach (Permission permission in role.Permissions)
                {
                    FieldsPermission fieldspermission = permission as FieldsPermission;
                    if (fieldspermission != null && fieldspermission.FieldsName.ToLower() == TableName.ToLower())
                    {
                        foreach (FieldPermission fieldpermission in fieldspermission.Fields)
                        {
                            if (fieldpermission.FieldName.ToLower() == FieldName.ToLower())
                            {
                                Result = fieldpermission;
                                break;
                            }
                        }
                    }
                }
            }

            return(Result);
        }
Exemplo n.º 2
0
        public bool CheckFieldPermission(String strTableName, String strFieldName, FieldPermission permission)
        {
            Guid?iUserID = GetCurrentUserID();

            if (iUserID.HasValue == false)
            {
                return(false);
            }

            return(ABCUserProvider.CheckFieldPermission(iUserID.Value, strTableName, strFieldName, permission));
        }
Exemplo n.º 3
0
        public async Task <IHttpActionResult> PostPermission([FromBody] FieldPermission fieldPermission)
        {
            var permissionCreated = await _fieldPermissionsService.AddFieldPermissionAsync(fieldPermission, UserName);

            if (HttpContext.Current == null)
            {
                return(Created("", permissionCreated));
            }

            var create   = HttpContext.Current.Request.Url + $"/{permissionCreated.Id}";
            var response = Created(create, permissionCreated);

            return(response);
        }
Exemplo n.º 4
0
        internal PermissionCollection InitPermissions(String[] PermissionIndex)
        {
            PermissionCollection permissionCollection = new PermissionCollection();

            if (PermissionIndex == null || PermissionIndex.Length == 0)
            {
                return(permissionCollection);
            }

            StringBuilder Sql_Permissions = new StringBuilder();

            //增加查询条件  Scdel=0  2013-10-17
            Sql_Permissions.Append("select * from sys_auth_Permissions where Scdel=0 and ID in ");
            Sql_Permissions.Append(string.Concat("('", string.Join("','", PermissionIndex), "')"));
            Sql_Permissions.Append(" order by ClsInfo");

            StringBuilder Sql_FieldPermission = new StringBuilder();

            Sql_FieldPermission.Append("select * from sys_auth_FieldPermission where FieldsID in (");
            //增加查询条件  Scdel=0  2013-10-17
            Sql_FieldPermission.Append("select ID from sys_auth_Permissions where Scdel=0 and ID in ");
            Sql_FieldPermission.Append(string.Concat("('", string.Join("','", PermissionIndex), "')"));
            Sql_FieldPermission.Append(" And ClsInfo='Fields'");
            Sql_FieldPermission.Append(") order by Indentity");

            StringBuilder Sql_RecordPermission = new StringBuilder();

            Sql_RecordPermission.Append("Select * from sys_auth_RecordPermission where RecordsID in (");
            //增加查询条件  Scdel=0  2013-10-17
            Sql_RecordPermission.Append("select ID from sys_auth_Permissions where Scdel=0 and ID in ");
            Sql_RecordPermission.Append(string.Concat("('", string.Join("','", PermissionIndex), "')"));
            Sql_RecordPermission.Append(" And ClsInfo='Records'");
            Sql_RecordPermission.Append(") order by Indentity");

            StringBuilder Sql_FunctionPermission = new StringBuilder();

            Sql_FunctionPermission.Append("Select * from sys_auth_FunctionPermission where FunctionsID in (");
            //增加查询条件  Scdel=0  2013-10-17
            Sql_FunctionPermission.Append("select ID from sys_auth_Permissions where Scdel=0 and ID in ");
            Sql_FunctionPermission.Append(string.Concat("('", string.Join("','", PermissionIndex), "')"));
            Sql_FunctionPermission.Append(" And ClsInfo='Functions'");
            Sql_FunctionPermission.Append(") order by Indentity");

            StringBuilder Sql_DataPermission = new StringBuilder();

            Sql_DataPermission.Append("Select * from sys_auth_DataPermission where TableID in (");
            //增加查询条件  Scdel=0  2013-10-17
            Sql_DataPermission.Append("select ID from sys_auth_Permissions where Scdel=0 and ID in ");
            Sql_DataPermission.Append(string.Concat("('", string.Join("','", PermissionIndex), "')"));
            Sql_DataPermission.Append(" And ClsInfo='Datas'");
            Sql_DataPermission.Append(") order by TableID");

            List <String> Sql_Commands = new List <string>();

            Sql_Commands.Add(Sql_Permissions.ToString());
            Sql_Commands.Add(Sql_FieldPermission.ToString());
            Sql_Commands.Add(Sql_RecordPermission.ToString());
            Sql_Commands.Add(Sql_FunctionPermission.ToString());
            Sql_Commands.Add(Sql_DataPermission.ToString());

            DataSet dataset = GetDataSet(Sql_Commands.ToArray());

            if (dataset != null)
            {
                DataTable PermissionDataTable         = dataset.Tables["sys_auth_Permissions"];
                DataTable FieldPermissionDataTable    = dataset.Tables["sys_auth_FieldPermission"];
                DataTable RecordPermissionDataTable   = dataset.Tables["sys_auth_RecordPermission"];
                DataTable FunctionPermissionDataTable = dataset.Tables["sys_auth_FunctionPermission"];
                DataTable DataPermissionDataTable     = dataset.Tables["sys_auth_DataPermission"];

                foreach (DataRow Row in PermissionDataTable.Rows)
                {
                    String Index       = Row["ID"].ToString();
                    String Cls         = Row["ClsInfo"].ToString();
                    String ModelIndex  = Row["ModuleID"].ToString();
                    String Description = Row["Description"].ToString();

                    PermissionType Type = Type = (PermissionType)Enum.Parse(typeof(PermissionType), Cls);
                    if (Type == PermissionType.Records)
                    {
                        RecordsPermission recordsPermission = new RecordsPermission();
                        recordsPermission.ModuleID = ModelIndex;
                        recordsPermission.Index    = Index;
                        recordsPermission.Caption  = Description;
                        permissionCollection.Add(recordsPermission);

                        DataRow[] RecordRows = RecordPermissionDataTable.Select("RecordsID='" + Index + "'");
                        foreach (DataRow RecordRow in RecordRows)
                        {
                            RecordListElement recordListElement = new RecordListElement();
                            recordListElement.Caption = RecordRow["Description"].ToString();
                            recordListElement.Index   = RecordRow["Indentity"].ToString();
                            recordListElement.Code    = RecordRow["RecordCode"].ToString();
                            recordsPermission.RecordPermissionList.Add(recordListElement);
                        }
                    }
                    else if (Type == PermissionType.Fields)
                    {
                        FieldsPermission fieldsPermission = new FieldsPermission();
                        fieldsPermission.ModuleID   = ModelIndex;
                        fieldsPermission.Index      = Index;
                        fieldsPermission.Caption    = Description;
                        fieldsPermission.FieldsName = Description;
                        permissionCollection.Add(fieldsPermission);

                        DataRow[] FieldRows = FieldPermissionDataTable.Select("FieldsID='" + Index + "'");
                        foreach (DataRow FieldRow in FieldRows)
                        {
                            FieldPermission fieldPermission = new FieldPermission();
                            fieldPermission.Index     = FieldRow["Indentity"].ToString();
                            fieldPermission.FieldName = FieldRow["Description"].ToString();
                            fieldPermission.Editable  = Convert.ToBoolean(FieldRow["Editable"]);
                            fieldPermission.Viewable  = Convert.ToBoolean(FieldRow["Viewable"]);
                            fieldsPermission.Fields.Add(fieldPermission);
                        }
                    }
                    else if (Type == PermissionType.Functions)
                    {
                        FunctionsPermission functionsPermission = new FunctionsPermission();
                        functionsPermission.ModuleID = ModelIndex;
                        functionsPermission.Index    = Index;
                        functionsPermission.Caption  = Description;
                        permissionCollection.Add(functionsPermission);

                        DataRow[] FunctionRows = FunctionPermissionDataTable.Select("FunctionsID='" + Index + "'");
                        foreach (DataRow FunctionRow in FunctionRows)
                        {
                            FunctionPermission functionPermission = new FunctionPermission();
                            functionPermission.Caption = FunctionRow["Description"].ToString();
                            functionPermission.Index   = FunctionRow["Indentity"].ToString();
                            functionsPermission.Functions.Add(functionPermission);
                        }
                    }
                    else if (Type == PermissionType.Datas)
                    {
                        DatasPermission datasPermission = new DatasPermission();
                        datasPermission.ModuleID = ModelIndex;
                        datasPermission.Index    = Index;
                        datasPermission.Caption  = Description;
                        permissionCollection.Add(datasPermission);

                        DataRow[] DataRows = DataPermissionDataTable.Select("TableID='" + Index + "'");
                        foreach (DataRow DataRow in DataRows)
                        {
                            DataPermission dataPermission = new DataPermission();
                            dataPermission.Index     = DataRow["TableID"].ToString();
                            dataPermission.FieldName = DataRow["FieldName"].ToString();

                            String FieldValueList = DataRow["FieldValues"].ToString();
                            if (!string.IsNullOrEmpty(FieldValueList))
                            {
                                String[] Values = FieldValueList.Split(new Char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                                dataPermission.Values.AddRange(Values);
                            }

                            datasPermission.Conditions.Add(dataPermission);
                        }
                    }
                }
            }

            return(permissionCollection);
        }
Exemplo n.º 5
0
        /// <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;
            }
        }
Exemplo n.º 6
0
        private void CompareFieldPermissions(List <string> diff, IEnumerable <FieldPermission> enumerable1, IEnumerable <FieldPermission> enumerable2, string tabSpacer)
        {
            var tableOnlyIn1 = new FormatTextTableHandler("Entity name", "Attribute Name", "Can Create", "Can Read", "Can Update");
            var tableOnlyIn2 = new FormatTextTableHandler("Entity name", "Attribute Name", "Can Create", "Can Read", "Can Update");

            var tableDifferent = new FormatTextTableHandler("FieldPermission"
                                                            , Connection1.Name + " Can Create"
                                                            , Connection2.Name + " Can Create"
                                                            , Connection1.Name + " Can Read"
                                                            , Connection2.Name + " Can Read"
                                                            , Connection1.Name + " Can Update"
                                                            , Connection2.Name + " Can Update"
                                                            );

            if (enumerable1 != null)
            {
                foreach (var item1 in enumerable1)
                {
                    string entityName1    = item1.EntityName;
                    string attributeName1 = item1.AttributeLogicalName;

                    if (enumerable2 != null)
                    {
                        var item2 = enumerable2.FirstOrDefault(i =>
                                                               string.Equals(i.EntityName, entityName1, StringComparison.InvariantCultureIgnoreCase) &&
                                                               string.Equals(i.AttributeLogicalName, attributeName1, StringComparison.InvariantCultureIgnoreCase)
                                                               );

                        if (item2 != null)
                        {
                            continue;
                        }
                    }

                    string cancreate1 = item1.FormattedValues.Contains(FieldPermission.Schema.Attributes.cancreate) ? item1.FormattedValues[FieldPermission.Schema.Attributes.cancreate] : string.Empty;
                    string canread1   = item1.FormattedValues.Contains(FieldPermission.Schema.Attributes.canread) ? item1.FormattedValues[FieldPermission.Schema.Attributes.canread] : string.Empty;
                    string canupdate1 = item1.FormattedValues.Contains(FieldPermission.Schema.Attributes.canupdate) ? item1.FormattedValues[FieldPermission.Schema.Attributes.canupdate] : string.Empty;

                    tableOnlyIn1.AddLine(entityName1, attributeName1, cancreate1, canread1, canupdate1);

                    tableOnlyIn2.CalculateLineLengths(entityName1, attributeName1, cancreate1, canread1, canupdate1);

                    this.ImageBuilder.AddComponentSolution1((int)ComponentType.FieldPermission, item1.Id);
                }
            }

            if (enumerable2 != null)
            {
                foreach (var item2 in enumerable2)
                {
                    string entityName2    = item2.EntityName;
                    string attributeName2 = item2.AttributeLogicalName;

                    if (enumerable1 != null)
                    {
                        var item1 = enumerable1.FirstOrDefault(i =>
                                                               string.Equals(i.EntityName, entityName2, StringComparison.InvariantCultureIgnoreCase) &&
                                                               string.Equals(i.AttributeLogicalName, attributeName2, StringComparison.InvariantCultureIgnoreCase)
                                                               );

                        if (item1 != null)
                        {
                            continue;
                        }
                    }

                    string cancreate2 = item2.FormattedValues.Contains(FieldPermission.Schema.Attributes.cancreate) ? item2.FormattedValues[FieldPermission.Schema.Attributes.cancreate] : string.Empty;
                    string canread2   = item2.FormattedValues.Contains(FieldPermission.Schema.Attributes.canread) ? item2.FormattedValues[FieldPermission.Schema.Attributes.canread] : string.Empty;
                    string canupdate2 = item2.FormattedValues.Contains(FieldPermission.Schema.Attributes.canupdate) ? item2.FormattedValues[FieldPermission.Schema.Attributes.canupdate] : string.Empty;

                    tableOnlyIn2.AddLine(entityName2, attributeName2, cancreate2, canread2, canupdate2);

                    tableOnlyIn1.CalculateLineLengths(entityName2, attributeName2, cancreate2, canread2, canupdate2);

                    this.ImageBuilder.AddComponentSolution2((int)ComponentType.FieldPermission, item2.Id);
                }
            }

            if (enumerable1 != null && enumerable2 != null)
            {
                foreach (var item1 in enumerable1)
                {
                    string entityName1    = item1.EntityName;
                    string attributeName1 = item1.AttributeLogicalName;

                    FieldPermission item2 = enumerable2.FirstOrDefault(i =>
                                                                       string.Equals(i.EntityName, entityName1, StringComparison.InvariantCultureIgnoreCase) &&
                                                                       string.Equals(i.AttributeLogicalName, attributeName1, StringComparison.InvariantCultureIgnoreCase)
                                                                       );

                    if (item2 != null)
                    {
                        continue;
                    }

                    string cancreate1 = item1.FormattedValues.Contains(FieldPermission.Schema.Attributes.cancreate) ? item1.FormattedValues[FieldPermission.Schema.Attributes.cancreate] : string.Empty;
                    string canread1   = item1.FormattedValues.Contains(FieldPermission.Schema.Attributes.canread) ? item1.FormattedValues[FieldPermission.Schema.Attributes.canread] : string.Empty;
                    string canupdate1 = item1.FormattedValues.Contains(FieldPermission.Schema.Attributes.canupdate) ? item1.FormattedValues[FieldPermission.Schema.Attributes.canupdate] : string.Empty;

                    string cancreate2 = item2.FormattedValues.Contains(FieldPermission.Schema.Attributes.cancreate) ? item2.FormattedValues[FieldPermission.Schema.Attributes.cancreate] : string.Empty;
                    string canread2   = item2.FormattedValues.Contains(FieldPermission.Schema.Attributes.canread) ? item2.FormattedValues[FieldPermission.Schema.Attributes.canread] : string.Empty;
                    string canupdate2 = item2.FormattedValues.Contains(FieldPermission.Schema.Attributes.canupdate) ? item2.FormattedValues[FieldPermission.Schema.Attributes.canupdate] : string.Empty;

                    if (cancreate1 != cancreate2 || canread1 != canread2 || canupdate1 != canupdate2)
                    {
                        this.ImageBuilder.AddComponentDifferent((int)ComponentType.FieldPermission, item1.Id, item2.Id);

                        tableDifferent.AddLine(entityName1, attributeName1
                                               , cancreate1, cancreate2
                                               , canread1, canread2
                                               , canupdate1, canupdate2
                                               );
                    }
                }
            }

            if (tableOnlyIn1.Count > 0)
            {
                diff.Add(string.Format("Privileges ONLY in {0}: {1}", Connection1.Name, tableOnlyIn1.Count));
                tableOnlyIn1.GetFormatedLines(true).ForEach(s => diff.Add(tabSpacer + s));
            }

            if (tableOnlyIn2.Count > 0)
            {
                diff.Add(string.Format("Privileges ONLY in {0}: {1}", Connection2.Name, tableOnlyIn2.Count));
                tableOnlyIn2.GetFormatedLines(true).ForEach(s => diff.Add(tabSpacer + s));
            }

            if (tableDifferent.Count > 0)
            {
                diff.Add(string.Format("Different Privileges {0} and {1}", Connection1.Name, Connection2.Name));
                tableDifferent.GetFormatedLines(true).ForEach(s => diff.Add(tabSpacer + s));
            }
        }
Exemplo n.º 7
0
        public async Task <IHttpActionResult> UpdatePermission(string fieldPermissionId, [FromBody] FieldPermission fieldPermission)
        {
            if (fieldPermission.Id != fieldPermissionId)
            {
                return(BadRequest("Field Permission Id does not match with request id"));
            }
            var result = await _fieldPermissionsService.UpdateFieldPermissionAsync(fieldPermission, UserName);

            return(Ok(result));
        }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// a FieldSecurityProfile object is created and tied to an existing team. Then a
        /// custom entity and several attributes are created and FieldPermission is
        /// assigned to the Identity attribute of the new entity.
        /// </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();

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

                    // Create the request object and set the monikers with the
                    // teamprofiles_association relationship.
                    AssociateRequest teamToProfile = new AssociateRequest
                    {
                        Target          = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId),
                        RelatedEntities = new EntityReferenceCollection
                        {
                            new EntityReference(Team.EntityLogicalName, _teamId)
                        },
                        Relationship = new Relationship("teamprofiles_association")
                    };

                    // Execute the request.
                    _serviceProxy.Execute(teamToProfile);

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

                    // Execute the request.
                    _serviceProxy.Execute(req);
                    Console.Write("Entity Created, ");

                    // Create custom attributes.
                    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"
                    };

                    // Execute the request.
                    CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq);
                    _identityId = identityAttributeResponse.AttributeId;
                    Console.Write("Identity Created, ");

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

                    // Execute the request.
                    CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq);
                    _messageId = messageAttributeResponse.AttributeId;
                    Console.Write("Message Created, ");

                    // Create the field permission for the Identity attribute.
                    FieldPermission identityPermission = new FieldPermission()
                    {
                        AttributeLogicalName = "new_identity",
                        EntityName           = "new_tweet",
                        CanRead = new OptionSetValue(FieldPermissionType.Allowed),
                        FieldSecurityProfileId = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId)
                    };

                    // Execute the request
                    _identityPermissionId = _serviceProxy.Create(identityPermission);
                    Console.Write("Permission Created. ");

                    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;
            }
        }
Exemplo n.º 9
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    ////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Create Field Security Profile.
                    FieldSecurityProfile managersProfile = new FieldSecurityProfile();
                    managersProfile.Name = "Managers";
                    _profileId           = service.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")
                    };
                    service.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")
                    };
                    service.Execute(userToProfile);

                    // Create custom activity entity.
                    CreateEntityRequest req = new CreateEntityRequest()
                    {
                        Entity = new EntityMetadata
                        {
                            LogicalName           = "new_message",
                            DisplayName           = new Label("Message", 1033),
                            DisplayCollectionName = new Label("Tweet", 1033),
                            OwnershipType         = OwnershipTypes.UserOwned,
                            SchemaName            = "New_Message",
                            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)
                        }
                    };
                    service.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)service.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)service.Execute(attrReq);
                    _identityId = identityAttributeResponse.AttributeId;
                    Console.Write("Identity Created, ");

                    // Create custom message attribute.
                    attrReq = new CreateAttributeRequest()
                    {
                        Attribute = new StringAttributeMetadata()
                        {
                            LogicalName   = "new_picture",
                            DisplayName   = new Label("Picture", 1033),
                            SchemaName    = "New_Picture",
                            MaxLength     = 140,
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(
                                AttributeRequiredLevel.Recommended),
                            IsSecured = true
                        },
                        EntityName = "new_tweet"
                    };
                    CreateAttributeResponse messageAttributeResponse =
                        (CreateAttributeResponse)service.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 = service.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)service.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 = service.RetrieveMultiple(qba).Entities;
                    Console.Write("Attributes Retrieved. ");

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

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

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Exemplo n.º 10
0
        public static bool CheckFieldPermission(Guid iUserID, String strTableName, String strFieldName, FieldPermission permission)
        {
            bool result = false;


            String strKey = iUserID.ToString() + strTableName + strFieldName + permission.ToString();

            if (FieldPermissionList.TryGetValue(strKey, out result))
            {
                return(result);
            }

            ADUsersInfo user = new ADUsersController().GetObjectByID(iUserID) as ADUsersInfo;

            if (user != null && user.FK_ADUserGroupID.HasValue)
            {
                ADUserGroupsInfo group = new ADUserGroupsController().GetObjectByID(user.FK_ADUserGroupID.Value) as ADUserGroupsInfo;
                if (group != null)
                {
                    result = (user.No == "sysadmin");
                    String strQuery = String.Format(@"SELECT TOP 1 A.* FROM  GEPermissionFields A JOIN ADUserPermissions B ON A.TableName ='{0}' AND A.FieldName ='{1}' AND B.FK_GEPermissionID = A.FK_GEPermissionID AND  (B.FK_ADUserGroupID ='{2}' OR B.FK_ADUserID ='{3}') ORDER BY B.FK_ADUserID  DESC", strTableName, strFieldName, user.FK_ADUserGroupID.Value, user.ADUserID);
                    foreach (GEPermissionFieldsInfo fieldPermission in new GEPermissionFieldsController().GetList(strQuery).Cast <GEPermissionFieldsInfo>().ToList())
                    {
                        switch (permission)
                        {
                        case FieldPermission.AllowView:
                            result = (result || fieldPermission.AllowView);
                            break;

                        case FieldPermission.AllowEdit:
                            result = (result || fieldPermission.AllowEdit);
                            break;
                        }
                    }
                }
            }
            if (SystemProvider.SystemConfig.IsRelease)
            {
                FieldPermissionList.Add(strKey, result);
            }
            return(result);
        }
        /// <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;
            }
        }
Exemplo n.º 12
0
        protected void createTabXML()
        {
            FieldPermissions allFieldPermissions = new FieldPermissions();

            DataTable permissionDataTable          = TabPermissionDataTable;
            DataTable permissionConditionDataTable = PermissionConditionDataTable;

            foreach (DataRow drPermission in permissionDataTable.Rows)
            {
                string OnField   = drPermission[Constants.PermissionField.SPFieldName].ToString();
                bool   IsDefault = Helper.ConvertToBool(drPermission[Constants.PermissionField.IsDefault].ToString());
                Enums.PermissionLevel permissionLevel = (Enums.PermissionLevel)(Convert.ToInt32(drPermission[Constants.PermissionField.PermissionID].ToString()));
                string         OnForms                = drPermission[Constants.PermissionField.OnFormIDs].ToString();
                string         ForSPPrinciples        = drPermission[Constants.PermissionField.SPPrinciples].ToString();
                Enums.Operator BySPPrinciplesOperator = (Enums.Operator)(Convert.ToInt32(drPermission[Constants.PermissionField.SPPrinciplesOperatorID].ToString()));
                int            permissionID           = Convert.ToInt32(drPermission[Constants.RowID]);

                FieldPermission perm1 = new FieldPermission(new Field(OnField), permissionLevel, FieldPermission.ParseForms(OnForms), ForSPPrinciples, BySPPrinciplesOperator);


                DataTable conditionOfSelectedPermission = Helper.GetViewFromDataTable(permissionConditionDataTable, permissionID, Constants.ConditionField.PermissionRowID).ToTable();

                if (conditionOfSelectedPermission != null && conditionOfSelectedPermission.Rows.Count > 0)
                {
                    foreach (DataRow drCondition in conditionOfSelectedPermission.Rows)
                    {
                        string         OnField2        = drCondition[Constants.ConditionField.SPFieldName].ToString();
                        Enums.Operator ByFieldOperator = (Enums.Operator)Convert.ToInt32(drCondition[Constants.ConditionField.SPFieldOperatorID].ToString());
                        object         Value           = drCondition[Constants.ConditionField.Value].ToString();

                        perm1.Conditions.Add(new Condition(new Field(OnField2), ByFieldOperator, Value));
                    }
                }

                allFieldPermissions.Add(perm1);
            }


            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite objSite = new SPSite(SPContext.Current.Web.Url.ToString()))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPList list = objWeb.Lists[new Guid(Request.QueryString["List"])];

                        objWeb.AllowUnsafeUpdates = true;

                        string xml = allFieldPermissions.ToString();
                        if (allFieldPermissions.Count > 0 && Helper.IsValidXml(xml))
                        {
                            Helper.CreateConfigFile(list, Constants.ConfigFile.FieldPermissionFile, xml);
                        }
                        else
                        {
                            Helper.DeleteConfigFile(list, Constants.ConfigFile.FieldPermissionFile, xml);
                        }

                        objWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
        protected void createTabXML()
        {
            FieldPermissions allFieldPermissions = new FieldPermissions();

            DataTable permissionDataTable = TabPermissionDataTable;
            DataTable permissionConditionDataTable = PermissionConditionDataTable;

            foreach (DataRow drPermission in permissionDataTable.Rows)
            {
                string OnField=drPermission[Constants.PermissionField.SPFieldName].ToString();
                bool IsDefault = Helper.ConvertToBool(drPermission[Constants.PermissionField.IsDefault].ToString());
                Enums.PermissionLevel permissionLevel = (Enums.PermissionLevel)(Convert.ToInt32(drPermission[Constants.PermissionField.PermissionID].ToString()));
                string OnForms = drPermission[Constants.PermissionField.OnFormIDs].ToString();
                string ForSPPrinciples = drPermission[Constants.PermissionField.SPPrinciples].ToString();
                Enums.Operator BySPPrinciplesOperator = (Enums.Operator)(Convert.ToInt32(drPermission[Constants.PermissionField.SPPrinciplesOperatorID].ToString()));
                int permissionID = Convert.ToInt32(drPermission[Constants.RowID]);

                FieldPermission perm1 = new FieldPermission(new Field(OnField), permissionLevel, FieldPermission.ParseForms(OnForms), ForSPPrinciples, BySPPrinciplesOperator);


                DataTable conditionOfSelectedPermission = Helper.GetViewFromDataTable(permissionConditionDataTable, permissionID, Constants.ConditionField.PermissionRowID).ToTable();

                if (conditionOfSelectedPermission != null && conditionOfSelectedPermission.Rows.Count > 0)
                {
                    foreach (DataRow drCondition in conditionOfSelectedPermission.Rows)
                    {
                        string OnField2 = drCondition[Constants.ConditionField.SPFieldName].ToString();
                        Enums.Operator ByFieldOperator = (Enums.Operator)Convert.ToInt32(drCondition[Constants.ConditionField.SPFieldOperatorID].ToString());
                        object Value = drCondition[Constants.ConditionField.Value].ToString();

                        perm1.Conditions.Add(new Condition(new Field(OnField2), ByFieldOperator, Value));
                    }

                }

                allFieldPermissions.Add(perm1);
            }


            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite objSite = new SPSite(SPContext.Current.Web.Url.ToString()))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPList list = objWeb.Lists[new Guid(Request.QueryString["List"])];

                        objWeb.AllowUnsafeUpdates = true;

                        string xml = allFieldPermissions.ToString();
                        if (allFieldPermissions.Count > 0 && Helper.IsValidXml(xml))
                        {

                            Helper.CreateConfigFile(list, Constants.ConfigFile.FieldPermissionFile, xml);
                        }
                        else
                        {
                            Helper.DeleteConfigFile(list, Constants.ConfigFile.FieldPermissionFile, xml);
                        }

                        objWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
            
        }
Exemplo n.º 14
0
        public async Task <FieldPermission> UpdateFieldPermissionAsync(FieldPermission fieldPermission, string userName)
        {
            var result = await _fieldPermissionsRepository.UpdateAsync(fieldPermission);

            return(result);
        }
Exemplo n.º 15
0
 public async Task <FieldPermission> AddFieldPermissionAsync(FieldPermission fieldPermission, string userName)
 {
     return(await _fieldPermissionsRepository.AddAsync(fieldPermission));
 }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// a FieldSecurityProfile object is created and tied to an existing team. Then a
        /// custom entity and several attributes are created and FieldPermission is 
        /// assigned to the Identity attribute of the new entity.
        /// </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
            {
                //<snippetEnableFieldSecurityForAnEntity1>
                // 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, ");

                    //<snippetEnableFieldSecurityForAnEntity2>
                    // Create the request object and set the monikers with the
                    // teamprofiles_association relationship.
                    AssociateRequest teamToProfile = new AssociateRequest
                    {
                        Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId),
                        RelatedEntities = new EntityReferenceCollection
                        {
                            new EntityReference(Team.EntityLogicalName, _teamId)
                        },
                        Relationship = new Relationship("teamprofiles_association")
                    };

                    // Execute the request.
                    _serviceProxy.Execute(teamToProfile);
                    //</snippetEnableFieldSecurityForAnEntity2>

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

                    // Execute the request.
                    _serviceProxy.Execute(req);
                    Console.Write("Entity Created, ");

                    // Create custom attributes.
                    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"
                    };

                    // Execute the request.
                    CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq);
                    _identityId = identityAttributeResponse.AttributeId;
                    Console.Write("Identity Created, ");

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

                    // Execute the request.
                    CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq);
                    _messageId = messageAttributeResponse.AttributeId;
                    Console.Write("Message Created, ");

                    // Create the field permission for the Identity attribute.
                    FieldPermission identityPermission = new FieldPermission()
                    {
                        AttributeLogicalName = "new_identity",
                        EntityName = "new_tweet",
                        CanRead = new OptionSetValue(FieldPermissionType.Allowed),
                        FieldSecurityProfileId = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId)
                    };

                    // Execute the request
                    _identityPermissionId = _serviceProxy.Create(identityPermission);
                    Console.Write("Permission Created. ");

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

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