Code snippets


Gallery Items – Search Custom Page

If(
    IsBlank(varRegionOfInterest),
    FirstN(
        Filter(
            AddColumns(
                Products,
                "RegionName",
                LookUp(
                    Villages,
                    Village = Products[@Village].Village
                ).Region.Name,
                "VillageName",
                LookUp(
                    Villages,
                    Village = Products[@Village].Village
                ).Name,
                "VillageStatus",
                LookUp(
                    Villages,
                    Village = Products[@Village].Village
                ).Status,
                "LivingOptionsName",
                LookUp(
                    Villages,
                    Village = Products[@Village].Village
                ).'Living Option'
            ),
            IsBlank('Created On')
        ),
        1
    ),
    Sort(
        Filter(
            AddColumns(
                Products,
                "RegionName",
                LookUp(
                    Villages,
                    Village = Products[@Village].Village
                ).Region.Name,
                "VillageName",
                LookUp(
                    Villages,
                    Village = Products[@Village].Village
                ).Name,
                "VillageStatus",
                LookUp(
                    Villages,
                    Village = Products[@Village].Village
                ).Status,
                "LivingOptionsName",
                LookUp(
                    Villages,
                    Village = Products[@Village].Village
                ).'Living Option'
            ),
            Status = 'Status (Products)'.Active,
            'Product Type' = 'Product Type (Products)'.Asset,
            VillageStatus = 'Status (Villages)'.Active,
            IsBlank(comboRegion.Selected.Name) || false || RegionName = comboRegion.Selected.Name,
            IsBlank(comboVillage.Selected.Name) || false || VillageName = comboVillage.Selected.Name,
            IsBlank(comboBedroom.Selected.Value) || false || Bedroom = Value(comboBedroom.Selected.Value),
            IsBlank(comboAssetStatus.Selected.Value) || false || 'Asset Status' = comboAssetStatus.Selected.Value,
            IsBlank(comboAssetType.Selected.Value) || false || 'Asset Type' = comboAssetType.Selected.Value,
            IsBlank(comboBudgetRange.Selected.Label) || false || 'Recommended Selling Price' >= Value(comboBudgetRange.Selected.RangeLower) && 'Recommended Selling Price' <= Value(comboBudgetRange.Selected.RangeUpper),
            IsBlank(comboLivingOptions.SelectedItems) || IsEmpty(comboLivingOptions.SelectedItems) || LivingOptionsName[@Value] in comboLivingOptions.SelectedItems
        ),
        Name,
        SortOrder.Ascending
    )
)

Check Form Type, Set Lookup (Business Unit)

function SetBusinessUnit(executionContext)
{
	// the scirpt will run only in create / new form.
		
   var formContext = executionContext.getFormContext(); 
	
	if(formContext.ui.getFormType() != 1)
		return;
	
	
// get the userId
var userId = Xrm.Utility.getGlobalContext().userSettings.userId;
// remove { and } from the userId
userId = userId.replace("{", "").replace("}", "");
// Xrm.WebApi call to retrieve details of the user (fullname)
// and the name of the businessunit (name from expand)
Xrm.WebApi.online.retrieveRecord("systemuser", 
userId,
"?$select=fullname&$expand=businessunitid($select=name)").then(
function success(result) {
	
	
    console.log(result);
    // Columns
    var systemuserid = result["systemuserid"]; // Guid
    var fullname = result["fullname"]; // Text
    
    // Many To One Relationships
    if (result.hasOwnProperty("businessunitid")) {
		       
		var businessunitid = result["businessunitid"]["businessunitid"]; // GUID of Business Unit
		var businessunitid_name = result["businessunitid"]["name"]; // Name of the Business Unit
		
		// set business unit lookup 
		var lookup = [];   // Creating a new lookup Array
		lookup[0] = {};    // new Object
		lookup[0].id = businessunitid;  // GUID of the lookup id
		lookup[0].name = businessunitid_name; // Name of the lookup
		lookup[0].entityType = "businessunit"; // Entity Schema name
		formContext.getAttribute("di_businessunit").setValue(lookup);	
		
    }
},
function(error) {
	

    console.log(error.message);
}
);

}

