2009-08-13

Remove 'Add Existing...' button from associated view entities form

I was found this code at Dave Hawes blog — http://blog.davehawes.com/post/2008/04/23/MSCRM-4-Remove-Add-Existing-xxxxx-button.aspx
This code should be added to onLoad event for the form of the entity where you want to hide buttons for the associated views of other entities.


HideAssociatedViewButtons('new_account_new_accountclassificate', ['Добавить к этой записи существующий объект Классификация организации']);

function HideAssociatedViewButtons(loadAreaId, buttonTitles){
var navElement = document.getElementById('nav_' + loadAreaId);
if (navElement != null) {
navElement.onclick = function LoadAreaOverride() {
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;
}
}
}
}
}
}
}

Publishing it here for memory.

2009-08-12

How to get a PhoneCallId


SELECT
ActivityPartyBase.PartyId AS ContactId,
ActivityPartyBase.ActivityId AS PhoneCallId
FROM

CampaignActivityBase
INNER JOIN ActivityPointerBase

ON (ActivityPointerBase.RegardingObjectId = CampaignActivityBase.ActivityId)AND (ActivityPointerBase.DeletionStateCode = 0)

INNER JOIN PhoneCall

ON ((PhoneCall.ActivityId = ActivityPointerBase.ActivityId) AND (ActivityPointerBase.StateCode = 0) AND (PhoneCall.DeletionStateCode = 0))

INNER JOIN ActivityPartyBase

ON ((PhoneCall.ActivityId = ActivityPartyBase.ActivityId) AND (PartyObjectTypeCode = 2))

INNER JOIN ContactBase

ON (ContactBase.ContactId = ActivityPartyBase.PartyId) AND (ContactBase.DeletionStateCode = 0)


WHERE
(CampaignActivityBase.ActivityId = @CampaignActivityId)

2009-07-20

How to write into the eventlog custom journal with impersonalization in code


private const string LOG_NAME = "MSCRM.Common";

///
/// Write message in log
///

public static void WriteLog(string message, Exception exception)
{
System.Security.Principal.WindowsImpersonationContext ctx = null;
ctx = System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero);
try
{
string logSource = "MSCRM.Common.Web.Controls.Grid";

if (EventLog.SourceExists(logSource))
{
if (!EventLog.LogNameFromSourceName(logSource, ".").Equals(LOG_NAME))
{
EventLog.DeleteEventSource(logSource, ".");
EventLog.CreateEventSource(logSource, LOG_NAME);
}
}
else
{
EventLog.CreateEventSource(logSource, LOG_NAME);
}
EventLog el = new EventLog();
el.Log = LOG_NAME;
el.Source = logSource;
el.WriteEntry(String.Format("{0}\nDetails:\n{1}", message, GetLogInfo(exception)), EventLogEntryType.Error);
}
catch (Exception ex)
{
throw ex;
}
finally
{
ctx.Undo();
}
}

Get selected item in CRM grid

The following snippet will allow you to retrieve an array containing the Id values of the selected records in the grid:

// get array of selected records
var a = document.all['crmGrid'].InnerGrid.SelectedRecords;
var selectedItems = new Array(a.length);
for (var i=0; i < a.length; i++)
{
selectedItems[i] = a[i][0];
}
alert(selectedItems);

To get all of the records in the grid (ie. “All Records on Current Page”):

// array of all records on current page
var iTotal = document.all['crmGrid'].InnerGrid.NumberOfRecords;
var o = document.all['crmGrid'].InnerGrid;
var allItems = new Array;
var ii = 0;
for (var i=0; i < iTotal; i++)
{
allItems[ii] = o.rows[i].oid;
ii++;
}
alert(allItems);

The source: http://blog.customereffective.com/blog/2009/02/javascript-snippets-for-working-with-grids-in-crm.html

2009-07-16

How to programmatically launch an application under a specific user


ProcessStartInfo psi = new ProcessStartInfo("cmd", @"/C c:\SomeApp.exe");
psi.UserName = "UserName";
psi.Domain = "DomaiName";
psi.Password = ReadPassword("password");
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
using (Process p = Process.Start(psi))
{
// if you need to wait the end of the process
p.WaitForExit();
}

