2009-10-05

Mask the phone fields

I was need some mask on the "mobilephone" field in contact card. So I was combine some google search result with my experience and got next code:
//base maskphone function 
window.applyMask = function()
{
    // var of fields wich must be masked
    var ele = document.getElementById("mobilephone");

var FormatPhoneHandler=function()
    {
      var PH = this.value;
      var re = /\D/g;
      // +7 - this is country code of Russia, so this is decision only for one country
      PH = PH.replace("+7","");
      PH = PH.replace(re,"");
     
      if(PH.length <1)
      {
          this.value = "";
      }
      else if(PH.length <= 3)
      {
            this.value = "+7 (" + PH;
      }
      else if(PH.length > 3 && PH.length <= 6)
      {
            this.value = "+7 (" + PH.substring(0,3) + ") " + PH.substring(3,6);
      }
      else if(PH.length > 6)
      {
            this.value = "+7 (" + PH.substring(0,3) + ") " + PH.substring(3,6) + "-" + PH.substring(6,10);
      }
    }

    ele.onkeyup = FormatPhoneHandler;
}

// turn it on
applyMask();

Place this code in onLoad event in the entity wich you need and don't forget change names of the field for the right one.

2009-08-20

Embeded notification

We were needed some kind of notify message for user without any pop-up or an alerts.


function CreateRequestObject() {
if (window.XMLHttpRequest) {
try {
return new XMLHttpRequest();
} catch (e) { }
} else if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) { }
}
}
return null;
}

function RetrieveEntity(sEntityName, GUID, sAttributeNames) {
var attributes = "";
if (sAttributeNames.length == 0)
return null;
for (var i = 0; i < sAttributeNames.length; i++) {
attributes += "" + sAttributeNames[i] + "";
}
var soapBody = "" +
"" +
"" + sEntityName + "" +
"" + GUID + "" +
"" +
"" + attributes + "" +
"
" +
"
" +
"
";
var soapXml = " "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xmlns:xsd='http://www.w3.org/2001/XMLSchema' " +
"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
soapXml += GenerateAuthenticationHeader();
soapXml += soapBody;
soapXml += "
";

xmlhttp = CreateRequestObject();
xmlhttp.open("POST", "/mscrmservices/2007/crmservice.asmx", false);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
xmlhttp.setRequestHeader("Content-Length", soapXml.length);
xmlhttp.send(soapXml);

// Capture the result.
var resultXml = xmlhttp.responseXML;
// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0) {
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
return null;
}
// Display the retrieved value.
else {
var retEntityValues = new Array();
var retrieveNodes = resultXml.selectNodes("soap:Envelope/soap:Body/RetrieveResponse/RetrieveResult/q1:*");
for (var i = 0; i < retrieveNodes.length; i++) {
var nodeName = retrieveNodes[0].baseName;
var nodeValue = retrieveNodes[0].nodeTypedValue;
retEntityValues[nodeName] = nodeValue;
}
return retEntityValues
}
}

function AddNotification(noticationId, text) {
if (crmForm.all.Notifications.all[noticationId] != null)
crmForm.all.Notifications.all[noticationId + '_text'].innerHTML = text;
else {
crmForm.all.Notifications.innerHTML += '
' + text + '
';
crmForm.all.Notifications.style.display = 'block';
}
}

function RemoveNotification(noticationId) {
if (crmForm.all.Notifications.all[noticationId] != null) {
crmForm.all.Notifications.all[noticationId].removeNode(true);
if (crmForm.all.Notifications.childNodes.length == 0)
crmForm.all.Notifications.style.display = 'none';
}
}

var customer = crmForm.all.customerid;
if (customer.DataValue != null && customer.DataValue[0].typename == 'account') {
var cs = new Array();
cs[0] = 'new_attention';
var acc = RetrieveEntity('account', customer.DataValue[0].id, cs);
if (acc != null && acc['new_attention'] == 1) {
AddNotification('NotificationAccount', 'Клиент требует внимания! Для более подробной информации перейдите в карточку клиента.');
crmForm.all.customerid_d.getElementsByTagName('SPAN')[0].style.color = 'Red';
}
else {
RemoveNotification('NotificationAccount');
}
}
else {
RemoveNotification('NotificationAccount');
}

2009-08-19

Get contact status in custom extended marketing list


declare @contactid uniqueidentifier
declare @campaignactivityid uniqueidentifier
-- some Guids
set @contactid='48CF39EE-AA8C-DE11-A526-000C2989FA53'
set @campaignactivityid='72CE8156-AD8C-DE11-A526-000C2989FA53'

select exL.New_ExtMarketingListsElementId, exL.New_contactStatus
from dbo.New_ExtMarketingListsElementExtensionBase exL
JOIN dbo.ContactBase cnt ON exL.new_contact=cnt.ContactId
JOIN dbo.ListBase lst ON exL.new_list=lst.ListId
JOIN dbo.CampaignActivityItemBase cai ON lst.ListId=cai.ItemId
where cnt.ContactId=@contactid
and cai.CampaignActivityId=@campaignactivityid

How to get Marketing Lists by Campaign Activity Id


declare @campaignactivityid uniqueidentifier
-- an example GUID
set @campaignactivityid='72CE8156-AD8C-DE11-A526-000C2989FA53'

-- связь между маркетинговым списком и кампанией осуществляется через промежуточную таблицу CampaignActivityItemBase
select *
from dbo.CampaignActivityItemBase cai
JOIN dbo.ListBase lb ON lb.ListId=cai.ItemId
where cai.CampaignActivityId=@campaignactivityid

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