Calling JavaScript function from different file.

&nbsp;

if (typeof (TK) == "undefined")
{ TK = { __namespace: true }; }

TK.CRM = { __namespace: true };

TK.CRM.GetConfiguration = function (key) {
 return key;

};

TK =
 {
 IHDURL: TK.CRM.GetConfiguration("Enya"),

 GetConfig : function () { 

 alert("Enigma and " + TK.IHDURL);
 }
 }

<input id=”Button1″ type=”button” value=”button”  onclick =”TK.GetConfig(‘Testing’);”/>

string userId = “i:0#.f|membership|geek@favs.onmicrosoft.com”;

var g= userId.Substring(userId.LastIndexOf(“|”) + 1);

SPMetal /web:http://hydvlscmvm20:5000  /code:C:\LSS\InvoiceForms\SPContext.cs

Gettting value from Soap Response

var resultXml = xmlHttpRequest.responseXML;
alert(resultXml.xml);

var entityNodes =
resultXml.selectNodes(“//RetrieveResponse/RetrieveResult/a:Attributes”);
var billetId=entityNodes[0].childNodes[1].childNodes[1].childNodes[0].nodeTypedValue;

Quick reference of stsadm commads related to solution

  • stsadm -o upgradesolution -name inoutcontactwebpart.wsp -filename “C:\inoutcontactwebpart.wsp” -immediate -allowgacdeployment
  • stsadm -o execadmsvcjobs
  • stsadm -o deletesolution -name inoutcontactwebpart.wsp -override
    stsadm -o addsolution -filename  “C:\inoutcontactwebpart.wsp”
  • stsadm -o deploysolution -name inoutcontactwebpart.wsp -allcontenturls -immediate -allowgacdeployment -force

Using Case when null in t-sql query

SELECT
CASE
WHEN  caseorigincodename IS NUll
THEN  ‘NA’
ElSE  caseorigincodename
END as CaseOrigin
FROM         FilteredIncident
WHERE     (statecode = 0)

Showing hyperlink in GridView.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

/*

http://crm/ACES/main.aspx?etn=contact&etc=2&id={33201199-28EE-DF11-8F27-00155D326904}&pagetype=entityrecord

*/

if (e.Row.RowType == DataControlRowType.DataRow)

{

e.Row.Cells[1].Text = “<a href=’http://crm/ACES/main.aspx?etn=contact&extraqs=_gridType=2&etc=2&id={“ + e.Row.Cells[0].Text + “}&pagetype=entityrecord’>” + e.Row.Cells[1].Text + “</a>”;

e.Row.Cells[0].Visible = false;

}

if (e.Row.RowType == DataControlRowType.Header)

{

e.Row.Cells[0].Visible = false;

}

}

window.open(url, ”, ‘width=400,height=300,toolbar=0,resizable=0’);

ImageFieldUrl

<asp:ImageField DataImageUrlField=”ImageFile” DataImageUrlFormatString=”~/Images/Products/{0}” >
<asp:ImageButton ID=”ImageButton1″ runat=”server”

ImageUrl='<%# Eval(“ImageFile”, “~/Images/Products/{0}”) %>’ PostBackUrl='<%# Eval(“ProductID”,”~/ProductDetail.aspx?id={0}”) %>’ />

Code for update using Dynamic Entity

CrmService service = new CrmService();

service.Credentials = System.Net.CredentialCache.DefaultCredentials;

service.CrmAuthenticationTokenValue = new CrmAuthenticationToken();

service.CrmAuthenticationTokenValue.AuthenticationType = 0;

service.CrmAuthenticationTokenValue.OrganizationName = “orgName”;

DynamicEntity myDE = new DynamicEntity();

myDE.Name = EntityName.contact.ToString();

KeyProperty keyProp = new KeyProperty();

keyProp.Name = “contactid”;

keyProp.Value = new Key();

keyProp.Value.Value = new Guid(“entityGuid”);

StringProperty strProp = new StringProperty();

strProp.Name = “lastname”;

strProp.Value = “myLastName”;

Property[] propColl = new Property[2];

propColl[0] = keyProp;