public System.Security.SecureString ReadPassword(string password)
{
System.Security.SecureString secPass = new System.Security.SecureString();
for (int i = 0; i < password.Length; i++)
secPass.AppendChar(password[i]);
return secPass;
}

2009-07-10

MSCRM, SQL and Localization

If you need to look at localized name of some attribute thru the SQL then check out next code


select l.*
from MetadataSchema.LocalizedLabel l
join MetadataSchema.Attribute a on l.objectid=a.AttributeId
join MetadataSchema.Entity e on a.EntityId=e.EntityId
where a.name= 'address1_city' and e.name='account'

2009-06-26

Campaign Activity status = Pending

If campaignactivity status is "pending" all the time, when you are distributing the activities, then check out the Microsoft CRM Asynchronous Processing Service was started on the server.

Convert HTML to plain text and remove tags


// convert HTML to plain text
string Description = System.Web.HttpUtility.HtmlDecode(HTML_encoded_string);

Description = StripTags(Description);

...

// remove tags from HTML-parsed string
private string StripTags(string HTML)
{
System.Text.RegularExpressions.Regex objRegEx = new System.Text.RegularExpressions.Regex("<[^>]*>");

return objRegEx.Replace(HTML, "");
}

2009-06-09

TargetUpdate VS Update method

If you have a question what is better for use: UpdateRequest with TargetUpdate or Update method, then first of all you must to look at MS CRM SDK "CrmService Common Methods" article.

There was said:
"The CrmService Web service provides a set of methods used to perform the most common operations on system and custom entities. These operations can also be performed by using the Execute method and the corresponding message. However, the methods will perform faster so they should be used whenever possible."

So service.Update is a winner.

2009-06-04

CrmDateTime conversion to DateTime


Convert.ToDateTime(crmdatetime.Value)
DateTime.Parse(crmdatetime.Value)


For more information on the CrmDateTime, look in the SDK:
http://msdn2.microsoft.com/en-us/library/aa613542.aspx

Open any entity for edit

The universal URL to open any entity for edit is

http://server name/company name/CRMReports/viewer/drillopen.aspx?ID=objectguid&OTC=object type code

Object type code you can find at Microsoft Dynamics CRM SDK Entity Type Codes article.

Also like that:
http://server name/company name/CRMReports/viewer/drillopen.aspx?ID=objectguid&LogicalName=entity name (contact, account, e.t.c.)

2009-05-29

Error: "Unable to connect to the remote server"

To resolve this error you can edit registry at MS CRM Server - look through the article (PartnerSource) at Microsoft Dynamics: KB913515

Also here is another way, to use the unsafe connection sharing.
Article at blogs.msdn.com: "Best Practices for Better Performance from Your Custom Code"

2009-05-12

MS CRM database fragmentation

If your CRM is very slow, then check the indexes fragmentation.
And if received table was not empty then you must rebuild the indexes.


USE AdventureBase
GO
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(N'AdventureBase'), NULL,NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id
where avg_fragmentation_in_percent>30
GO

2009-05-08

Replace non-digit symbols with RegEx

If you need to restrict input in nvarchar field(only the digit symbols for example), you may write some code to OnSave() event.
This code is replace all of non-digit symbols in new_telephonenumber field to nothing, i.e. "".


//before: new_telephonenumber = "555-555$#5"
//after: new_telephonenumber = "5555555"

var re = /\D/g;
if(document.crmForm.all.new_telephonenumber.DataValue != null){
crmForm.all.new_telephonenumber.DataValue = crmForm.all.new_telephonenumber.DataValue.replace(re,"");
}

2009-05-06

The Microsoft Dynamics CRM Developer Toolkit

Microsoft Dynamics CRM 4.0 toolkit for Visual Studio 2008. Download link

2009-05-05

Test before save

I don't want to write a server code if I can do the same at the client side.
Here is the test for INN field, that must contain only the numbers.

