Saturday, July 31, 2010

How to Hide a Tab in an Entity MS CRM 4.0

Sometime user required to hide a tab in an Entity then use the following line of code:

crmForm.all.tab3Tab.style.display = "none";

Thursday, July 29, 2010

Override Custom Tool Tips On-Mouse-Over in MS CRM 4.0

Some time users give more information into what they should enter into a field? You can either make the label of a given field really long, put a field in a section on it's own, and write the description out in the section title, or you could use scripts to override the tool tip of the field.
Here's the script:
var oPopup = window.createPopup();
var oPopupBody = oPopup.document.body;
oPopupBody.style.fontFamily = 'Tahoma';
oPopupBody.style.border = '1px solid black';
function My_OrgName_showRatingPopup ()
{
oPopupBody.innerHTML = "<div><table style='font-size:xx-small'>";
oPopupBody.innerHTML += "<tr><td><b></b></td><td> Custom Tool Tip Text Here</td></tr></table></div>";
var x_coord = -100;
var y_coord = 20;
var width = 350;
var height = 90;
var documentElement = event.srcElement;
oPopup.show(x_coord, y_coord, width, height, documentElement);
}
//Be sure to modify the field name here so that you attach your OnMouseOver event
//to the correct field. The "_c" indicates the label of the field.
crmForm.all.new_customfield_c.attachEvent('onmouseover', My_OrgName_showRatingPopup);
Now just hover over your field label and you'll see you new custom tooltip pop up.

To read in detail <a href="http://blog.expertsoftware.co.uk/?tag=/mscrm&page=2">Click Here</a>. Original Post: <a href="http://blog.expertsoftware.co.uk/?tag=/mscrm&page=2">expertsoftware </a>

Wednesday, July 28, 2010

Calling a workflow of MS CRM 4.0 from c# code (ExecuteWorkflow Message (CrmService)).

Executes a workflow.

To perform this action, the caller must have access rights on the workflow entity instance.

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create an ExecuteWorkflow request.
ExecuteWorkflowRequest request = new ExecuteWorkflowRequest();

//Assign the ID of the workflow you want to execute to the request.
request.WorkflowId = new Guid("b050f053-6968-dc11-bb3a-0003ffbad37a");

//Assign the ID of the entity to execute the workflow on to the request.
request.EntityId = new Guid("1DCDEE97-35BB-44BE-8353-58BC36592656");

// Execute the workflow.
ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)service.Execute(request);

Tuesday, July 27, 2010

How to compare more than one column in where clouse using "NOT IN" in SQL Server

answer is: CHECKSUM

CHECKSUM computes a hash value, called the checksum, over its list of arguments. The hash value is intended for use in building hash indices. If the arguments to CHECKSUM are columns, and an index is built over the computed CHECKSUM value, the result is a hash index, which can be used for equality searches over the columns.

CHECKSUM satisfies the properties of a hash function: CHECKSUM applied over any two lists of expressions returns the same value if the corresponding elements of the two lists have the same type and are equal when compared using the equals (=) operator. For the purpose of this definition, NULL values of a given type are considered to compare as equal. If one of the values in the expression list changes, the checksum of the list also usually changes. However, there is a small chance that the checksum will not change.

BINARY_CHECKSUM and CHECKSUM are similar functions: they can be used to compute a checksum value on a list of expressions, and the order of expressions affects the resultant value. The order of columns used in the case of CHECKSUM(*) is the order of columns specified in the table or view definition, including computed columns.

CHECKSUM and BINARY_CHECKSUM return different values for the string data types, where locale can cause strings with different representation to compare equal. The string data types are char, varchar, nchar, nvarchar, or sql_variant (if its base type is a string data type). For example, the BINARY_CHECKSUM values for the strings "McCavity" and "Mccavity" are different. In contrast, in a case-insensitive server, CHECKSUM returns the same checksum values for those strings. CHECKSUM values should not be compared against BINARY_CHECKSUM values.
Examples
Using CHECKSUM to build hash indices