propColl[1] = strProp;

myDE.Properties = propColl;

service.Update(myDE);

 

Expression for a field in report

It would check whether a field is null or not. If null that it would add six months to current date or else keep the same value. It would also remove the time part from it.

= iif(
IsNothing(new_mydate.Value),
Format(DateAdd(DateInterval.Month,6,Now()),”M\/d\/yyyy”),
Format(Fields!new_mydate.Value,”M\/d\/yyyy”)
)

= iif(

IsNothing(new_mydate.Value),

Format(DateAdd(DateInterval.Month,6,Now()),”M\/d\/yyyy”),

Format(Fields!new_mydate.Value,”M\/d\/yyyy”)

)

Dynamically showing progress bar in the left navigation pane of the entity form.

document.getElementById(‘navAsyncOperations’).innerHTML = “<table align=’center’><tr><td><div id=’showbar’ style=’font-size:8pt;padding:2px;border:solid black 2px;’><span id=’p1′>            </span>  <span id=’p2′>            </span>  <span id=’p3′>            </span></div><span id=’info’></span></td></tr></table>”;

var percentComplete;
GetPercentComplete=function()
{

// hard code the the value for total number of field
var totalField=3;

// set total no of blank field as 0
var totalBlankField=0;

// check for all the required fields and increment the value
if(crmForm.all.new_name.DataValue==null)
{
totalBlankField++;
}

if(crmForm.all.new_firstname.DataValue==null)
{
totalBlankField++;
}

if(crmForm.all.new_lastname.DataValue==null)
{
totalBlankField++;
}

// total no. of fields would be total field minus total blank field

var totalFilledField=totalField-totalBlankField;

// if total filled field is zero that 0 % complete

if(totalFilledField==0)
{

percentComplete=0;
}
else
{

// calculate the percentage
percentComplete=(totalFilledField/totalField)*100;

}

Code for refreshing parent Crm Form from an asp.net page code

private void ReloadWindow()
{
StringBuilder builder = new StringBuilder();
builder.Append(“<script language=JavaScript>”);
builder.Append(“\r\n”);
builder.Append(“if (“);
builder.Append(“(window.opener != null) &&”);
builder.Append(“(window.opener.parent != null) &&”);
builder.Append(“(window.opener.parent.document != null) &&”);
builder.Append(“(window.opener.parent.document.crmForm != null)) {“);
builder.Append(“\r\n”);
builder.Append(“var parentForm = window.opener.parent.document.crmForm;”);
builder.Append(“\r\n”);
builder.Append(“parentForm.Save();”);
builder.Append(“\r\n”);
builder.Append(“window.opener.document.location.replace(window.opener.location);”);
builder.Append(“\r\n”);
builder.Append(“}”);
builder.Append(“\r\n”);
builder.Append(“self.focus();”);
builder.Append(“</script>”);
this.Response.Write(builder.ToString());
}

Just a simple JavaScript to change the status of the form

var statusContent=”’test content’

document.getElementById(‘EntityStatusText’).innerHTML=statusContent;

Preventing user from changing url in browser javascript

<body onBlur=”self.focus();”>

For getting value from crm’s form to iframe page

var AccountName = parent.document.forms[0].all.name.DataValue;
alert(‘Order Name=’+AccountName);

For getting values from Iframe’s page

// test is the name of the iframe
// textbox1,image1 are the control inside the page within iframe

var to=window.frames[‘test’].document.getElementById(‘TextBox1’).value;
var to1=window.frames[‘test’].document.getElementById(‘Image1’).src;
For changing Button value using javascript

script type=”text/javascript”>

function SetReadOnly()
{

var x=document.getElementsByTagName(“input”);
for (var i=0;i<x.length;i++)
{
if (x.item(i).type==”button”&&x.item(i).value==”OK”)
{
x.item(i).value=”Save”
};
}
}
_spBodyOnLoadFunctionNames.push(“SetReadOnly()”);

</script>
For writing log in a text file

TextWriter log = TextWriter.Synchronized(File.AppendText(@”C:\g.txt”));
log.WriteLine(“MyMessage”);
log.Close();

For converting mm/dd/yyyy format to dd/mm/yyyy

public string ConvertTOSqlServerFormat(string DateToConvert)
{
int day, month, year;
String[] myDelim = DateToConvert.Split(new Char[] { ‘/’ });

day = Convert.ToInt32(myDelim[0]);
month = Convert.ToInt32(myDelim[1]);
year = Convert.ToInt32(myDelim[2]);

string myConvertedDate = new DateTime(year, month, day).ToShortDateString();
return myConvertedDate;
}

For giving double quotes

string myInfo=”Hello”;
string myMsg = @”This is my message”””+myInfo+ @”””to you”;
MessageBox.Show(myMsg);

–> This is my message “Hello” to you

For finding the days difference in javascript and setting a particular date 28 days before

<!–[if gte mso 9]> Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 <![endif]–><!–[if gte mso 9]> <![endif]–> <!–[endif]–>

function GetDiff(form1)

{

date1 = new Date(form1.firstdate.value);

date2 = new Date(form1.seconddate.value);

diff = new Date();

//date.getTime() –>Returns the number of milliseconds since midnight Jan 1, 1970

//Math.abs() –>Returns the absolute value of a number

//Math.floor –>Returns the value of a number rounded downwards to the nearest integer

diff=diff.setTime(Math.abs(date1.getTime() – date2.getTime()));

days = Math.floor(diff / (1000 * 60 * 60 * 24));

// if days greater than 28

// than set the first date 28 days less than the second date

if(days>28)

{

alert(‘Greater than 28 ‘);

// setting the second date 28 days less

date2.setDate(date2.getDate()-28);

// converting to string to find the length and if 1 than adding a 0

// i.e 1 to 01

var month=((date2.getMonth())+1).toString();

if(month.length==1)

{

month=“0”+month;

}

var date=date2.getDate().toString();

if(date.length==1)

{

date=“0”+date;

}

form1.firstdate.value=month+“/”+date+“/”+date2.getYear();

}

}

35 thoughts on “Code snippets”

    1. Hi,

      Nishant I am facing some problem while calling webservice from client machine. Below code is working fine on local machine(window 2003 server). When i call application from user machine (window XP) than permission denied error raise. Please help. Thanx in advance.

      function XmlhttpCall(objXML,serviceName)
      {
      try
      {
      var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
      var xmlHttpGo = xmlHttp;

      var str = “http://192.168.0.1/MyWebService/HelloWebService.asmx” + serviceName;
      //Service name is webmethod define in Webservice
      //192.168.0.1 is ip address of my server (Window 2003 Server)
      xmlHttpGo.open(“POST”, str, false);
      xmlHttpGo.SetRequestHeader(“Content-type”,”application/x-www-form-urlencoded”);
      xmlHttpGo.send(‘xmlLogin=’ + objXML.xml);

      var xmlString1 = xmlHttpGo.responseXML.text;

      return xmlString1;
      }
      catch(e)
      {
      return (e.Message + “–> XmlhttpCall”);
      }
      }

      Like

  1. Hi Nishant,

    I am trying to update attributes of entities programmatically for CRM 4.0 using metadatawebservice. can you please help me with snippet on how to do it.

    Like

  2. Hi Nishat,

    I need to call a custom webservice and pass a value on some event through javasript in CRM entity page.
    Can you please help me in this regard, giving some sample code?

    Like

  3. Hey Nishat, are you up for a SharePoint development project? reply a follow up comment here to let me know. This is for a company in California. Thanks.

    Like

  4. hi nishanth im trying to invoke a Siebel web service from .net(im using c#).im querying contacts.but im getting null response..can you please tell me how to do it properly..thanks in advance

    Like

  5. Hi Nishanth ,
    I am working on the MS CRM webservice on java . i couldn’t find much examples in the Java .can you please help on this . I am trying to store the value into the Salesorder entity . but i am getting exception. And Same thing is hpning while retrieving the data with query condition.
    . Please help me .

    org.apache.axis2.AxisFault:
    com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character ‘S’
    (code 83) in prolog; expected ‘<'
    at [row,col {unknown-source}]: [1,1]
    at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
    at
    org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:118)
    at
    org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:67)
    at
    org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:354)

    Like

  6. I have created a webservice to Add a contact, account etc.. So my client application will be to create a contact thro webservice.

    Right now, my client application database has tables for contact and account, but the primary key is of int data type. If i import all the contacts from the existing database to crm, all the contactid will be in GUID type.

    how will I identify which contact id(int) is for which guid?..

    how will I retrieve a imported contact from crm if I pass the contactid (int) to the webservice? ..

    should I create a custom attribute in crm as an identifier?

    Your help is greatly appreciated!

    Like

  7. I have created a webservice to Add a contact, account etc.. So my client application will be to create a contact thro webservice.

    Right now, my client application database has tables for contact and account, but the primary key is of int data type. If i import all the contacts from the existing database to crm, all the contactid will be in GUID type.

    how will I identify which contact id(int) is for which guid?..

    how will I retrieve a imported contact from crm if I pass the contactid (int) to the webservice? ..

    should I create a custom attribute in crm as an identifier?

    Your help is greatly appreciated!

    Thanks
    karthik

    Like

  8. Thanks for another informative web site. Where else could I get that type of info written in such an ideal way? I’ve a project that I’m just now working on, and I have been on the look out for such information.

    Like

  9. you are in reality a good webmaster. The site loading velocity is amazing.
    It kind of feels that you’re doing any unique trick. In addition, The contents are masterpiece. you have done a great process on this matter!

    Like

  10. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is fantastic, let alone the content!. Thanks For Your article about Code snippets | Nishant Rana& .

    Like

  11. Wow, awesome blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is magnificent, as well as the content!. Thanks For Your article about Code snippets | Nishant Rana& .

    Like

  12. Wow, fantastic blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is fantastic, let alone the content!. Thanks For Your article about Code snippets | Nishant Rana& .

    Like

  13. Wow, marvelous blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is wonderful, as well as the content!. Thanks For Your article about Code snippets | Nishant Rana& .

    Like

  14. Heya just wanted to give you a quick heads up and let
    you know a few of the pictures aren’t loading correctly. I’m not sure
    why but I think its a linking issue. I’ve tried it in two different browsers
    and both show the same results.

    Like

  15. I’m curious to find out what blog platform you are utilizing?
    I’m experiencing some small security issues with my latest website and I would like to find something more risk-free.
    Do you have any solutions?

    Like

  16. Hi folks,
    I am new to Dynamics CRM, I want to integrate CRM such that when even some operations/changes performed on Accounts and Leads, I need to post them to a HTTP endpoint.
    please help me.

    Like

  17. Hi there, I discovered your web site via a search engine at the same time as searching for a similar topic. I really appreciate this post. I have been looking everywhere for this! Your site hit the nail upon the top and outlined the whole thing without having side effect , other people could take a benefit and will probably come again to get more. Thanks!

    Like

  18. नमस्ते, मैंने उसी समय एक खोज इंजन के माध्यम से आपकी वेब साइट की खोज की थी जब एक समान विषय की खोज की गई थी। मेरे द्वारा इस पोस्ट में वास्तव में प्रसंशा की जाती है। मेरे द्वारा इसे हर जगह ढूंढा जा रहा था! आपकी साइट ने शीर्ष पर कील ठोक दी और साइड इफेक्ट के बिना पूरी बात को रेखांकित किया, अन्य लोग लाभ उठा सकते थे और शायद अधिक प्राप्त करने के लिए फिर से आएंगे। धन्यवाद!

    Like

  19. Bonjour, j’ai découvert votre site web via un moteur de recherche en même temps que je cherchais un sujet similaire. J’apprécie vraiment cet article. Je l’ai cherché partout ! Votre site a frappé le clou sur le dessus et a souligné l’ensemble de la chose sans avoir d’effet secondaire, d’autres personnes pourraient prendre un avantage et sera probablement revenir pour obtenir plus. Je vous remercie !

    Like

Please share your thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Power Spark

Power Spark By Shrangarika

Van Carl Nguyen

Exploration of Power Platform

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog of Paul Andrew

Sponsored by Cloud Formations Ltd

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Dynamics 365 Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM