Quantcast
Channel: CRM Development forum
Viewing all 465 articles
Browse latest View live

jQuery/JavaScript - Set HTML value in web resource

$
0
0

I am making an OData call which returns the correct data I need (Question, Topic and Score).  I then have identified the first record in the array and I am trying to set an HTML cell value (for the Topic) value using jQuery.  For whatever reason, it is not working.  Eventually, what I would like to do with this code is that for every question returned in the OData (which will include each question's respective Topic and Score), I would like for jQuery to dynamically create a row per Question in the HTML table.  Here is what I have so far for both jQuery and HTML.  FYI--checkAccountType is being called in the OnLoad event handler in CRM:

//  Get Scoring records of current Account

  //Wait for page to load then check Account Type
//$(document).ready(function () {
//    console.log("document).ready fired");
//    checkAccountType();
//});

//  Check Account Type
function checkAccountType() {
    //  Validation to check if there is a value in the Organization Type lookup field
    var lookup = Xrm.Page.getAttribute("new_customertypeid").getValue();
    if ((lookup != null) && (lookup != "undefined")) {
        //  Call getScoringQuestions
        getScoringQuestions();
    }

}

//  Grabs the specific details from the parent Account record
function getScoringQuestions() {

    var accountId = Xrm.Page.data.entity.getId();
    var accountFilter = "$select=new_Score,new_ScoringQuestionId,new_new_scoringquestion_new_scoring/new_QuestionTopicId,new_new_scoringquestion_new_scoring/new_SequenceId&" +"$expand=new_new_scoringquestion_new_scoring&$filter=new_ScoringAccountId/Id eq guid'" + accountId + "'";
    SDK.JQuery.retrieveMultipleRecords("new_scoring",
        accountFilter,
        function (results) {
            for (var i = 0; i < results.length; i++) {
                var topics = results[i].new_new_scoringquestion_new_scoring.new_QuestionTopicId.Name;
                var questions = results[i].new_ScoringQuestionId.Name;
                var scores = results[i].new_Score;

                var firstTopic = results[0].new_new_scoringquestion_new_scoring.new_QuestionTopicId.Name;
                var firstQuestion = results[0].new_ScoringQuestionId.Name;
                var firstScore = results[0].new_Score;

                //console.log(topics);
                //console.log(questions);
                //console.log(scores);

                console.log(firstTopic);
                //console.log(firstQuestion);
                //console.log(firstScore);


                $("#Topic").html(firstTopic);
                $("#Question").html(firstQuestion);
                $("#Score").html(firstScore);





            }


        },
        errorHandler,
        questionRetrieveComplete);



}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title></title><link rel="stylesheet" type="text/css" href="../styles/SummaryTable.css"/><script type="text/javascript" src="../../ClientGlobalContext.js.aspx"></script><script type="text/javascript" src="../../new_SDKJquery"></script><!--<script type="text/javascript" src="../scripts/jquery.js"></script>--><script type="text/javascript"src="../../new_/scripts/jquery.1.10.2.min.js"></script><script type="text/javascript" src="../scripts/sdk/json2.js"></script><script type="text/javascript" src="../../new_/sdk/rest.js" ></script><script type="text/javascript" src="../scripts/entities/account_scoring.js"></script></head><body><table id="scoringSummary" width="100%" border="1" cellpadding="0" cellspacing="0"><thead id="theads"><tr><th class="th">Topic</th><th class="th">Question</th><th class="th">Allowed Values</th><th class="th">Score</th><th class="th">Is Editable?</th></tr></thead><tbody id="tbody"><tr><td id="Topic"></td><td id="Question"></td><td id="allowedValues" align="center">    <!-- Dropdown --><select id="dropdown"><option value="optionValue">Option Value</option></select></td><td id="score"></td><td id="isEditable"><input type="radio" name="editable" value="0"/>No<input type="radio" name="editable" value="1"/>Yes</td></tr></tbody></table></body></html>

If anyone could provide some insight, it would be greatly appreciated.  Thanks in advance!


document.getElementById(GridName): Object is required.

$
0
0

Hi, I use the following sort of script to re-size the height of the sub grid.

function fnHeight()
 {
document.getElementById("testingGrid").control.style.height = "4px";
}

But the above code gives me the following error message at this line 4.

<Message>Object required</Message>

<Line>4</Line>

So, Please let me know how can I change the above code to change the height of the sub-grid.

Your kind help and suggestions will encourage me in this regards.

Thank You.

Regards.

Plugin Create Record from Track Email ISV Error

$
0
0

Is there a way to check if contact exists in CRM and if not ignore them? I am running into an error where if the to or from contact in the email doesn't exist in the CRM it throws a ISV error. I need to check if the to or from value equals a specific user if it does it creates a lead if not it does nothing. The only way I know to check the to or from fields is to create the activityparty array and then check those values but if they don't even exist in the first place in the CRM it throws that ISV error. Is there code that can check if they exist in the CRM before trying to grab the contact values out of the CRM contact records?

Below is the bit of code I have that checks who the to and from persons are. The to catch prevents the ISV error if the from person doesn't exist in the CRM when tracking. However, now people are going back and tracking sent emails and that throws off the"to" catch and then gives the ISV error. So I'm hoping there is a simply way to just say if the contact doesn't exist in the CRM don't run the plugin.

Thanks for any help!

EntityCollection emailTo = entity.Attributes["to"] as EntityCollection;
                    EntityReference toEmail = emailTo[0].Attributes["partyid"] as EntityReference;
                    Guid emailToId = toEmail.Id;
                    Guid myId = new Guid("E200F73B-57CC-E111-B35F-12A32B1E376A");

                if (emailToId == myId)
                {
                    EntityCollection emailAddress = entity.Attributes["from"] as EntityCollection;
                    EntityReference email = emailAddress[0].Attributes["partyid"] as EntityReference;
                    Guid emailId = email.Id;
                    Guid contactId = new Guid("84B80350-B14B-E311-876F-12A32B1E376A");

                    if (contactId == emailId)

Displaying images and PDF’s stored as Annotations in a HTML Web Resource

$
0
0

Displaying Annotation images in a HTML Web Resource works fine. The image is displayed no problem.

However, I cannot display a PDF and/or Visio file.

The code in bold is what isn’t working, I think.

What am I doing wrong?

<html><head><title>Annotation Viewer</title><script type="text/javascript" src="jquery"></script> <script type="text/javascript" src="ClientGlobalContext.js.aspx"></script><script type="text/javascript">
            function getImages(guid) {
                var context = GetGlobalContext();
                $.getJSON(context.getServerUrl() + "/XrmServices/2011/OrganizationData.svc/AnnotationSet?$select=AnnotationId,DocumentBody,MimeType&$filter=AnnotationId eq guid'" + guid + "'", function (data) {
                    if (data.d.results.length > 0) {
                        var singleRecord = data.d.results[0]
                        loadImage(singleRecord);
                    }
                });
            }


            function loadImage(record) {
                while (attachment_content_table.rows.length > 0) {
                    attachment_content_table.deleteRow(0);
                }
                var newRow = attachment_content_table.insertRow(0);
                var newCell = newRow.insertCell(0);

                if (record.MimeType == "image/png" || record.MimeType == "image/gif" || record.MimeType == "image/jpeg") {
                    newCell.innerHTML = "<img src='data:" + record.MimeType + ";base64," + record.DocumentBody + "'/>";
                }
                else if (record.MimeType == "application/pdf" || record.MimeType == "application/vnd.visio") {newCell.innerHTML = "<object data='data:" + record.MimeType + ";base64," + record.DocumentBody + "' type='" + record.MimeType + "'><embed src='data:" + record.MimeType + ";base64," + record.DocumentBody + "' type='" + record.MimeType + "' /></object>";                }
            }</script></head><body><table id="attachment_content_table" /></body></html>




crm connectivity

$
0
0

I am getting this error "NAV Server time and CRM Server time may not be in sync or there is no data for the submitted date"while running my ms dynamics nav-crm connector application in .net. Has anyone come across this error or know how to rectify this.... The code down below is used for this connector..not the entire code however.,.,This I believe is occuring while trying to connect tot he CRM in the

getOrders function


using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Security;
using System.Runtime.InteropServices;
using System.DirectoryServices.AccountManagement;
using System.ServiceModel;

//crm
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using EssaeXrm;

namespace Wpf_to_CRM
{
    class config
    {
        public Uri DiscoveryUri ;
        public Uri OrganizationUri ;
        DiscoveryServiceProxy discserviceProxy ;
        OrganizationServiceProxy orgserviceProxy ;
        public ClientCredentials clientcred ;
        public DateTime datm;
        string usr, pwd, reg, organisation , crmver;
        public ClientCredentials devicecred ;


        public void usrpwd(string x, string y , string z , string c)
        {
            this.usr = x;
            this.pwd = y;
            this.reg = z;
            this.crmver = c;
        }

  
        public virtual ClientCredentials GetCredentials()
        {
            ClientCredentials credentials = new ClientCredentials();
            credentials.UserName.UserName = usr;
            credentials.UserName.Password = pwd;
            return credentials;
        }

        protected virtual ClientCredentials GetDeviceCredentials()
        {
            return Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
        }

        public OrganizationDetailCollection DiscoverOrganizations(IDiscoveryService service)
        {
            if (service == null) throw new ArgumentNullException("service");
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse orgResponse =
                (RetrieveOrganizationsResponse)service.Execute(orgRequest);

            return orgResponse.Details;
        }

        public OrganizationDetailCollection allorgs()
        {
            try
            {
                this.clientcred = this.GetCredentials();
                this.devicecred = this.GetDeviceCredentials();
                this.DiscoveryUri = new Uri(String.Format("https://{0}.{1}.dynamics.com/XRMServices/2011/Discovery.svc", this.crmver, this.reg));
                using (discserviceProxy = new DiscoveryServiceProxy(DiscoveryUri, null, clientcred, devicecred))
                {
                    OrganizationDetailCollection allorg = this.DiscoverOrganizations(discserviceProxy);
                    return allorg;
                }
            }
            catch
            {
                return new OrganizationDetailCollection();
            }
        }

        public List<string> orgdetail()
        {
            OrganizationDetailCollection orgs = this.allorgs();
            List<string> orgname = new List<string>();
            int i = 0;
            while(i < orgs.Count)
            {
                orgname.Add(orgs[i].UrlName);
                i++;
            }
            return orgname;
        }

        public void selectedorg(string retorg , DateTime datme)
        {
            this.organisation = retorg;
            this.datm = datme;
        }

        public DataTable querylist()
        {
            try
            {
                //Organization URL
                OrganizationUri = new Uri(String.Format("https://{0}.api.{1}.dynamics.com/XRMServices/2011/Organization.svc", this.organisation, this.reg));
                using (orgserviceProxy = new OrganizationServiceProxy(OrganizationUri, DiscoveryUri, clientcred, devicecred))
                {
                    // This statement is required to enable early-bound type support.
                    orgserviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                    IOrganizationService orgservice = (IOrganizationService)orgserviceProxy;
                    using (ServiceContext svcContext = new ServiceContext(orgserviceProxy))
                    {
                        DateTime d = datm.AddDays(1);
                        //DateTime d1 = d.AddDays(-1);
                        //DateTime d2 = d.AddDays(1);
                        var query = from a in svcContext.SalesOrderSet join b in svcContext.AccountSet on a.CustomerId.Id equals b.Id where a.SubmitDate < d && a.SubmitDate > datm && a.StatusCode == 3 select new { A = a, B = b };
                        //StreamWriter sw = new StreamWriter(@"C:\excelfile\excel.csv", true);
                        DataTable dt = new DataTable();
                        dt.Columns.Add("SO Id");
                        dt.Columns.Add("Order Number");
                        dt.Columns.Add("Name");
                        dt.Columns.Add("Submitted Date");
                        dt.Columns.Add("Customer");
                        dt.Columns.Add("Total Tax");
                        dt.Columns.Add("Total Line Item Amount");
                        dt.Columns.Add("Total Amount");
                        dt.Columns.Add("Structure");
                        foreach (var e in query)
                        {
                            dt.Rows.Add(e.A.Id.ToString(), e.A.OrderNumber, e.A.Name, e.A.SubmitDate, e.B.AccountNumber, e.A.TotalTax, e.A.TotalLineItemAmount, e.A.TotalAmount, e.A.new_Structure.Name);

                            //sw.WriteLine(e.A.Id.ToString() + "," + e.A.OrderNumber + "," + e.A.Name + "," + e.A.TotalAmount.ToString() + "," + e.A.CustomerId.Id.ToString() + "," + e.B.AccountNumber + "," + e.B.AccountId.Value.ToString() + "," + e.B.AccountId.ToString() + "," + e.B.Name);
                        }
                        //sw.Close();
                        return dt;

                    }
                }
            }
            catch
            {
                return new DataTable();
            }
        }

        public virtual ClientCredentials newcred(string usr, string pass)
        {
            ClientCredentials cred = new ClientCredentials();
            cred.UserName.UserName = usr;
            cred.UserName.Password = pass;
            return cred;
        }
        public DataTable prodquery(List<string> str)
        {
            DiscoveryUri = new Uri(String.Format("https://{0}.{1}.dynamics.com/XRMServices/2011/Discovery.svc", str[1], str[4]));
            OrganizationUri = new Uri(String.Format("https://{0}.api.{1}.dynamics.com/XRMServices/2011/Organization.svc",str[0],str[4]));
            this.newcred(str[2],str[3]);
            using(OrganizationServiceProxy orgprox = new OrganizationServiceProxy(OrganizationUri,DiscoveryUri,this.newcred(str[2],str[3]),this.GetDeviceCredentials()))
            {
                // This statement is required to enable early-bound type support.
                orgprox.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                using(ServiceContext svCon = new ServiceContext(orgprox))
                {
                    Guid ID = new Guid(str[5]);
                    var prodq = from e in svCon.SalesOrderDetailSet join d in svCon.ProductSet on e.ProductId.Id equals d.Id where e.SalesOrderId.Id == ID select new { E = e, D = d };
                    DataTable prdet = new DataTable();
                    prdet.Columns.Add("Product Name");
                    prdet.Columns.Add("Quantity");
                    prdet.Columns.Add("Unit Price");
                    foreach(var q in prodq)
                    {
                        prdet.Rows.Add(q.D.ProductNumber,q.E.Quantity,q.E.PricePerUnit);
                    }
                    return prdet;
                }
            }
        }

        public DataTable getOrders(DateTime datm)
        {
            try
            {
                DiscoveryUri = new Uri(String.Format("https://{0}.{1}.dynamics.com/XRMServices/2011/Discovery.svc", "dev", "crm5"));
                OrganizationUri = new Uri(String.Format("https://{0}.api.{1}.dynamics.com/XRMServices/2011/Organization.svc", "essaetechnologyspvtlimited", "crm5"));
                using (OrganizationServiceProxy orgproxy = new OrganizationServiceProxy(OrganizationUri, DiscoveryUri, this.newcred("essaecrm@live.in", "Essae@123"), this.GetDeviceCredentials()))
                {
                    orgproxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                    using (ServiceContext svcContext = new ServiceContext(orgproxy))
                    {
                        DateTime d = datm.AddDays(1);
                        var query = from a in svcContext.SalesOrderSet join b in svcContext.AccountSet on a.CustomerId.Id equals b.Id join c in svcContext.SystemUserSet on a.OwnerId.Id equals c.Id where a.SubmitDate < d && a.SubmitDate > datm && a.StatusCode == 3 select new { A = a, B = b, C = c };
                        DataTable dt = new DataTable();
                        dt.Columns.Add("SO Id");
                        dt.Columns.Add("Order Number");
                        dt.Columns.Add("Name");
                        dt.Columns.Add("Submitted Date");
                        dt.Columns.Add("Customer");
                        dt.Columns.Add("Address Contact");
                        dt.Columns.Add("Ship to Address 1");
                        dt.Columns.Add("Ship to Address 2");
                        dt.Columns.Add("Structure");
                        dt.Columns.Add("Ship to City");
                        dt.Columns.Add("Purchase Order No");
                        dt.Columns.Add("Purchase Order Date");
                        dt.Columns.Add("Remarks");
                        dt.Columns.Add("SO Series");
                        dt.Columns.Add("Core details");
                        dt.Columns.Add("Salesperson Code");
                        dt.Columns.Add("Request Delivery Date");
                        string SOseries = String.Empty;
                        string CoreDetails = String.Empty;
                        foreach (var e in query)
                        {
                            try
                            {
                                switch (e.A.new_SOseries)
                                {
                                    case 100000000: SOseries = "HO";
                                        break;
                                    case 100000001: SOseries = "LD";
                                        break;
                                    case 100000002: SOseries = "MH";
                                        break;
                                    case 100000003: SOseries = "AP";
                                        break;
                                    default: SOseries = "";
                                        break;
                                }

                                switch (e.A.new_CoreDetails)
                                {
                                    case 100000000: CoreDetails = "1\"";
                                        break;
                                    case 100000001: CoreDetails = "0.5\"";
                                        break;
                                    case 100000002: CoreDetails = "40mm";
                                        break;
                                    case 100000003: CoreDetails = "3\"";
                                        break;
                                    default: CoreDetails = "";

                                        break;
                                }
                                dt.Rows.Add(e.A.Id.ToString(), e.A.OrderNumber, e.A.Name, e.A.SubmitDate, e.B.AccountNumber, e.A.BillTo_ContactName, e.A.ShipTo_Line1, e.A.ShipTo_Line2, e.A.new_Structure.Name, e.A.ShipTo_City, e.A.new_PONumber, e.A.new_PurchaseOrderDate, e.A.Description, SOseries, CoreDetails, e.C.dynamics_erpsystemuserid.Name, e.A.RequestDeliveryBy);
                            }
                            catch
                            {
                            }
                        }
                        return dt;
                    }
                }
            }
            catch
            {
                return new DataTable();
            }
        }
    }
}


Unable to get Value of the propert 'getFormType': object is null or undefined.

$
0
0
I have facing script error when i configured CRM 2011 with outlook, my org is on premises. Error is not occurring when i open the contact Entity from the CRM. but when i open the Contact Entity from the outlook and press any navigation, it shows me error "Unable to get value of the property 'getFormType': object is null or undefined". 

URL: http://crm.lmkr.com/LMKR/main.aspx?etc=2&extraqs=%3fetc%3d2%26id%3d%257bAF6FB739-0553-E311-972E-02BF0A416542%257d%26pagemode%3diframe%

I have disabled the javascript that is calling onload event of Contact Entity, but could not find the actual solution why it is occurring.

Thanks, Qaisar

Silverlight plugin duplicate creates

$
0
0

Hi All,

Having this odd issue; I have an OpportunitySet that I use to create multiple opportunities into my CRMOnline.

What happens is that I loop through all my stackpanels that hold the controls to add info and if its valid I add the current Opportunity to the set.

                    if (!inval)
                    {   _context.AddToOpportunitySet(newOpportunity);
                        p.Children.Clear();
                    }

When I loop back I clear the Opportunity and start fresh. After all are done I save the set with my service.

_context.BeginSaveChanges(OnCreateOpportunityComplete, _context.OpportunitySet);

Now where it gets funny is that it only saves the first, and if i have >2 sets it will make that first as many times equal to the number of records there should be.  BUT if i use debugger it will make all the Opportunities it's supposed to PLUS the first one multiple times over.

I've created an Opportunity array that adds the new opportunity at the same time as the OpportunitySet to make sure there is no funny business when clearing the old data; and the data looks perfect.  My thoughts are its in the ASync calls, but if any knows why or the solution please help!

Thank you

How can i get all Activities of organization crm?

$
0
0
Hello, everyone!
I just started working with crm 2011. I have connection with database:
var connection = new CrmConnection("crmconnection");
var service = new OrganizationService(connection);
var context = new CrmOrganizationServiceContext(connection);
I need to get all activitypointers and their LastEditDate. Please help.=)

CRM 2011 Getting System.TypeLoadException after plugin build

$
0
0

Hi!

Fixed an error in a plugin(EmailFilterPlugin which treats emails) and build it With success(Visual Studio 2010). Then updated the plugin with Plugin registration Tool(as usual) and suddenly we get the error below... I have also tried with no change in code, same problem. I believe there must be something with my develop environment but can't see what it is... when I update with an old build it Works fine!  

Please help me, I'm stuck:-)

Log Name:      MSCRMEmailLog
Source:        MSCRMEmailLog
Date:          18.09.2013 11:05:09
Event ID:      9628
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      _server.local
Description:
#9628 - An error occurred while delivering the e-mail message with subject "bla bla bla" in mailbox testskjema@bla.no for delivery to http://_server/MSCRMOrg. System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: System.TypeLoadException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #D06FF112 (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
Event Xml:<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"><System><Provider Name="MSCRMEmailLog" /><EventID Qualifiers="0">9628</EventID><Level>2</Level><Task>0</Task><Keywords>0x80000000000000</Keywords><TimeCreated SystemTime="2013-09-18T09:05:09.000000000Z" /><EventRecordID>12712398</EventRecordID><Channel>MSCRMEmailLog</Channel><Computer>_server.local</Computer><Security /></System><EventData><Data>#9628 - An error occurred while delivering the e-mail message with subject "bla bla bla" in mailbox testskjema@bla.no for delivery to http://_server/MSCRMOrg. System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: System.TypeLoadException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #D06FF112 (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).</Data></EventData></Event>
BR Knut Myre


MS CRM 2011 Online - How to retrieve unit for order product automatically from price list item?

$
0
0

How can I retrieve a unit for product automatically from a price list when I am creating a new order product?

I have managed to get a default unit of the product but now I need to get the unit which are defined under the price list.

This is the code which I used for retrieving the default unit.

/*
When a product value is changed set the Unit field to the Default Unit value specified on the Product entity
//The JSON2 Javascript library must be added to the form as a webresource and set to load before this javascript library
Set the Timer function to be fired onchange of the product field - this will wait for 100ms then launch the SetProductUnit function
*/
function Timer()

//This is the function that is fired onchange of the product field
//A timer is required before firing the SetProductUnit function
//More info here http://promx.wordpress.com/2011/06/27/setting-the-default-unit-for-opportunity-quote-and-salesorder-product-in-crm-2011-using-javascript/
{

    window.setTimeout(SetProductUnit(), 100);
}
 
function SetProductUnit()
//Set the Unit value to the default Unit of the product
{

    //Start building URI of rest endpoint
    //var serverUrl = "http://" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
	var serverUrl = document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
    //Get the value of the Product
    var productid = Xrm.Page.data.entity.attributes.get('productid').getValue();


 
    if (productid != null)
    {
 
        var productguid = productid[0].id;
 
         // Creating the Odata Endpoint
		
		
		var clear = productguid;
		var n=clear.replace("{", "").replace("}", "");
        var oDataPath ="https://destamatic.crm11.com/XRMServices/2011/OrganizationData.svc";
        var retrieveReq = new XMLHttpRequest();
        var Odata = oDataPath + "/ProductSet?$select=DefaultUoMId&$filter=ProductId eq Guid'" + n + "'";
        retrieveReq.open("GET", Odata, false);
        retrieveReq.setRequestHeader("Accept", "application/json");
        retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
		        retrieveReq.onreadystatechange = function ()
        {
            if (this.readyState == 4)
                    {
                        if (this.status == 200)
                                {
                                    var retrievedRecords = JSON.parse(retrieveReq.responseText).d;
                                    if(retrievedRecords.results.length > 0)
                                                    {
                                                        var product = retrievedRecords.results[0];
                                                        var uomguid = product.DefaultUoMId.Id;
                                                        var uomname = product.DefaultUoMId.Name;
                                                        var uomlogical = product.DefaultUoMId.LogicalName;
                                                        //Set the Unit lookup field with the value returned
                                                        Xrm.Page.getAttribute('uomid').setValue([{id: uomguid, name: uomname, entityType: uomlogical}]);
                                                    }
                                }
                    }
        }
    //Send the request
    retrieveReq.send();
    }
    else
    {
        //If the onchange event has been a delete of the Product or no product exists then clear the Unit field
        Xrm.Page.getAttribute('uomid').setValue(null);
    }
}

How to associate multiple contacts with account in CRM 4

$
0
0

How can i associate contacts with account using SDK ?

for primary contact it works fine, but i need to associate N contacts with single account based on a criteria. 

Everything is working fine except association.

Here is the code

 // Create an AssociateEntities linked.
                    AssociateEntitiesRequest linked = new AssociateEntitiesRequest();
                    // Set the ID of Moniker1 to the ID of the lead.
                    linked.Moniker1 = new Moniker()
                    {
                        Id = accidstring.Value,
                        Name = "account"
                    };
                    //linked.Moniker1.Id = new Guid("B050F053-6968-DC11-BB3A-0003FFBAD37A");
                    //linked.Moniker1.Name = EntityName.lead.ToString();

                    // Set the ID of Moniker2 to the ID of the contact.
                    linked.Moniker2 = new Moniker()
                    {
                        Id = new Guid(contactId),
                        Name = "contact"
                    };
                    //linked.Moniker2.Id = new Guid("1DCDEE97-35BB-44BE-8353-58BC36592656");
                    //linked.Moniker2.Name = EntityName.contact.ToString();

                    // Set the relationship name to associate on.
                    try
                    {
                        linked.RelationshipName = "contact_customer_accounts";

                        // Execute the linked.
                        svc.Execute(linked);
                    }
                    catch
                    {
                        linked.RelationshipName = "accounts_contacts";
                        svc.Execute(linked);
                    }


( ';')< "I hate this UI"

Serialization Exception in WorkFlow 4.5 with WorkflowInstanceUnhandledExceptionRecord

$
0
0

Hi, I have configured my WorkFlowApplication to emit tracking records. And, in the overridden Track() method Im trying to convert the TrackingRecord to XML and storing it somewhere.

Im able to parse all the type of Tracking Record except UnhandledExceptionRecord and FaultPropogationRecord.

It throws SerializationException. 

Here is my Track() method,

  protected override void Track(TrackingRecord record, TimeSpan timeout)
        {
            string _xmlData = string.Empty;
            WorkFlowTrackingEntity trackEntity = null;
            if (record != null)
            {
                using (TextWriter textWriter = new StringWriter())
                {
                    XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
                    DataContractSerializer serializer = new DataContractSerializer(record.GetType());
                    serializer.WriteObject(xmlWriter, record);
                    _xmlData = textWriter.ToString();
                    xmlWriter.Flush();
                    textWriter.Flush();
                }
                trackEntity = new WorkFlowTrackingEntity(record.InstanceId.ToString(), record.EventTime);
                trackEntity.XMLContent = _xmlData;
                WorkFlowTrackingHandler.GetInstance.LogTrackingRecord(trackEntity);
            }
        }

This is how i convert the record to XML.

Can anyone pls tell where I'm going wrong.

CRM 2013: Calling actions from javascript

$
0
0

Hi all,

I was trying to call action from javascript using the below code:

function Approve()
{
    debugger;
    var reason = "aaaaaaaaaaaaaaaaaa";
    var entityId = Xrm.Page.data.entity.getId();
    var entityName = "serviceappointment";
    var requestName = "new_SetRejectionReason";
    ExecuteActionCreateProject(reason, entityId, entityName, requestName);
}

function ExecuteActionCreateProject(reason, entityId, entityName, requestName)
{
    // Creating the request XML for calling the Action
    var requestXML = ""
    requestXML += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    requestXML += "  <s:Body>";
    requestXML += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestXML += "      <request xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
    requestXML += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    requestXML += "          <a:KeyValuePairOfstringanyType>";
    requestXML += "            <b:key>Reason</b:key>";
    requestXML += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">"+reason+"</b:value>";
    requestXML += "          </a:KeyValuePairOfstringanyType>";
    requestXML += "          <a:KeyValuePairOfstringanyType>";
    requestXML += "            <b:key>Target</b:key>";
    requestXML += "            <b:value i:type=\"a:EntityReference\">";
    requestXML += "              <a:Id>"+entityId+"</a:Id>";
    requestXML += "              <a:LogicalName>"+entityName+"</a:LogicalName>";
    requestXML += "              <a:Name i:nil=\"true\" />";
    requestXML += "            </b:value>";
    requestXML += "          </a:KeyValuePairOfstringanyType>";
    requestXML += "        </a:Parameters>";
    requestXML += "        <a:RequestId i:nil=\"true\" />";
    requestXML += "        <a:RequestName>"+requestName+"</a:RequestName>";
    requestXML += "      </request>";
    requestXML += "    </Execute>";
    requestXML += "  </s:Body>";
    requestXML += "</s:Envelope>";
    var req = new XMLHttpRequest();
    req.open("POST", GetClientUrl(), false)
    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationServic/Execute");
    req.send(requestXML);
    //Get the Resonse from the CRM Execute method
    var response = req.responseXML.xml;
}
function GetClientUrl() {
    if (typeof Xrm.Page.context == "object") {
        clientUrl = Xrm.Page.context.getClientUrl();
    }
    var ServicePath = "/XRMServices/2011/Organization.svc/web";
    return clientUrl + ServicePath;
}

And this the response that I get:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault><faultcode xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">a:ActionNotSupported</faultcode><faultstring xml:lang="en-US">The message with Action 'http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationServic/Execute' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).</faultstring></s:Fault></s:Body></s:Envelope>

Kindly advise


Serialization Exception in WorkFlow 4.5 with WorkflowInstanceUnhandledExceptionRecord

$
0
0

Hi, I have configured my WorkFlowApplication to emit tracking records. And, in the overridden Track() method Im trying to convert the TrackingRecord to XML and storing it somewhere.

Im able to parse all the type of Tracking Record except UnhandledExceptionRecord and FaultPropogationRecord.

It throws SerializationException. 

Here is my Track() method,

  protected override void Track(TrackingRecord record, TimeSpan timeout)
        {
            string _xmlData = string.Empty;
            WorkFlowTrackingEntity trackEntity = null;
            if (record != null)
            {
                using (TextWriter textWriter = new StringWriter())
                {
                    XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
                    DataContractSerializer serializer = new DataContractSerializer(record.GetType());
                    serializer.WriteObject(xmlWriter, record);
                    _xmlData = textWriter.ToString();
                    xmlWriter.Flush();
                    textWriter.Flush();
                }
                trackEntity = new WorkFlowTrackingEntity(record.InstanceId.ToString(), record.EventTime);
                trackEntity.XMLContent = _xmlData;
                WorkFlowTrackingHandler.GetInstance.LogTrackingRecord(trackEntity);
            }
        }

This is how i convert the record to XML.

Can anyone pls tell where I'm going wrong.

Authentication Using Java CRM CRUD Example - CRM 2011

$
0
0

I am trying to run the Java example in the Walkthrough for CRM 2011, and the request is failing when attempting to retrieve the Online Authentication Policy (using the class OnlineAuthenticationPolicy). I added debug to see what exactly was happening, and when we attempt to retrieve the Policy Node (from the Discovery Service WSDL), we get back the following XML (after searching for the wsp.All node:

<ms-xrm:AuthenticationPolicy xmlns:ms-xrm="http://schemas.microsoft.com/xrm/2011/Contracts/Services"><ms-xrm:Authentication>ActiveDirectory</ms-xrm:Authentication></ms-xrm:AuthenticationPolicy><sp:SymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy"><wsp:Policy><sp:ProtectionToken><wsp:Policy><sp:SpnegoContextToken
             sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient"><wsp:Policy><sp:RequireDerivedKeys/></wsp:Policy></sp:SpnegoContextToken></wsp:Policy></sp:ProtectionToken><sp:AlgorithmSuite><wsp:Policy><sp:Basic256/></wsp:Policy></sp:AlgorithmSuite><sp:Layout><wsp:Policy><sp:Strict/></wsp:Policy></sp:Layout><sp:IncludeTimestamp/><sp:EncryptSignature/><sp:OnlySignEntireHeadersAndBody/></wsp:Policy></sp:SymmetricBinding><sp:Wss11 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy"><wsp:Policy/></sp:Wss11><sp:Trust10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy"><wsp:Policy><sp:MustSupportIssuedTokens/><sp:RequireClientEntropy/><sp:RequireServerEntropy/></wsp:Policy></sp:Trust10><wsaw:UsingAddressing/>]

The code then attempts to search for the "appliesTo", "policy", and "issuerUri" nodes in this XML, but cannot find them since the nodes the code is looking for do not exist. We are using an "On Premises" server (the CRM version is running on our server), but when I attempt to point to the server in the sample code (https://disco.crm.dynamics.com/XRMServices/2011/Discovery.svc), that service does have the correct nodes (but then authentication fails since we are not defined on that server). Is this due to how we have our authentication structure configured in our server?

Any help would be greatly appreciated.


Endless Paging results from Query Expression (Many records with same Modified Date)

$
0
0

Hi all,

I'm experiencing a weird issue regarding paging results via the XRM SDK (v5.0.17).
The code I am using is very similar to the example code provided by Microsoft in the following article:

The problem is that I have a CRM instance where the above code never finished paging through the list of Accounts.

The cause seems to be related to the fact that a large portion (500+) of Accounts share exactly the same Modified Date (due to a previous Import).  While thePageInfo.Count (page size) I am using is set to 250. 
(Unfortunately, extending this pagesize is not a viable option as I expect it could eventually exceed the maximum return packet).

What happens is that all is fine paging the large result set until it reaches these imported Accounts, then the paging gets "stuck" re-returning the same page of results.

I can kind of understand why this might be happening when I inspect the PageInfo.PagingCookie, as this specifies items such as the last Modified Date retrieved (below):

<cookie page="5"><modifiedon last="2013-12-19T10:29:42-00:00" first="2013-12-19T10:29:42-00:00" /><accountid last="{41383BE5-DA03-E211-BC22-00505681000E}" first="{A915AF5B-4100-DF11-A0D2-000C2925A48B}" /></cookie>

However, it also seems to also specify the last AccountID as well, which I would have thought would negate this issue.

Would really appreciate anyone that has suggestions to overcome this issue (I'm probably doing something wrong!)

Many thanks!


Retriving Entity including RelatedEntity using OrganizationService and without using SDK

$
0
0

At Present I am getting  orders with following code, Now I want to get even related entities like products with salesorder. Can any one please suggest me code block for retrieving related entity with salesorder.

I dont want to use any sdk dlls here. only Organization service reference.

OrganizationService.ColumnSet cset = new ColumnSet(); cset.Columns = new string[] { "new_orderid", "salesorderid", "pricelevelid", "transactioncurrencyid", "customerid" };

QueryExpression salesorderQuery = new QueryExpression { EntityName = "salesorder", ColumnSet = cset, Criteria = new FilterExpression { }, // LinkEntities= new LinkEntity[]{relatedEntity}; }; Entity[] salesorder = client.RetrieveMultiple(salesorderQuery).Entities;



Thanks Regards Prashanth Kamasamudram Even the least work done for others awakens the power within; even thinking the least good of others gradually instills into the heart the strength of a lion.


Add multiple Custom views in Party Lookup (Regarding)

$
0
0

I have set up the Regarding lookup (in Email entity) to show only Incidents and a custom entity, called Problem.

I can set up through JavaScript a custom view (filtered) only for one of these entities, but not for both.

How can I have multiple custom views for this lookup?

document.getElementById("regardingobjectid").setAttribute("defaulttype", "112");
document.getElementById("regardingobjectid").setAttribute("lookuptypenames", "Incident:112:Case,aux_problem:10036:Problem");
document.getElementById("regardingobjectid").setAttribute("lookuptypes", "112,10036");
document.getElementById("regardingobjectid").setAttribute("lookuptypeIcons", "/_imgs/ico_18_112.gif:../WebResources/aux_problem_icon_16");

setCasesView("aux_account", "regardingobjectid", false);

 I call here to setProblemsView, the same as setCasesView but not setting it as default (with the false at the end)

Xrm.Page.getControl(lookupFieldName).addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, false);

But is not applying my filtered view when I choose problems Problems

function setCasesView(entityFieldName, lookupFieldName, resetSelection) {

    // use randomly generated GUID Id for the view
    var viewId = "{xxxxxxxx-xxxx-0000-9FB6-58E69E4C81AA}";

    var entityName = "incident";

    // give the custom view a name
    var viewDisplayName = "Cases in Account: " + accname + "";

    // find all cases where account is the account selected
    var fetchXml = ...
    var layoutXml = ...

    Xrm.Page.getControl(lookupFieldName).addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
    document.getElementById(lookupFieldName).setAttribute("disableViewPicker", "1");
}

Update Using the REST Enpoint with JavaScript fails

$
0
0

I'm trying to update a custom entity field value (an auto number) from the onsave event of a form. Here's the relevant script saved in the WebResource attached to the form's onsave event there (_orgDataPath is retrieved from the page context and works e.g. for a Retrieve request on the same form, so it does not appear to be the source of the issue here).

When I run this in the form's onsave event, the new_CurrentIndex value of the custom entity is not updated and no error message is given.

So my questions are: 1) Is the code below correct for a synchronous REST update using javascript? 2) If the code for the basic REST update above is correct, are there CRM configuration settings that would prevent the update from succeeding?

(new to this...thanks for help)

///<summary>
/// Entry point.
///</summary>
function GetAutoNumber() {
    var targetGuid = "90DD7D29-D129-E311-93D4-00155D001A03";  // the guid of the ECRs auto number entity
    var targetName = "new_autonumbersetting";  // the name of the entity      

    // get the current record for targetName entity
    var autoNumberSetting = retrieveRecord(targetGuid, targetName);

    // set retrieved next index number to form field
    Xrm.Page.getAttribute("new_ecr_number").setValue("ECR-" + autoNumberSetting.new_CurrentIndex.toString());

    // increment
    autoNumberSetting.new_CurrentIndex++;

    // update
    updateRecord(targetGuid, autoNumberSetting, targetName);
}

///<summary>
/// Sends a synchronous request to update a record.
///</summary>
function updateRecord(id, object, type) {
    ///<param name="id" type="String">
    /// A String representing the GUID value for the record to retrieve.
    ///</param>
    ///<param name="object" type="Object">
    /// A JavaScript object with properties corresponding to the Schema Names for
    /// entity attributes that are valid for update operations.	
    ///</param>
    ///<param name="type" type="String">
    /// The Schema Name of the Entity type record to retrieve.
    /// For an Account record, use "Account"
    ///</param>    

    var req = new XMLHttpRequest();
    req.open("POST", encodeURI(this._orgDataPath() + type + "Set(guid'" + id + "')"), false);  // synchronous call
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("X-HTTP-Method", "MERGE");
    var jsonEntity = window.JSON.stringify(object);

    req.send(jsonEntity);
}

How to delete a Contract detail and associated records?

$
0
0

We have CRM 2011 on premises. I am trying to cancel a contract detail without cancelling its parent contract.

Questions:

1) I found this code online:

TargetDeleteContractDetail target = new TargetDeleteContractDetail();
 target.EntityId = new Guid(someGuid);
DeleteRequest delete = new DeleteRequest();
 delete.Target = target;
 DeleteResponse deleted = (DeleteResponse)service.Execute(delete);

but TargetDeleteContractDetail is not coming up as a valid class.  In what namespace and in what dll does it reside?

2) Is there an alternate way of accomplishing this?

3) We have a custom entity, call it "D", which has an N:1 relationship with Contact.  D also has a relationship with a Contract Detail, call it "CD", as follows, where "X" is an entity that just connects the two.

When I cancel the contractdetail, I also have to delete all entity records X, that connect to all entity records D for that Contract Detail.

Please advise how to accomplish this.

Thank you.

Viewing all 465 articles
Browse latest View live


Latest Images

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