The CHECKSUM function may be used to build hash indices. The hash index is built by adding a computed checksum column to the table being indexed, then building an index on the checksum column.

-- Create a checksum index.
SET ARITHABORT ON
USE Northwind
GO
ALTER TABLE Products
ADD cs_Pname AS checksum(ProductName)
CREATE INDEX Pname_index ON Products (cs_Pname)

The checksum index can be used as a hash index, particularly to improve indexing speed when the column to be indexed is a long character column. The checksum index can be used for equality searches.

/*Use the index in a SELECT query. Add a second search
condition to catch stray cases where checksums match,
but the values are not identical.*/
SELECT *
FROM Products
WHERE checksum(N'Vegie-spread') = cs_Pname
AND ProductName = N'Vegie-spread'

Creating the index on the computed column materializes the checksum column, and any changes to the ProductName value will be propagated to the checksum column. Alternatively, an index could be built directly on the column indexed. However, if the key values are long, a regular index is not likely to perform as well as a checksum index.

LIVE EXAMPLE:

SELECT TBL1.* FROM TABLE1 TBL1
INNER JOIN TABLE2 TBL2 ON TBL1.COLUMN_NAME = TBL2.COLUMN_NAME
WHERE CHECKSUM(TBL1.COLUMN1,TBL1.COLUMN2) NOT IN (SELECT CHECKSUM(COLUMN1,COLUMN2) FROM ANOTHERTABLE)

Friday, July 23, 2010

What is Microsoft Dynamics CRM External Connector License?

The External Connector License is only necessary when external users access
data. The term “external users” means that users are not:
• The organization's employees
• The organization's contractors or agents
• Employees of a company affiliated to the organization
• Contractors or agents of a company affiliated with the organization
For example, an organization cannot set up an external connector license for
users in a call center environment.

Example A - License required
An organization must have an External Connector License if it wants to create a
web site where the organization's customers can view and maintain their contact
information that is stored in Microsoft Dynamics CRM.

Example B - License not required
An External Connector License is not required if an organization wants to create
a web site that only displays a form that allows the public to enter information
that will be saved in Microsoft Dynamics CRM. The key difference is that in
Example A, the external users have access to Microsoft Dynamics CRM data. In
Example B, external users will enter data that is saved in Microsoft Dynamics
CRM, but they do not have access to Microsoft Dynamics CRM data.

Creating Additional Organizations

When Microsoft Dynamics CRM is installed, the Microsoft CRM Server Setup
wizard prompts the Administrator for the default organization information. The
wizard, in turn, creates the organization record and adds it into the configuration
database.
Following installation of the Microsoft Dynamics CRM Enterprise Edition, any
additional organizations must be added by the CRM Administrator through a new
Organizations tool in Deployment Manager.

Perform the following steps to create a new organization using the Deployment
Manager's Organizations tool:

1. On your desktop, click the Start menu, click All Programs, click
the Microsoft Dynamics CRM program group, then click
Deployment Manager.
2. Click on the Organizations folder to view the existing
organizations.
3. To add a new organization, either right click on the Organizations
folder and select New Organization, or click Action on the menu bar
and select New Organization.
4. In the New Organization Wizard, on the Specify the Organization
Name window, enter the Organization name. The name cannot
include blank spaces or any unsupported characters.
5. When you tab out of the Organization name field, the same name is
prefilled in the Friendly name field. Change this value if required.
Note: You can add blank spaces back in to the Friendly name if
necessary. For example, if adding an organization record for
Northwind Traders, the organization name might be
“NorthwindTraders”, but the Friendly name could be “Northwind
Traders”.
6. The ISO currency code field specifies the base currency for the new
organization. Click the Browse button and select the new
organization's base currency. Click OK.
7. The Currency name and Currency symbol are prefilled based on the
selected base currency. Click Next.
8. On the Help Us Improve the Customer Experience window, select
whether this organization is willing to participate in the Customer
Experience Improvement program. Click Next.
9. On the Select SQL Server window, select from the drop down list the
Microsoft SQL Server that contains the CRM database. Click Next.
10. On the Specify Reporting Services Server window, the report server
URL is prefilled for you. Change this value if necessary. Click Next.
11. On the System Requirements window, review the results of the
verification tasks. If any errors occur, click Details for more
information. If necessary, click Back to correct any previously
entered information. If no errors occurred, click Next.
12. On the Ready to Create window, verify the organization information.
If anything requires change, click Back to correct the information. If
all the information is correct, click Create.
13. Click Finish once the New Organization is successfully created.
14. The new organization will appear in the Organizations folder.

