Thursday, December 20, 2012

Disabling all Fields on a Form in CRM 2011 - JS

Disabling all Fields on a Form in CRM 2011 - Andrew Zimmer - Avtex Blogs for SharePoint, Microsoft CRM, .NET Development, and Infrastructure Services:

'via Blog this'

Tuesday, November 27, 2012

Disabling all Fields on a Form in CRM 2011(Locking Form for Editing)

Disabling all Fields on a Form in CRM 2011 - Andrew Zimmer - Avtex Blogs for SharePoint, Microsoft CRM, .NET Development, and Infrastructure Services:


"function doesControlHaveAttribute(control) {
    var controlType = control.getControlType();
    return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
}

function disableFormFields(onOff) {

    Xrm.Page.ui.controls.forEach(function (control, index) {
        if (doesControlHaveAttribute(control)) {
            control.setDisabled(onOff);
        }
    });
}"

Usage
disableFormFields(true);

Thursday, August 16, 2012

Connecting to CRM online Office 365 From webresource Utility

I was trying to connect to the office 365 env via the webresource utility tool provided in the SDK.

I was getting the error that MetaData Cannot be resolved and i noticed that the URL is pointing to https://dev.orgname.crm.dynamics.com/XRMServices/2011/Discovery.svc

but when i see the actual url for the discovery service in the developer resources section of the customization then its a different url

https://disco.orgname.crm.dynamics.com/XRMServices/2011/Discovery.svc

So to resolve this issue i had to make a minor change in the code for the webresource utility tool. 

Open the webresource utility solution and in the DataAccess folder open ConsolelessServerConnection.cs

locate the method with the below signature
public virtual ServerConnection.Configuration GetServerConfiguration(string server, string orgName, string user, string pw, string domain )

and change  config.DiscoveryUri =
new Uri(String.Format("https://dev.{0}/XRMServices/2011/Discovery.svc", config.ServerAddress));

to

config.DiscoveryUri =
new Uri(String.Format("https://disco.{0}/XRMServices/2011/Discovery.svc", config.ServerAddress));

This will resolve the issue.

We might have to go the same change for other tools also. so just incase if you face similar issue then you can try this


Thursday, July 26, 2012

Encrypt web.cong files


Below are the steps to do this

1) Encrypt appsettings in web.config using Aspnet_regiis.exe
using Aspnet_regiis.exe you can encrypt whole section only not a particular key.so when you need to encrypt a particular key in appSettings things get complicated. Here is a roundabout way of doing this. Modify your web.config



2) Under AppSettings you can add any key value pairs.

Also secureAppSettings is the name i had given. You can give any. Save this web.config file and go to visual studio command prompt

3) Type

aspnet_regiis -pef secureAppSettings  “ur web.config path”  -prov DataProtectionConfigurationProvider


4) In code you can access it as usual

NameValueCollection secureAppSettings = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings")
String str= secureAppSettings["ipwd"];


For example to decrypt identity section
aspnet_regiis -pdf "system.web/identity" "C:\Inetpub\sampleapplication"



Tuesday, June 19, 2012

Jquery Mobile Dialog when ajax is disabled

Click Here:

Normally, dialog boxes in JQM do not require full HTML pages, just HTML snippets (e.g. :layout => nil) as they are loaded via AJAX and work like jQuery UI dialogs.

However, when you set "$.mobile.ajaxEnabled = false" JQM will no longer load dialogs via ajax, EVEN if you set "data-ajax=true" on the dialog links. That seems like a bug to me, ignoring "data-ajax=true". A patch to fix the problem:
diff --git js/jquery.mobile.navigation.js js/jquery.mobile.navigation.js
index f85a491..181b9c9 100755
--- js/jquery.mobile.navigation.js
+++ js/jquery.mobile.navigation.js
@@ -1322,10 +1322,11 @@
                        var baseUrl = getClosestBaseUrl( $link ),
 
                                //get href, if defined, otherwise default to empty hash
-                               href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl );
+                               href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl ),
+        isTargetDialog = $link.data("rel") === "dialog";
 
                        //if ajax is disabled, exit early
