Customization of CRM application on basis of security role

Changes which are need to be made:-

  1. Change in the security role

  2. Customization of all the CRM form (Home page, Form Data Entry page, Form grid page)

  3. Changing the views according to the roles

Change in the security role

Change in the security role is made in the Setting → Administration → Security Role.

The privilege can be given on the basis of

  1. None:- That privilege will not be given

  2. User :- That user will able to do operation on his/her records only.

  3. Business Unit :- That user will able to do operation on his/her business unit records only.

  4. Parent Business Unit :- That user will able to do operation on his/her parent business unit records only.

  5. Organization :-That user will able to do operation on all records.

Customization of all the CRM form (Home page, Form Data Entry page, Form grid page)

There are two things which are needed to be changed:-

  1. Ribbon Button

  2. Site map

Ribbon button Customization

Steps(Example :- Advance Find):-

  1. Create an entity in the name of the button (new_advancefindrole)

  2. Give the permission to the entity(new_advancefindrole) in the Security Role under custom entity(Read).

  3. Open the ribbon solution in a ribbon editor.

  4. Add a new button and copy  the (detail,action , display rule, enable rule ) from advance find to new button

  5. Add a new display rule

    1. Entity Privilege rule

    2. Give the name of the entity( new_advancefindrole)

    3. Privilege depth :- Basic

    4. Privilege type :- Read

    5. Default :- true

    6. Invert Result :- false

  1. Hide the original advance find button(we can’t change the display rule in original advance find as it is managed)

  2. save the customization

  3. give permission under security role to entity(new_advancefindrole) to read to show in different roles.

Site Map

Steps(Example :- Settings):-

  1. Create an entity in the name of the button (new_settingsrole)

  2. Give the permission to the entity(new_settingsrole) in the Security Role under custom entity(Read).

  3. Export the “Site map” solution from the CRM

  4. Open Customization.xml in an xml editor

  5. Find “Area Id=<AreaName>(Ex :- Settings)” tag. Paste the Code Below.

<SubAreaId=nav_administrationResourceId=Homepage_AdministrationDescriptionResourceId=Administration_SubArea_DescriptionIcon=/_imgs/ico_18_administration.gifUrl=/tools/Admin/admin.aspxAvailableOffline=false >

                       <PrivilegeEntity=new_settingsrolePrivilege=Read />

                   </SubArea>

  1. Paste this code under every subarea of the settings

  2. Save the solution zip it , import it and publish it

  3. give permission under security role to entity(new_settingsrole) to read to show in different roles.

Changing the views according to the roles

Showing the view according to the role. There are two method in which this can be done :-

  1. By plug-in

  2. By creating personal view and sharing it with team

By Plug-in

Steps:-

  1. Create the Plug-in with following code.

  2. By this plug-in the view Starting from “My” will not be shown

  3. Register it :-

    1. Message :- RetriveMultiple

    2. Primary Entity :- savedquery

    3. Eventing :- Per-operation

    4. Execution Mode:- Synchronous

    5. Deployment:- Server

Plug-in Code:-

using System;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.Text;

using System.Xml;

using System.Xml.XPath;

using Microsoft.Crm.Sdk;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

using Microsoft.Xrm.Sdk.Messages;

using Microsoft.Crm.Sdk.Messages;

namespace Excitation.PluginHideSystemViews

{

    publicclassCheckView : IPlugin

