Quantcast
Channel: Forum CRM Development
Viewing all 1000 articles
Browse latest View live

Javascript/FetchXML OnChange working for me but not other Admin

$
0
0

We are on CRM 4.0 and I've implemented some JavaScript with FetchXML in it which should perform the following actions.

On my custom entity, I have a "Site" lookup field with a custom text field below it.  When the Site is populated or changed, the javascript should kick off and grab the Parent Account lookup from the Site.  Then, get the text of a field at the Parent Account level. After it has the text, it should populate the custom text field as mentioned at the beginning.  This all works fine for me but does not work at all for another Admin user. I need this to be working for all users and I am stumped as to what the problem is.

Does anyone have any ideas as to what could be the problem?  

Also, here is the JavaScript.

if (crmForm.all.new_siteid !=null)
{

if(crmForm.all.new_siteid.DataValue != null)
{ 

   GetSiteParent(crmForm.all.new_siteid.DataValue[0].id);
}

}


function GetSiteParent(siteId)
{
 var textReturn = "";

   if (siteId !=null)
   {
     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>new_site</q1:EntityName>" + "    <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" + "     <q1:Attributes>" + "      <q1:Attribute>new_siteid</q1:Attribute>" + "      <q1:Attribute>new_parentid</q1:Attribute>" + "      <q1:Attribute>new_schoolyearopen</q1:Attribute>" + "     </q1:Attributes>" + "    </q1:ColumnSet>" + "    <q1:Distinct>false</q1:Distinct>" + "    <q1:Criteria>" + "     <q1:FilterOperator>And</q1:FilterOperator>" + "     <q1:Conditions>" + "      <q1:Condition>" + "       <q1:AttributeName>new_siteid</q1:AttributeName>" + "       <q1:Operator>Equal</q1:Operator>" + "       <q1:Values>" + "        <q1:Value xsi:type=\"xsd:string\">" + siteId + "</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 resultXml = xmlHttpRequest.responseXML;

//alert(resultXml);


if(resultXml !=null)
{  
  var parentId = resultXml.selectSingleNode("//q1:new_parentid").nodeTypedValue;

  if(parentId !="")
  {
    GetAccountCostCenter(parentId);
  }
  else
	{
		crmForm.all.new_costcenter.DataValue = null;
	}
}
}
	else
	{
		crmForm.all.new_costcenter.DataValue = null;
	}
//return textReturn;
}


function GetAccountCostCenter(accountId)
{
 var textReturn = "";

   if (accountId !=null)
   {
     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>account</q1:EntityName>" + "    <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" + "     <q1:Attributes>" + "      <q1:Attribute>accountid</q1:Attribute>" + "      <q1:Attribute>new_costcenter</q1:Attribute>" +"     </q1:Attributes>" + "    </q1:ColumnSet>" + "    <q1:Distinct>false</q1:Distinct>" + "    <q1:Criteria>" + "     <q1:FilterOperator>And</q1:FilterOperator>" + "     <q1:Conditions>" + "      <q1:Condition>" + "       <q1:AttributeName>accountid</q1:AttributeName>" + "       <q1:Operator>Equal</q1:Operator>" + "       <q1:Values>" + "        <q1:Value xsi:type=\"xsd:string\">" + accountId + "</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 resultXml = xmlHttpRequest.responseXML;

//alert(resultXml);

if(resultXml !=null)
{  
  textReturn= retriveText(resultXml.selectNodes("//BusinessEntity/q1:new_costcenter"));

  if(textReturn !="")
  {
    crmForm.all.new_costcenter.DataValue = textReturn;
  }
  else
	{
		crmForm.all.new_costcenter.DataValue = null;
	}


}

} 

return textReturn;
}


function retriveText(InputNode)
{
 var text = "";
if (InputNode !=null)
{
 if(InputNode[0]!=null)
 {
 text =InputNode[0].text;
   }
  } 

 return text;
}


Use Javascript to Update Price Per Unit When Selecting a Product in Dynamics CRM 2011

$
0
0

PowerObjects - Use Javascript to Update Price Per Unit When Selecting a Product in Dynamics CRM 2011