-                       if( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ){
+                       if( !$.mobile.ajaxEnabled && !isTargetDialog && !path.isEmbeddedPage( href ) ){
                                httpCleanup();
                                //use default click handling
                                return;

Monday, May 28, 2012

CRM Fetch XML Execute Tool

This tool is developed to execute custom fetch xml to get the results from the connected crm environment
please feel free to post your suggestions to improve this tool

you can find the source code and the executable from the below link.

https://crm2011fetchexecute.codeplex.com/

Tuesday, April 24, 2012

Using JQuery and Json in Ribbon button’s function handler(Include JS files in Ribbon Button Script)


  • In one of my CRM 2011 requirement, I had to update a record using ribbon button placed on CRM grid.
  • I had written an update script which calls OData service using Json & JQuery. (link)
  • But when I execute the function, I got “$ undefined” exception.
  • I wondered since I already had “Json.js” & “JQuery.js” web resources added to my entity.
  • After digging deeper, I came to know that, “JQuery.js” web resource is not getting loaded when my ribbon button’s function handler fired.
Fix :-
  • I fixed the problem by loading “JQuery.js” web resource dynamically, before I call my update method.
  • Below is the script to load the web resource’s


 var JScriptWebResourceUrl = “../WebResources/new_JQuery”;
var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
xmlHttp.open(“GET”, JScriptWebResourceUrl, false);
xmlHttp.send();
eval(xmlHttp.responseText);

Saturday, April 21, 2012

CRM 2011 Add notifications to entity form


CRM 2011: Notification area


function DC_Notification() {
    var attributes = Xrm.Page.data.entity.attributes;
    
    var notificationsArea = document.getElementById('crmNotifications');
    /*clear out notification area*/
    notificationsArea.SetNotifications(null, null);

    if (notificationsArea == null)
    {
        alert('div not found');
        return;
    }
    /*
    The integer is the notification type
    1 = Error
    2 = Warning
    3 = Info
    notificationsArea.AddNotification("<;unique value>;", 3, "","Your text here");
    */
    /*Create some notifications*/
    notificationsArea.AddNotification("1", 1, "1","Test 1");
    notificationsArea.AddNotification("2", 2, "2","Test 2");
    notificationsArea.AddNotification("3", 3, "3","Test 3");
}

Saturday, March 17, 2012

Win 8 consumer preview

installed windows 8 consumer preview..... First look has the wow feeling!!!!!!!

Tuesday, March 13, 2012

Read Configuration file (Web resource - Data (Xml)...

Read Configuration file (Web resource - Data (Xml)...: Sometimes, we would like to read data of configuration file which has been added as web resource of type Data (Xml) in Dynamic CRM. In t...

Tuesday, February 28, 2012

Get User Security Roles in Jscript


function GetAllSystemRoles() {
    var serverUrl = Xrm.Page.context.getServerUrl();

    var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
    oDataEndpointUrl += "RoleSet";
    var service = GetRequestObject();
    if (service != null) {
   
    service.open("GET", oDataEndpointUrl, false);
    service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
    service.setRequestHeader("Accept", "application/json, text/javascript, */*");
    service.send(null);

    var requestResults = eval('(' + service.responseText + ')').d;
    return requestResults;
    }
}


function GetRoleIdByName(allsecurityRoles,rolename) {
    if (allsecurityRoles != null && allsecurityRoles.results.length > 0) {
        for (var i = 0; i < allsecurityRoles.results.length; i++) {
            var role = allsecurityRoles.results[i];
            if (role.Name == rolename) {
                id = role.RoleId;
                return id;
            }

        }
    }
    return null;
}

function UserHasRole(allsecurityRoles) {
    debugger;
    var nsrApprovedPrivilage = new Array("Pricing Analyst", "TSC", "Pricing Team manager", "TSC Manager", "Sales Manager - Direct", "Sales Manager - Telesales", "Sales Manager - Winback", "General Manager - Direct", "TSM");
    for (var j = 0; j < nsrApprovedPrivilage.length; j++) {
        var id = GetRoleIdByName(allsecurityRoles, nsrApprovedPrivilage[j]);
        var currentUserRoles = Xrm.Page.context.getUserRoles();
        for (var i = 0; i < currentUserRoles.length; i++) {
            var userRole = currentUserRoles[i];
            if (GuidsAreEqual(userRole, id)) {
                return true;
            }
        }
    }
   return false;
}

function GetRequestObject() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}

function GuidsAreEqual(guid1, guid2) {
    var isEqual = false;

    if (guid1 == null || guid2 == null) {
        isEqual = false;
    }
    else {
        isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
    }

    return isEqual;
}



function CheckIfUserCanApprove() {
    debugger;
    var hasPrivilagesToApprove = UserHasRole(GetAllSystemRoles());
    if (hasPrivilagesToApprove) {
        alert("hasPrivilagesToApprove");
    }
    else {
        alert("does not have hasPrivilagesToApprove");
    }
}


Add the list of security roles in nsrApprovedPrivilage array to check if user has that particular role

Monday, February 20, 2012

CRM 2011 Convert EntityCollection to DataTable


public DataTable convertEntityCollectionToDataTable(EntityCollection BEC)
        {
            DataTable dt = new DataTable();
            int total = BEC.Entities.Count;
            for (int i = 0; i < total; i++)
            {
                DataRow row = dt.NewRow();
                Entity myEntity = (Entity)BEC.Entities[i];
                var keys= myEntity.Attributes.Keys;
                foreach (var item in keys)
           {
                    string columnName = item;
                    string value = getValuefromAttribute(myEntity.Attributes[item]);
                    if (dt.Columns.IndexOf(columnName) == -1)
                    {
                        dt.Columns.Add(item, Type.GetType("System.String"));
                    }
                    row[columnName] = value;
                }
                dt.Rows.Add(row);
            }
            return dt;
        }

        private string getValuefromAttribute(object p)
        {
            if (p.ToString() == "Microsoft.Xrm.Sdk.EntityReference")
            {
                return ((EntityReference)p).Name;
            }
            if (p.ToString() == "Microsoft.Xrm.Sdk.OptionSetValue")
            {
                return ((OptionSetValue)p).Value.ToString();
            }
            if (p.ToString() == "Microsoft.Xrm.Sdk.Money")
            {
                return ((Money)p).Value.ToString();
            }
            if (p.ToString() == "Microsoft.Xrm.Sdk.AliasedValue")
            {
                return ((Microsoft.Xrm.Sdk.AliasedValue)p).Value.ToString();
            }
            else
            {
                return p.ToString();
            }
        }

Tuesday, February 7, 2012

code that can retrieve total number of your desired entity



 code that can retrieve total number of your desired entity and return this as int
///

/// Gets the supplied entity count from CRM 2011.
///

/// "Service">The CRM 2011 service.
/// "EntityName">Name of the entity we need get count of.
/// "ServicePageSize">Size of the page (optional).
///
private int GetEntityCount(IOrganizationService Service, string EntityName, int ServicePageSize = 5000)
{
RetrieveMultipleResponse retrieved;
int PageNumber = 1;
string PagingCookie = string.Empty;
int PageSize = ServicePageSize;

do {
QueryExpression query = new QueryExpression() {
EntityName = EntityName,
//ColumnSet = new ColumnSet(Columns),
PageInfo = new PagingInfo() {
PageNumber = 1,
Count = PageSize
}
};

if (PageNumber != 1) {
query.PageInfo.PageNumber = PageNumber;
query.PageInfo.PagingCookie = PagingCookie;
}

RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieved = (RetrieveMultipleResponse)Service.Execute(retrieve);

if (retrieved.EntityCollection.MoreRecords) {
PageNumber++;
PagingCookie = retrieved.EntityCollection.PagingCookie;
}
} while (retrieved.EntityCollection.MoreRecords);

return ((PageNumber - 1) * PageSize) + retrieved.EntityCollection.Entities.Count;
}

Monday, February 6, 2012

Get User Security Roles


private EntityCollection GetUserSecurityRole(Guid userGuid, IOrganizationService service)
        {
            var query = new QueryExpression
            {
                LinkEntities =
                                {
                                new LinkEntity
                                {
                                    LinkFromEntityName = "role",
                                    LinkFromAttributeName = "roleid",
                                    LinkToEntityName = "systemuserroles",
                                    LinkToAttributeName = "roleid",
                                    LinkCriteria = new FilterExpression
                                        {
                                            FilterOperator =LogicalOperator.And,
                                            Conditions =
                                            {
                                            new ConditionExpression
                                            {
                                            AttributeName =  "systemuserid",
                                            Operator =    ConditionOperator.Equal,
                                            Values =
                                                        {
                                                        userGuid
                                                        }
                                            }
                                        }
                                }
                                }
                                },
                ColumnSet = new ColumnSet(true),
                EntityName = "role"
            };
            var userRoles = service.RetrieveMultiple(query);

            return userRoles;
        }

Monday, January 23, 2012

How to get access privilages for a user on a particular record

            RetrievePrincipalAccessRequest req = new RetrievePrincipalAccessRequest();

            //specify team or systemuser you want to get privileges for
            req.Principal = new EntityReference("team", teamId);

            //specify the CRM record you want to check principal permissions for (can be any entity type)
            req.Target = new EntityReference("account", accountid);

            RetrievePrincipalAccessResponse resp = (RetrievePrincipalAccessResponse)service.Execute(req);
            return resp.AccessRights.ToString();