Microsoft Dynamics CRM uses Active Directory for storing information
regarding:
• Users
• Client computers
• The Organizational Unit
• Security groups

How to delete organizations in CRM?

As per many peoples, Once organization created in CRM it will be disabled but never deleted.
It's wrong,If required to delete existing organizations then read the following paragraph.

When an administrator creates a new organization in the Enterprise Edition of
Microsoft Dynamics CRM, the organization information is stored in the
configuration database. Similarly, the administrator can remove an existing
organization from the configuration database, although the organization must be
disabled first before it can be deleted. And if there are no more organizations left
in the configuration database, the administrator can uninstall Microsoft Dynamics
CRM from the server(s).

Update page size in CRM 4.0

As defined in CRM you can increase your page size maximum of 250 records, but if you need to resize it for 1000-2000 records then you are unable to do it, you can do it in unsupported way after using the following code.

update usersettings set PagingLimit=1900 where ModifiedByName='user name'

Refresh your CRM panel, if not reflecting then reset application Pool in IIS.

Friday, July 16, 2010

What is CredentialCache Class in CRM SDK

The CredentialCache class stores credentials for multiple Internet resources. Applications that need to access multiple resources can store the credentials for those resources in a CredentialCache instance that then provides the proper set of credentials to the Internet resource when required. When the GetCredential method is called, it compares the Uniform Resource Identifier (URI) and authentication type provided with those stored in the cache and returns the first set of credentials that match.

The DefaultCredentials property contains the system credentials of the current security context. For client applications, these represent the user name, password, and domain of the user who is currently logged in. For ASP.NET applications, the default credentials are the user credentials of the logged-in user or the user being impersonated.

How to cancel Save Operation in MS CRM4.0

Pass this line of code to prevent saving the current items in CRM.
// Cancel the save operation.
event.returnValue = false;

Read-Only fields Values don’t get saved in the database.

After changing the value of a read-only field with JavaScript the new value will not be saved into the database.

To save the newvalue set the ForceSubmit property of the field to true.

crmForm.all.new_customfield.ForceSubmit = true;

Attach an Event for a Lookup in JavaScript MS CRM 4.0

Some time we required to call a JavaScript function after selection the Lookup value for this use the below line of code to attach event.

crmForm.all.objectid.attachEvent("onafterselect", javaScriptFunctionName);

Thursday, July 15, 2010

Attaching to Processes

Now that you have the plug-in registered, you are ready to start debugging. You need to attach to W3WP.exe(for synchronous services) to attach to plug-ins since they run within IIS. To attach to workflows you need to attach to the CRM async service which is Crmasyncservice.exe(for asynchronous services).

Hiding System defined Views in CRM 4.0

Some time user required to hide some system defined views from any entity in CRM 4.0,
to do this we need to create a plug-in.

For Example: hare you can hide "All My Leads" and "My Closed Leads" view's from my lead entity.

Use the following code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Metadata;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;

namespace HideViewsPlugin
{
public class HideViews : IPlugin
{
public void Execute(IPluginExecutionContext context)
{
// Query the SavedQueryBase table to retrieve the Query Id for an attribute savedqueryid
Guid[] Views = new Guid[] {
new Guid("5F001E93-3C6D-DE11-991A-0019B9F5ED8F"), //All My Leads
new Guid("36AA1011-4F6C-DE11-991A-0019B9F5ED8F"), //My Closed Leads
};

if (context.InputParameters != null && Views.Length > 0)
{
if (context.InputParameters.Properties.Contains(ParameterName.Query))
{
QueryExpression qe = (QueryExpression)context.InputParameters.Properties[ParameterName.Query];

//only apply this action if the query is for 'views' or saved queries
if (qe.EntityName == "savedquery")
{
if (qe.Criteria != null)
{
if (qe.Criteria.Conditions != null)
{
//Append more condition logic to the default query that's used by CRM. In this case, I filtered on the savedqueryid to exclude the views from the Ids identified above.
//This conditional expression hide only two defined Views
ConditionExpression queryCondition = new ConditionExpression("savedqueryid", ConditionOperator.NotIn, Views);


OR

//If you required to hide all the Views starting from a specific string then use the below defined ConditionExpression

/*The query is edited to look at views not starting with "Hidden" at the begining of the View Name*/

//ConditionExpression queryCondition = new ConditionExpression("name", ConditionOperator.NotLike, "Hidden%");


qe.Criteria.Conditions.Add(queryCondition);
context.InputParameters.Properties[ParameterName.Query] = qe;
}
}
}
}
}
}
}
}

Now register this plug-in and register one more Step for this plug-in,Parametters those required for step are given below:

Meggage: RetrieveMultiple
Primary Entity: savequery
Eventing Pipline: Pre Stage
Execution Mode: Synchronous
Step Deployment: Server
Triggering Pipeline: Parent Pipeline

Wednesday, July 14, 2010

Create a task through JavaScript after using Web Service in MS CRM 4.0

Some times we required to create a task for a user through JavaScript, you can do this by the following code

Here you can pass your Description ,Owner, Regarding,subject and created By parametters.

function CreateTask(MangerID,CreatedByID)
{
var CurrentQuoteID = crmForm.all.quotenumber.DataValue;
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <Create xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <entity xsi:type=\"task\">" +
" <description>Your Message "+ CurrentQuoteID + "</description>" +
" <ownerid>" + MangerID + "</ownerid>" +
" <regardingobjectid type=\"quote\">" + crmForm.ObjectId + "</regardingobjectid>" +
" <subject>Your Subject "+ CurrentQuoteID + "</subject>" +
" <createdby>" + CreatedByID + "</createdby>" +
" </entity>" +
" </Create>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Create");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;
}

How can we use LookUpControl in my Custom page in CRM 4.0

I'm trying to replicate the functionality of this CRM 4.0 in my custom aspx page

<nobr>
<asp:TextBox ID="lookupresult" runat="server"></asp:TextBox>
<img src="/_imgs/btn_off_lookup.gif" onclick="ShowOwnerLookupDialog()" />

<script language="javascript">
function ShowOwnerLookupDialog()
{
var lookupItems = showModalDialog( '/_controls/lookup/lookupsingle.aspx?class=BasicOwner&objecttypes=8,2020&browse=0&ShowNewButton=1&ShowPropButton=1&DefaultType=0' , null, '' );
document.all.lookupresult.value = lookupItems.items[0].id;
}
</script>
</nobr>

Update Filtered lookup data in CRM 4.0