var re = new RegExp("[^0-9]");
if(crmForm.all.new_inn.DataValue != null){
if(re.test(crmForm.all.new_inn.DataValue == true){
alert("ИНН должен содержать только цифры");
event.returnValue = false;
return false;
}
}

2009-05-04

Error: 0x80042f09 SecLib::CheckPrivilege failed. Returned hr = -2147209463

If you get an exception like next one:

0x80042f09
SecLib::CheckPrivilege failed. Returned hr = -2147209463, User: 529cc8c0-23b6-dd11-a373-001cc458db68


You should check the user roles, because the error code 0x80042f09 means "The user has not been granted any licenses or the user has not been assigned any roles."
The user can have the role that can have no rights to the entity or to the entities witch have the owner-member relationship with base entity.
For example:
We have two entities organization -> opportunity and one role "salesperson" with rights on the organization and no rights to the opportunity. If you set the user with just "salesperson" role to the Owner of some organization, you will get the error 0x80042f09.

Same is fair to all errors "SecLib::CrmCheckPrivilege failed."

2009-04-26

DateTime in MSCRM

How to format string to write in CrmDateTime attribute:


string startdate; // - can be a parameter in method

opportunity oop = new opportunity();

opp.new_startdate = new CrmDateTime();

if(startdate!="")
opp.new_startdate.Value = (Convert.ToDateTime(startdate)).ToString("yyyy-MM-ddTHH:mm:ss");
else
opp.new_startdate.Value = DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ss");

2009-04-10

Null Values - based on MS CRM SDK

From Microsoft CRM SDK :

When you update an entity instance there is a mechanism you can use to differentiate the absence of a value from a null value. To set an attribute value to null you must set both IsNull and IsNullSpecified to true. For attributes of type String, you must assign the value to String.Empty. This same mechanism is used when you create a query to find a null value.

Another option is to use the type helper code available in Microsoft.Crm.Sdk assembly and in the CRMHelpers classes.

Example
The following code example shows you how to create null instances of the various Microsoft Dynamics CRM attribute types.

CrmBoolean boolean = new CrmBoolean();
boolean.IsNull = true;
boolean.IsNullSpecified = true;

CrmDecimal dec = new CrmDecimal();
dec.IsNull = true;
dec.IsNullSpecified = true;

CrmFloat f = new CrmFloat();
f.IsNull = true;
f.IsNullSpecified = true;

CrmMoney money = new CrmMoney();
money.IsNull = true;
money.IsNullSpecified = true;

CrmNumber number = new CrmNumber();
number.IsNull = true;
number.IsNullSpecified = true;

Lookup lookup = new Lookup();
lookup.IsNull = true;
lookup.IsNullSpecified = true;

PickList list = new PickList();
list.IsNull = true;
list.IsNullSpecified = true;

Status status = new Status();
status.IsNull = true;
status.IsNullSpecified = true;

Owner owner = new Owner();
owner.IsNull = true;
owner.IsNullSpecified = true;


Example
The following code example shows you how to create null instances of the various Microsoft Dynamics CRM attribute types using the type helper classes.

CrmBoolean boolean = CrmBoolean.Null;

CrmDecimal dec = CrmDecimal.Null;

CrmFloat flt = CrmFloat.Null;

CrmMoney money = CrmMoney.Null;

CrmNumber number = CrmNumber.Null;

Lookup lookup = Lookup.Null;

Picklist list = Picklist.Null;

Status status = Status.Null;

Owner owner = Owner.Null;


My Example
Moving the data from one field to another and cleaning the first field after that.

opportunity opp = new opportunity();
opp.opportunityid = new Key();
opp.opportunityid.Value = findedopp.opportunityid.Value;

opp.new_profittreshold = new CrmMoney();
opp.new_profittreshold.Value = (decimal)findedopp.new_investmenttreshold.Value;

opp.new_investmenttreshold = new CrmFloat();
opp.new_investmenttreshold.IsNull = true;
opp.new_investmenttreshold.IsNullSpecified = true;

service.Update(opp);

2009-04-08

JavaScript свойства объекта

Посмотреть свойства объекта - можно использовать конструкцию

for(key in obj){alert(key)}