Attempting to use this jscript below, getting the following error when debugging...Any help would be appreciated. Thanks

"Unable to get value of the property '0': object is null or undefined"

Line 39

"Unterminated string constant"

Line 8

function onChangeUnit() {

var productField = Xrm.Page.getAttribute("productid").getValue();

var productFieldId = productField[0].I\id;

//store the product guid here

if (productFieldId != null) //if product not null get guid for unit
{
var unit = Xrm.Page.getAttribute("uomid").getValue();

//get guid for Parent opportunity

var opportunityId = Xrm.Page.getAttribute("opportunityid").getValue();

if (opportunityId != null)

//if opportunity guid is null, discontinue

{
//build query

var pagecontext = Xrm.Page.context;

var serverUrl = pagecontext.getServerUrl();

var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc/";

var oDataSelect = oDataPath + "OpportunitySet?$select=PriceLevelId&$filter=OpportunityId eq guid'" + opportunityId + "'";

//start AJAX call for the parent price list guid

$.ajax({

type: "GET",

contentType: "application/json;charset=utf-8",

datatype: "json",

url: oDataSelect,

beforeSend: function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},

success: function (data, status)
{
NowWeHaveThePriceList(data, status, productFieldId, unit, oDataPath);
},

error: function (XmlHttpRequest, textStatus, errorThrown)
{
alert("OData Select Failed : " + errorThrown + " .There is no parent price list ");

}

});

}

}

}

function NowWeHaveThePriceList(data, status, productFieldId, unit, oDataPath)
{
var priceLevelId = data.d.results[0].PriceLevelId.Id; //retrieved pricelevel

//start AJAX clal for Price List Item entities = Price List GUID and Product Guid and Unit Guid and return the Amount on that price list item. This will return one results.

var oDataSelect2 = oDataPath + "ProductPriceLevelSet?$select=Amount&$filter=PriceLevelId/Id eq guid'" + priceLevelId + "' and ProductId/Id eq guid'" + productFieldId + "' and UoMId/Id eq guid'" + unit[0].id + "'";

$.ajax({

type: "GET",

contentType: "application/json;charset=utf-8",

datatype: "json",

url: oDataSelect2,

beforeSend: function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},

success: NowWeHavePrice,
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("OData Select Failed : " + errorThrown + " .There is no price list item for this product");

}

});

}

function NowWeHavePrice(data, status)
{
if (data != null) {

//set the price per unit

var priceListItemAmount = data.d.results[0].Amount.Value;

Xrm.Page.getAttribute("priceperunit").setValue(parseFloat(eval(priceListItemAmount)));

Xrm.Page.getAttribute("priceperunit").setSubmitModeAlways;

}
}

CRM Plugin throws the following error "Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)."

$
0
0

I have a plugin with a code snippet below on a custom entity.  I am trying to add a quote detail on creation of this entity.

As soon as it executes it throws the exception "

Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)."

 Guid productGuid = new Guid (result1[0].Attributes["productid"].ToString());
 Guid UomID = new Guid(result1[0].Attributes["defaultuomid"].ToString());
 Guid QuoteId = new Guid(dataSet[0].Attributes["quoteid"].ToString());

 Entity quoteDetail = new Entity("quotedetail");
                         quoteDetail.Attributes["quotedetailid"] = _quoteDetailId;
                         quoteDetail.Attributes["quoteid"] = new EntityReference("quote", QuoteId); 
                         quoteDetail.Attributes["productid"] = new EntityReference("product", productGuid);
                         quoteDetail.Attributes["quantity"] = QuoteLines.Attributes["axsi_quantity"];
                         quoteDetail.Attributes["priceperunit"] = QuoteLines.Attributes["axsi_priceperunit"];
                         quoteDetail.Attributes["uomid"] = new EntityReference("uom", UomID);
                         quoteDetail.Attributes["ispriceoverridden"] = true;
                         service.Create(quoteDetail);

I suspect there is something wrong around the UOMID. Any pointers would be highly appreciated.

Script to hide/show field based on Subject chosen

$
0
0

I have bee trying to get a code that will show a lookup field when a particular Subject is chosen. The code hides the field no matter what is chosen. Any advice as to the syntax on what to use would be appreciated. Below is what i've been using.