For this We have to pass fetch xml string using one of the parameters "search" recognised by the server otherwise exception is thrown (there is a way to disable parameters check through the registry setting
DisableParameterFilter, but it's easier without yet another undocumented setting).
Since we want to disable search functionality it makes sense to re-use search parameter.

Use the following code:

This line of code using for single entity
//The attribute where lookup is attached
var field = crmForm.all.pricelevelid;

// Ensure that search box is not visible in a lookup dialog
field.lookupbrowse = 1;
// Pass fetch xml through search value parameter
field.AddParam("search",
"<fetch mapping='logical'><entity name='pricelevel'>"
+ "<filter><condition attribute='name' operator='eq' value='pricelist name' /></filter></entity></fetch>");


This line of code using for multiple entity
//Lookup will show all the Child users of current loggedIn user

//Return all child users
var targetUserUnits = GetChildusers() //for eg: <value>"+Value1+"</value><value>"+Value2+"</value>
//The attribute where lookup is attached
var field = crmForm.all.new_userid;
//Ensure that search box is not visible in a lookup dialog
field.lookupbrowse = 1;

field.AddParam("search",
"<fetch mapping='logical'><entity name='systemuser'>"
+"<all-attributes/>"
+"<link-entity name='new_nesteduser' from='new_userid' to='systemuserid'>"
+"<filter type='and'><condition attribute='new_lft' operator='between'>"
+targetUserUnits
+"</condition></filter></link-entity></entity></fetch>");

Unsupported
You can manage it from lookup form means if this parameter contains any value then apply this filter otherwise use as origional.
to do this open the page "C:\Program Files\Microsoft Dynamics CRM\CRMWeb\_controls\lookup\lookupsingle.aspx " and change it accordingly as required.

For Eg.

void crmgrid_PreRender( object sender , EventArgs e )
{
// As we don't want to break any other lookups, ensure that we use workaround only if
// search parameter set to fetch xml.
<strong>if (crmGrid.Parameters["search"] != null && crmGrid.Parameters["search"].StartsWith("<fetch"))
{
crmGrid.Parameters.Add("fetchxml", crmGrid.Parameters["search"]);
// searchvalue needs to be removed as it's typically set to a wildcard '*'
crmGrid.Parameters.Remove("searchvalue");
// Icing on a cake - ensure that user cannot create new contact outside of the account
// and then select it.
this._showNewButton = false;
} </strong>
}

Expose the toggling function at the window level in CRM 4.0

After create a function in page load event of any entity in CRM and tried to call it from onSave or any attribute OnChange event
then you don't required to type the same function again and again just toggle this function at the bottom of pageLoad
event, to do this use the following code

//Expose the toggling function at the window level
this.functionName = functionName;

Monday, July 12, 2010

Determine Space Available/Used for Entities

Determine Space Available for your Entity

If you decide to add a custom attribute to an entity, you can determine if there is
space available for the attribute in the entity's extension table by running this
Transact-SQL query on the _CRM database.Use this following query:

select EntityName=e.name,Bytes_Remaining=8060-(Sum(a.length))
from entity e join attribute a on e.entityid=a.entityid
where a.iscustomerfield=1 and a.islogical=0
group by e.Name


Determine Space Used for your Entity

Alternatively, you can determine the number of bytes already used by custom
attributes for an entity by running this Transact-SQL query on the
_CRM database.Use this following query:

select EntityName=e.Name,Physical_size=Sum(a.length)
from entity e join attribute a on e.entityid=a.entityid
where a.iscustomerfield=1 and a.islogical=0
group by e.Name

Friday, July 9, 2010

Increase the Tab limit in MSCRM 4.0

By default the max number of tabs allowed in CRM Form is 8.

The max tab limit is defined in JavaScript of formeditor.aspx. This page can be found at the following location “\Microsoft Dynamics CRM\CRMWeb\Tools\FormEditor”.
You can change the count specified in the _iMaxTabs to increase the count.

Wednesday, July 7, 2010

Create and Sending Email in CRM 4.0

Use the following code to send an email to multiple customers in CRM4.0

SendMailToMembers(ICrmService crmService, ArrayList members, String msgBody, Guid ownerID, Guid userID,string subject)
{

// create an email
email emailCreate = new email();
emailCreate.subject = subject;
emailCreate.description = msgBody;

//specify the owner for the mail
emailCreate.ownerid = new Owner();
emailCreate.ownerid.type = EntityName.systemuser.ToString();
emailCreate.ownerid.Value = ownerID;

//create an activityparty array holding all the guids specified in the members array list
activityparty[] ap = new activityparty[members.Count];
// creating as many activity party as the no of users or members in a team
int i = 0;
foreach (String memberID in members)
{
ap[i] = new activityparty();
ap[i].partyid = new Lookup();
ap[i].partyid.type = EntityName.contact.ToString();
ap[i].partyid.Value = new Guid(memberID);
i++;
}

// specify to part of the email
emailCreate.to = ap;

// specify the from part of the email
activityparty from = new activityparty();
from.partyid = new Lookup();
from.partyid.type = EntityName.systemuser.ToString();
from.partyid.Value = userID;
emailCreate.from = new activityparty[] { from };

// finally create the email and get the guid of the email
Guid emailId = crmService.Create(emailCreate);

// Create an SendEmailRequest object
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailId;
req.TrackingToken = string.Empty;
req.IssueSend = true;

// Finally Send the email message.
SendEmailResponse res = (SendEmailResponse)crmService.Execute(req);
}

Updating custom entities icons (Upload a new image for a Custom Entity in CRM)

For all our projects, we are always customizing Microsoft Dynamics CRM 4.0. To achieve that, we create many custom entities and one of the worst aspect of that heavy customization is to have a lot of custom entities with the same icon. So, it is difficult to identify them just with their icon.

In order to customize further the application, it is a good thing to add different icon to each custom entity.

The standard approach

This approach consists of using the standard feature of Microsoft Dynamics CRM 4.0 to update custom entites icons. In the customization view, just click on the menu “More actions” and click on “Update icons…”.

You then need to provide a file for each required icons:

*
icon in web application (16x16 / gif / less that 10kb)
*
Shortcut icon in Outlook (32x32 / ico / less than 10kb)
*
Icon in entity form (66x48 / gif / less than 10kb)

For more Details Click Here

Tuesday, July 6, 2010

Plug-ins vs. Workflows in MS CRM 4.0

First of all, remember than both workflows and plug-ins can attach to exactly the same events. Well, plug-ins have available a couple of more events but essentially both work on top of the same event model.Remember also that workflows always run asynchronous and hence, the Asynchronous Processing Service must be running on the server in order to run.

Workflows are more suitable if:

1)you want to achieve simple tasks faster, such as sending an e-mail or creating / updating assigning records. These actions can be set up very quickly with a workflow without any need of writing code.