    {

        publicvoid Execute(IServiceProvider serviceProvider)

        {

            try

            {

               // Obtain the execution context from the service provider.

               Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)

               serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

               // Obtain the organization service reference.

               IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

               IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

               // The InputParameters collection contains all the data passed in the message request.

               if (CheckRole(context.UserId, “Salesperson”, service))

                {

                   if (context.InputParameters.Contains(“Query”) == true && context.InputParameters["Query"] isQueryExpression)

                   {

                       QueryExpression qe = (QueryExpression)context.InputParameters["Query"];

                       if (qe.EntityName == “savedquery”)

                       {

                           if (qe.Criteria != null)

                           {

                               if (qe.Criteria.Conditions != null)

                               {

                                   /*The query is edited to look at views not starting with “My” at the begining of the View Name*/

                                   ConditionExpression queryCondition = newConditionExpression(“name”, ConditionOperator.NotLike, “My%”);

                                   qe.Criteria.Conditions.Add(queryCondition);

                                  //context.InputParameters.Properties[ParameterName.Query] = qe;

                                   context.InputParameters["Query"] = qe;

                               }

                           }

                       }

                   }

                }

               else

                {

                   QueryExpression qe = (QueryExpression)context.InputParameters["Query"];

                   context.InputParameters["Query"] = qe;

                }

            }

            catch (Exception e)

            {

            }

        }

        //check if the user belongs to the specified role….

        privatestaticbool CheckRole(Guid UserGuid, string SecurityRole, IOrganizationService CrmService)

        {

           #region Retrieve records from an intersect table via QueryExpression

           //Create Query Expression to fetch Role Entity

           QueryExpression Query = newQueryExpression()

            {

               //Setting the link entity condition and filter condition criteria/

               LinkEntities =

                       {                           

                           newLinkEntity

                           {

                               LinkFromEntityName = “role”,

                               LinkFromAttributeName = “roleid”,

                               LinkToEntityName = “systemuserroles”,

                               LinkToAttributeName = “roleid”,

                               LinkCriteria = newFilterExpression

                               {

                                   FilterOperator = LogicalOperator.And,

                                   Conditions =

                                   {

                                       newConditionExpression

                                       {

                                           AttributeName = “systemuserid”,

                                           Operator = ConditionOperator.Equal,

                                           Values = { UserGuid }

                                       }

                                   }

                               }

                           }

                       }

            };

           Query.EntityName = “role”;

           Query.ColumnSet = newColumnSet(true);

            // Obtain results from the query expression.

           EntityCollection UserRoles = CrmService.RetrieveMultiple(Query);

            // Searching for a specified Security Role into the list

           String test = “”;

            test = UserGuid + ”   \n”;

           foreach (Entity UserSecurityRole in UserRoles.Entities)

            {

               test += (String)UserSecurityRole.Attributes["name"] + ” \n”;

               if ((String)UserSecurityRole.Attributes["name"] == SecurityRole)

                {

                   returntrue;

                }

            }

           Entity testE = newEntity(“new_transfer_opp”);

           testE.Attributes["new_name"] = test;

           CrmService.Create(testE);

            if (UserRoles.Entities.Count == 0)

            {

               //return false as the role does not present

               returnfalse;

            }

            else

            {

               returnfalse;

            }

           #endregion

        }

    }

}

By creating personal view and sharing it with team

Steps(Example:- Sale manager):-

  1. Create a team(Sales manager) and add user to that team (Team is added under Administration)

  2. Create a view by Advance find Save that view

  3. Go to saved view and share the view to the team you want to see that view.

How to get asp.net Check box value using c#?

ASP.NET Control We have:

<asp:CheckBox ID="chkMyCheckbox" runat="server" />

You can read checkbox value by IsChecked property
bool didYouChecked= chkMyCheckbox.IsChecked; // returns true or false

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>

If you have checkbox list
var selectedItems = CheckBoxList1.Items.Cast.Where(x => x.Selected);

How to redirect to another page after alert message in c#?

There is some situation where we want to show alert message and confiration
message before redirecting to another page.

Method 1

Response.Write("<script> alert('Your Message.');window.location='TargetpageURL'; </script>");

Method 2

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ScriptKey", "alert('Your Message will go here.');window.location='TargetpageURL'; ", true);

Method 3

HTMLHelper.jsAlertAndRedirect(this, "This is an alert.", ResolveUrl("~/Default.aspx"));

Method 4

string  strScript = "<script>"+"alert('your message.');";
                strScript += "window.location='test.aspx';";
                strScript += "</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Startup", strScript);

Umbraco get member by username by c#.

umbraco Get member by email address

Member memInfo = GetMemberFromEmail("xyz@gmail.com");

Get member from cache in umbraco

Member currentMem = Member.GetCurrentMember();
Member memInfo = GetMemberFromCache(currentMem.Id);

Get member by username in umbraco

Member[] memberList = GetMemberByName("username", false);

Get member by Name instead of user name in umbraco

Member[] memberList = GetMemberByName("name", true);

umbraco Get current member information

Member currentMem = Member.GetCurrentMember();

umbraco Get current member loginName

Member currentMem = Member.GetCurrentMember();
string memeberLoginName = currentMem.LoginName;

umbraco Get current member password

Member currentMem = Member.GetCurrentMember();
string currentMemPassword = currentMem.Password;

umbraco Get current member Id

Member currentMem = Member.GetCurrentMember();
int memberId = currentMem.Id;

I hope it will help :)

How to Get Client Ip address in asp.net .

You can capture Ip address of client.
Firs Method

        /// <summary>
        /// Get Client Ip address
        /// </summary>
        /// <returns></returns>
        public string GetClientIpAddress()
        {
            HttpRequest currentRequest = HttpContext.Current.Request;
            string ipAddress = currentRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (ipAddress == null || ipAddress.ToLower() == "unknown")
                ipAddress = currentRequest.ServerVariables["REMOTE_ADDR"];

            return ipAddress;
        }

Alternative One:

        /// <summary>
        /// Get Client Ip address
        /// </summary>
        /// <returns></returns>
        public string GetClientIpAddress()
        {
            string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            return ipAddress;
        }

Hope this will help :)

How to Upload Image asynchronously in asp.net by c#.

 +Summary

In Asp.net we have File Uploader control which is used for upload image , document and file on server. But it need postback to save on server. Some time this is not feasible solution for uploading image by post back. So In this post we will used Jquery plugin which will help us to upload image asynchronously.

 + Jquery File

Jquery File Uploader file Download From Here

 + AjaxFileUploader.ashx.cs File 

For uploading image asynchronously we will create generic handler in c#. First create generic handler and pest below code.

    /// <summary>
    /// Summary description for AjaxFileUploader
    /// </summary>
    public class AjaxFileUploader : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                string path = context.Server.MapPath("~/images/Temp");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                var file = context.Request.Files[0];

                string fileName;

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = file.FileName.Split(new char[] { '\\' });
                    fileName = files[files.Length - 1];
                }
                else
                {
                    fileName = file.FileName;
                }
                string strFileName = fileName;
                fileName = Path.Combine(path, fileName);
                file.SaveAs(fileName);

                string msg = "{";
                msg += string.Format("error:'{0}',\n", string.Empty);
                msg += string.Format("msg:'{0}'\n", "images/Temp/"+strFileName);
                msg += "}";
                context.Response.Write(msg);
            }
        }
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
 + FileUploader.aspx File 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery.js" type="text/javascript"></script>
    <script src="Scripts/ajaxfileupload.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:FileUpload ID="fuProfilePicUpload"  ClientIDMode="Static" runat="server" />
      <div id="divLoader" style="display:none">Please wait.............</div>
      <button id="btnUpload" onclick="return ajaxFileUpload();">Upload</button>
    </div>
    </form>
</body>
</html>
 + JavaScript Code 
<script type="text/javascript">
    function ajaxFileUpload() {

        $("#divLoader").ajaxStart(function () {
            $(this).show();
        }).ajaxComplete(function () {
            $(this).hide();
        });
        $.ajaxFileUpload(
       {
           url: 'AjaxFileUploader.ashx',
           secureuri: false,
           fileElementId: 'fuProfilePicUpload',
           dataType: 'json',
           data: { name: 'logan', id: 'id' },
           success: function (data, status) {
               if (typeof (data.error) != 'undefined') {
                   if (data.error != '') {
                       alert(data.error);
                   } else {
                       alert("Uploaded Successfully");
                   }
               }
           },
           error: function (data, status, e) {
               alert(e);
           }
       }
   )
        return false;
    }
</script>

I hope it will help you :)