// If "Case Category" (subjectid) equals Catalog, display the Catalog (fbsm_catalogid) field.  Otherwise, do not display this field.
if (crmForm.all.subjectid.SelectedText == 'Catalog')
{
crmForm.all.fbsm_catalogid_c.style.display = "block";
crmForm.all.fbsm_catalogid_d.style.display = "block";
}
else
{
crmForm.all.fbsm_catalogid_c.style.display = "none";
crmForm.all.fbsm_catalogid_d.style.display = "none";
}

How to reference the record id in an entity collection retrieved using FetchXML

$
0
0

I'm sure this is really simple but I'm not really a developer. I'm querying CRM using FetchXML and RetrieveMultiple. The querys runs against a custom entity and returns a total grouped by account (which is a lookup in the custom entity). The FetchXML looks like this:

            string fetchquery = @"<fetch distinct='false' mapping='logical' aggregate='true'><entity name='new_customentity'><attribute name='new_usercount' alias='UsercountSum' aggregate='Sum'/><attribute name='new_account' groupby='true' alias='Account'/></entity></fetch>";

I retrieve the results using:

        EntityCollection fetchquery_result = _service.RetrieveMultiple(new FetchExpression(fetchquery));

Now, I want to loop through the results and use the total user count for each account to update a field on the account. I can get at the user count using:

 foreach (var c in fetchquery_result.Entities)
            {
                int usercount = (int)((AliasedValue)c.Attributes["UsercountSum"]).Value;
}

But I can't work out how to reference the guid of the account record to use in an Update call. I've tried:

Guid thisaccountid = (Guid)((AliasedValue)c.Attributes["Account"]).Value;

but that returns an error, Specified cast is not valid. When casting from a number, the value must be a number less than infinity.

Any insight here would be highly appreciated.

how to Set Default "Look For " field for lookup view

$
0
0

Dear All,

How to set default LookFor value in Lookup field?

CRM 2011: Plugin to update fields of current record

$
0
0

Hi all,

I was trying to develop a very simple plugin for CRM 2011 to update an attribute for the current record, ( This attribute cannot be added to the form so I cannot do it with jscript or worflows), but I cannot find any queries sample for update operations on the SDK, all of them are for the retrieve operations only, so if someone could help with some code samples or snippets it would be great

 

Thanks in advance..


Can I disable the login prompt for MS CRM 2011 SDK if credentials are wrong?

$
0
0
Right now I access the CRM SDK as follows

    IServiceManagement<IDiscoveryService> serviceManagement =
                            ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(discoveryUri);
    ClientCredentials credentials = new ClientCredentials();
    credentials.Windows.ClientCredential = new System.Net.NetworkCredential(userName, password, domain);
    using (DiscoveryServiceProxy serviceProxy = new DiscoveryServiceProxy(new DiscoveryServiceProxy(serviceManagement, credentials))
    {
        RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
        RetrieveOrganizationsResponse orgResponse =
                    (RetrieveOrganizationsResponse)service.Execute(orgRequest);
        // do something with organisations
    }



However, if the domain credentials are incorrect, a Windows login prompt appears (somewhere in service.Execute). I don't want that login prompt. I have worked around this issue by validating the credentials using PrincipalContext before passing them to the DiscoveryServiceProxy, but I'm not entirely happy with that, as it does not work for IFD accessed from another domain.

Is there a way to disable the login prompt?

2 FetchXML Queries, One Report

$
0
0

Trying to figure out how to run two queries in a Fetch XML report on a Case/Incident and pass the same parameter to both queries.

The concept is that you are on the Case form, select 'Report' and run a Case Report.  The Case report will have details about the specific case that you are currently viewing, but also list some details about the related activities.

Incident query:

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"><entity name="incident" enableprefiltering="1" ><attribute name="incidentstagecode" /><attribute name="caseorigincode" /><attribute name="title" /><attribute name="responsiblecontactid" /></entity></fetch>

That seems to work. Then I add a 2nd query to get the related activities where the regarding object id matches the current incident ID.

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"><entity name="activitypointer"><attribute name="subject" /><attribute name="ownerid" /><attribute name="prioritycode" /><attribute name="regardingobjectid" /><attribute name="activitytypecode" /><order attribute="createdon" descending="true" /><filter type="and"><condition attribute="activitytypecode" operator="in"><value>4202</value><value>4210</value><value>4212</value></condition><condition attribute="regardingobjectid" operator="eq" value="@CRM_incident" /></filter></entity></fetch>

This doesn't seem to work, I get errors and it won't show the report.

Thoughts?  How can I get the IncidentID to both queries?

Find the earliest date/time present in any of the 4 fields and update the results.

$
0
0

Hi 

I want to get the earliest date/time present in any of the 4 fields outlined below and update the result toDate Result field .

I want it to be done using java script without writing lots of code and comparisons.

Can any one tell me how easily we can do it?


puja jain

add entity to a lookup crm 2011

$
0
0
Hello! I want to add an entity "account" to a "Recipient" field on the task form. Recipient field contains "contact" now.Can anyone please help how to acheive this functionality

How to change business unit of an user?

$
0
0

Hi All,

In crm 2011 is there any way to change the business unit of an user? If possible, then any c# coding help?

Thanks,

Mohak

CRM 2011: Setting lookup field default view using jscript

$
0
0

Hi all, I have a requirement to set the default view to be displayed in a opportunity based on the selected value of an optionset.

For sure the easiest way to do this is to create two custom views and to set one of them to be displayed on the change of the optionset value, but what if I already have the two views as system views ? Is there anyway to use them instead of creating two similar custom views ??

Thanks and best regards..

CRM 2011 UR 13 - dialogs rendering issue

$
0
0

Hi,

Our CRM servers have been upgraded to rollup 13 and we started facing some issues. Below is an issue with the Dialogs, they do not render properly and throw a javascript error message.

If anyone has run into this issue before and has a fix/workaround please assist.

<ScriptErrorDetails><Message>Invalid argument.</Message><Line>1</Line><URL>/_static/_controls/UIScripts/UIScriptUtil.js?ver=343258512</URL><Function>anonymous(hintId){this.$D_3&&this.HideHint(this.$D_3);this.$D_3=hintId;....


Annotation class

$
0
0

Hi,

Where do I get the reference of Annotation  class of CRM 2011 in asp.net application.


Dnyaneshwar Bhamare


CRM2011: Creating a Web Resource Web Page that Calls a Web Resource Javascript

$
0
0

I'v found code online that shows how to call a SRS report via the navigation bar of an Account entity. The code works really well and is made up of a custom webpage the calls an embedded javascript function to acquire the parent entities id key and also to configure the iframe needed by the srs report to function.

I need to create three of these navigation report links, but what I didn't want to do is have to repeat the javascript code each time, so I decided to lift the javscript code out of the web page and place it in its own javascript resource file and pass in the two unqiue parameters each report requires.

However, I soon came across a problem, and that was how do I get the web page resource file to reference the javascript resource file? I've seen chatter online that seems to indicate it's doable but I've not seen an example I can learn from.

Can anybody confirm it is possible to reference a javascript resource file from a web page resource file, and if so how.

Many thanks

Steve

How do I shorten a decimal value so I can update a form?

$
0
0

Trying to insert a value into a json / OData script:

            var new_TaxPercentage = result_timesheet.new_TaxTypePercentage;

            Xrm.Page.getAttribute("new_taxpercentage").setValue(parseFloat(eval(new_TaxPercentage.new_Float)));

The correct value is retrieved but the decimal point is greater: 20.000000000, and I want to insert into a field that has 1 decimal place. Any ideas?

Save on annotation entity fails with an exception in the event viewer.

$
0
0
I am trying to save the annotation entity in CRM 2011 using the following code :

<!-- language: c# -->

    var annotationContext = new CrmOrganizationServiceContext(crmOrganizationService);
    var annotation = annotationContext.CreateEntity("annotation");
    annotationContext.AddObject(annotation);
    // Setting the account id.
    entity.SetAttributeValue<EntityReference>("objectid", "account", "Guid of the account");    
    entity.iCrmSetPropertyValue(AnnotationDefinition.ColumnsName.DocumentBody,Convert.ToBase64String(new UnicodeEncoding().GetBytes("Sample Annotation Text")));
    entity.iCrmSetPropertyValue("isdocument",true);
    entity.iCrmSetPropertyValue(AnnotationDefinition.ColumnsName.Mime, "text/plain");
    entity.iCrmSetPickListValue(AnnotationDefinition.ColumnsName.ObjectType, 1);
    entity.iCrmSetPropertyValue(AnnotationDefinition.ColumnsName.Subject, "CompanyLogo");
    annotationContext.SaveChanges();

The save changes method fails with following error in the eventviewer of the crm server :

 The Web Service plug-in failed in OrganizationId: ###########;
 SdkMessageProcessingStepId: #####; EntityName: annotation; Stage: 30;
 MessageName: Create; AssemblyName:
 Microsoft.Crm.Extensibility.InternalOperationPlugin,
 Microsoft.Crm.ObjectModel, Version=5.0.0.0, Culture=neutral,
 PublicKeyToken=31bf3856ad364e35; ClassName:
 Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception:
 Unhandled Exception: System.InvalidCastException: Specified cast is
 not valid.    at
 Microsoft.Crm.BusinessEntities.EntityNameReferenceAttributeConverter.ConvertToBusinessEntity(Object
 value, AttributeMetadata attributeMetadata, Dictionary`2
 abbrvToChildAttributeMetadata, ICrmConversionContext context,
 BusinessEntity target)    at
 Microsoft.Crm.BusinessEntities.EntityToBusinessEntityConverter.ConvertUsingExistingBusinessEntity(EntityMetadata
 entityMetadata, ICrmConversionContext conversionContext, Entity
 entity, BusinessEntity businessEntity)    at
 Microsoft.Crm.BusinessEntities.BusinessEntity.Converter.ConvertFrom(ITypeDescriptorContext
 context, CultureInfo culture, Object value)    at
 Microsoft.Crm.BusinessEntities.ConversionHelpers.Convert(ICrmConversionContext
 conversionContext, Object source, Type destinationType)    at
 Microsoft.Crm.Extensibility.DictionaryMapper.Map(ParameterCollection
 inputs, ICrmConversionContext context)    at
 Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider
 serviceProvider)    at
 Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext
 context)    at
 Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext
 context)

Rollup 12 - problem with web resources and jquery

$
0
0

Hi all,

Before  Rollup 12, the main form iframe of an entity added js script references in the <head> section. After RU12 the scripts are added in the body and scripts aren't always executed in the order in which they referenced - causing random 'jquery' is undefined errors.

Is there any way of forcing CRM to reference scripts in the <head> section, or a way of adding 'DEFER' to the script tags ?

Paul

load email template when an email activity is addded in contact

$
0
0

Hello All,

I'm using below code to load email template on, onload of email activity. But its giving me error as CreateXmlDocument is undefined.

function loadtemplate()
{
var emailTemplateToLoad = "E83BA87D-65B9-E211-A110-00155D019F1E";//guid of template
// Get Regarding object details
var RegardingItems =Xrm.Page.getAttribute("regardingobjectid").getValue();
var regardingObjectId = RegardingItems[0].id;
var regardingObjectType = RegardingItems[0].type;
var command = new RemoteCommand("EmailTemplateService", "GetInstantiatedEmailTemplate");
command.SetParameter("templateId", emailTemplateToLoad );
command.SetParameter("objectId", regardingObjectId);
command.SetParameter("objectTypeCode", regardingObjectType);
var result = command.Execute();
if (result.Success)
{
    var o = new Object();
    o.EmailBody = "";
    o.EmailSubject = "";
    if(typeof(result.ReturnValue) == "string")
    {
        oXml = CreateXmlDocument(false);
        oXml.loadXML(result.ReturnValue);
        crmForm.all.description.InsertValue(oXml.selectSingleNode("template/body").text);
        o.EmailSubject = oXml.selectSingleNode("template/subject").text;
    }
}

}

Please help me solve this problem.

Thanks and Regards. Make sure to "Vote as Helpful" and "Mark As Answer",if you get answer of your question.

Viewing all 1000 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>