2)you want to easily scale things to managers (if they were setup for user records), as it is possible to assign records to them.

you want to allow an advanced user to make changes to logic. As using the integrated workflow designer is user-friendly, an advanced user would be able to edit an existing workflow and change some rules according to business changes.

3)the logic should be available to be run on demand. I mean, when you are within an entity and navigates to “workflows” option in the left pane, all workflows marked as available to run on demand can be executed making them independent of an event trigger.

4)you want to send emails making use of templates and attaching files.

Workflows also allow running child workflows which may make a lot of sense in some scenarios. Nevertheless, be careful if you need the child workflow results in order to make decisions on your main workflow, as child workflows always run asynchronous, which means that it will trigger the child workflow and continue. If you need your primary workflow to wait until child ends, you will need to write a custom activity.

On the other hand, plug-ins are more suitable if:

1)you need to manipulate data before is saved.

2)you need to make validations before submitting the operation.

3)you want to be able to cancel an operation based on your validations.

4)immediate response to the user is needed.

5)you need retrieve values and/or take actions after operation has been completed (i.e. getting and autogenerated id)

It is important to note that since Dynamics CRM 4, plug-ins can also be configured to run asynchronous (Mode attribute while registering plug-in). Nevertheless, pre-event asynchronous plug-ins are not supported. In this case, you will have to set it up as synchronous mode.

Another important thing about plug-ins is the Deployment option which says if the plug-in is going to be executed on the server and/or Outlook client. If both executions are set up and client goes offline and online, plug-in calls are triggered after synchronization so be prepared in this case to execute your code twice!

Regarding to security:

1)Workflows triggered automatically will run under the security context of the workflow owner. On the contrary, if executed on demand, the security context of the user who executed the workflow will be used.

2)Plug-ins execute under the security context of the CRM Web application pool identity (typically NETWORK SERVICE). As this account typically maps to generic CRM SYSTEM user this typically works fine.

However, within plug-ins you can make use of impersonation to work under the credentials of the user who is making the request. For doing so, you just need to pass True to the CreatCrmService method under the context object.If you need to always impersonate with a specific user, you can do that by passing True as above and setting impersonatinguserid attribute while registering the plug-in.It is important to know that plug-in impersonation does not work offline. The logged on user credentials are always used in this case.

referred from Here

How to get currently authenticated user in MSCRM SQL queries?

During developing SQL queries for MSCRM, it’s often required to fetch the currently authenticated user.
SUSER_SNAME() is a special function in SQL that returns the currently authenticated user. If your code doesn’t authenticate to SQL Server by using Windows authentication, your queries will never return any data, because all of the filtered views perform an inner join using systemuserid. Here is the query to fetch currently authenticated user in SQL server.

select SystemUserId, FullName from SystemUserBase
where SystemUserBase.DomainName = SUSER_SNAME()

above code referred from http://ayazahmad.wordpress.com/page/5/

Get Current User Roles through JavaScript in CRM

If you need to find businessunitid and name from role entity of current logged in user in JavaScript then for this you need to access WebService of CRM through JavaScript and privide logged in user id through system variable "EqualUserId".

In the below code you can access role entity attribute after liked other two entities with name "systemuserroles" and "systemuser" with "role" entity.

var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>role</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>businessunitid</q1:Attribute>" +
" <q1:Attribute>name</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>roleid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>role</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>systemuserroles</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>roleid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>systemuserid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>systemuserroles</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>systemuser</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>systemuserid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkCriteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>systemuserid</q1:AttributeName>" +
" <q1:Operator>EqualUserId</q1:Operator>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:LinkCriteria>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </query>" +
" </RetrieveMultiple>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction"," http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;

if (resultXml != null)
{
var entityNode = resultXml.selectSingleNode("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");
var RoleName = entityNode.selectSingleNode("q1:name").text;
var BUentityNode = resultXml.selectSingleNode("//RetrieveMultipleResult/BusinessEntities/BusinessEntity/q1:businessunitid");
var BUName = BUentityNode.getAttribute("name");
}

Get Regarding Activity Status from activitypointer Entity

Here you can find activityid and statecode from activitypointer entity through WebService in JavaScript after passing one parameter "crmForm.ObjectId", parameter return current entitt GUID.

var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>activitypointer</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>activityid</q1:Attribute>" +
" <q1:Attribute>statecode</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:Criteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>activitytypecodename</q1:AttributeName>" +
" <q1:Operator>Equal</q1:Operator>" +
" <q1:Values>" +
" <q1:Value xsi:type=\"xsd:string\">Task</q1:Value>" +
" </q1:Values>" +
" </q1:Condition>" +
" <q1:Condition>" +
" <q1:AttributeName>regardingobjectid</q1:AttributeName>" +
" <q1:Operator>Equal</q1:Operator>" +
" <q1:Values>" +
" <q1:Value xsi:type=\"xsd:string\">"+crmForm.ObjectId+"</q1:Value>" +
" </q1:Values>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:Criteria>" +
" </query>" +
" </RetrieveMultiple>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var objResult = xmlHttpRequest.responseXML;

var buNodes = objResult.selectNodes("//BusinessEntity/q1:statecode"); // CRM 4.0

if(buNodes != null )
{
/*get values*/
for( i = 0; i < buNodes.length; i++)
{
switch(buNodes[i].text)
{
//Put your logic here
}
}
}

Include Javascript files in CRM (load custom javascript file)

Some time user required to do same type of work at multiple place in JavaScript, for this user have two options either place a same type of code at all the places or store the same code at one place in JavaScript file and name it with "xyz.js", now the question is how to use this JS file in different entities from CRM.

Some steps are there:
1) create one folder with name "myscripts" in ISV in CRM server.
2) place the "xyz.js" file in above named folder.
3) use the following JavaScript code at the OnLoad event of the entity.

var script = document.createElement('script');
script.language = 'javascript';
script.src = '/ISV/myscripts/xyz.js';
document.getElementsByTagName('head')[0].appendChild(script);

var f = function()
{
if (event.srcElement.readyState == "loaded")
{
//perform onload scripts
FunctionfromJavaScriptFile();
// some function from your custom js file
}
}
script.attachEvent("onreadystatechange", f);

After using above three defined steps you are ready to call custom JavaScript file.

Disable Menu Buttons from any entity in CRM

Some time user is not interested to show some buttons from menu items, for this user required to hide these buttons. You can do this if you have ID of that button, but in CRM the ID of these buttons not standard these are created at the time of loading, but some part of the ID is unique every time, so find this unique id name from source control of entity.After this use following JavaScript to Hide these buttons.

function DisableButtons()
{
//Get all of the List Elements
var lis = document.getElementsByTagName('LI');
var i = 0;
//Loop through the list items
while (i < lis.length)
{
if (lis[i].getAttribute('id').indexOf( 'provide unique id name')!=-1)
{
var lnkmenuApproveDiscount = lis[i].getAttribute('id');
var menuApproveDiscountButton = document.getElementById(lnkmenuApproveDiscount);
menuApproveDiscountButton.style.display='none';
}
if (lis[i].getAttribute('id').indexOf( 'provide unique id name')!=-1)
{
var lnkmenuRejectDiscount = lis[i].getAttribute('id');
var menuRejectDiscountButton = document.getElementById(lnkmenuRejectDiscount);
menuRejectDiscountButton.style.display='none';
}
i = i + 1;
}
}

Hide associated view buttons(Buttons those are showing in related entity)

Some time user not required some buttons to be shown in associated (related entity view) grid menu.To hide associated(related entity view) buttons we are required to Add JavaScript on the form OnLoad event of entity, in which this assicated view is shown.

For example:- I have add entity with name Audit in CRM and associate it with Account, Now I tried to hide Audit assiciated button's Add New and Add Existing Item from Audit entity, but I saw ID's of these buttons not exist in Account entity source becuase associated entity open in Iframe, so for this we requried to add following JavaScript on Account form load event.

function HideAssociatedViewButtons(loadAreaId, buttonTitles) {
var navElement = document.getElementById('nav_' + loadAreaId);
if (navElement != null) {
navElement.onclick = function LoadAreaOverride() {
// Call the original CRM method to launch the navigation link and create area iFrame
loadArea(loadAreaId);
HideViewButtons(document.getElementById(loadAreaId + 'Frame'), buttonTitles);
}
}
}

function HideViewButtons(Iframe, buttonTitles) {
if (Iframe != null) {
Iframe.onreadystatechange = function HideTitledButtons() {
if (Iframe.readyState == 'complete') {
var iFrame = frames[window.event.srcElement.id]; var liElements = iFrame.document.getElementsByTagName('li'); for (var j = 0; j < buttonTitles.length; j++) {
for (var i = 0; i < liElements.length; i++) {
if (liElements[i].getAttribute('title') == buttonTitles[j]) {
liElements[i].style.display = 'none';
break;
}
}
}
}
}
}
}

HideAssociatedViewButtons function requires loadAreaId, buttonTitles as a parameters.
We can find this loadAreaID, by viewing source code of Account form. and buttonTitles means ToolTip of that button.

for Example:- HideAssociatedViewButtons('new_lead_custom_audit', ['Add existing Audit to this record', 'Add a new Audit to this record']);

Content refereed from http://mahadeomatre.blogspot.com/2009/07/hide-associated-view-buttons.html

Split the String values with a special character in MS Flow to convert this into Array

 Many times we have a requirement to prepare the Mailing address for some of the documents, suppose there are Address Line1, Address Line2, ...