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

CRM 2011 RollUp 14 : Request not supported: ExecuteMultiple

$
0
0

I have simple method which wrap bulk entity and send to crm via

ExecuteMultipleRequest

With previous Rollup 12 it works OK, now it is broken.

Error message:

Request not supported: ExecuteMultiple

There is no error when I change send them to crm one by one so I guess it is not the data issue.

Does any encounter same issue?


Trying to limit field security to owner of record using PrincipalObjectAttributeAccess

$
0
0

I've got a field on an appointment entity - PrivateNotes. I only want to allow the OWNER of the field to be able to read & update this field. So, field security will not suffice.

I googled this question, and found some code that uses PrincipalObjectAttributeAccess to restrict an individual field's security to just the owner, however I can't get the code to work, and I've tried several ways. PrincipalObjectAttributeAccess is new to me, I never heard of it before today.

Here is the simplest version I found:

       private void ShareSecureFieldWithOwner(Entity record)
        {
            // Any method that helps you find the AttributeMetadata Id
            var attributeId = FindSecuredAttribute();

            if (attributeId != Guid.Empty)
            {
                var userAccess = new PrincipalObjectAttributeAccess
                {
                    AttributeId = attributeId,
                    ObjectId = record.ToEntityReference(),
                    PrincipalId = record.OwnerId,
                    UpdateAccess = true,
                    ReadAccess = true
                };

            context.AddObject(userAccess);
            context.SaveChanges();
            }
        }

2 main problems with this:

1. I don't know how I'm going to implement FindSecuredAttribute.

2. It's telling me that I'm missing a reference or assembly, as it doesn't recognise PrincipalObjectAttributeAccess. I'm trying to find what using statement/namespace/reference I need for this, but can't find anything.

Here are the current using statements I have:

using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

I REALLY don't know what I'm doing here, so I need the simplest explanantion possible!

Thanks.

accessing crm data withing ISV custom code

$
0
0

I have this scenario where after manage to bypass the sign in page with authentication, I still get a 401 unauthorised when trying to access the CRM entities

this code will let my web service return a value like just a hardcoded string but will fail if I try to access and return an crm 4 entity

   CrmAuthenticationToken sdktoken = new CrmAuthenticationToken();
                sdktoken.AuthenticationType = 2;
                sdktoken.OrganizationName = orgInfo.OrganizationName;
                sdktoken.CrmTicket = ticketResponse.CrmTicket;

                CrmService x = new CrmService();
                x.CrmAuthenticationTokenValue = sdktoken;
                x.Url = orgInfo.CrmServiceUrl;

tried change to networkauthentication, localhost:555 but still didn't work, it says 401 unauthorized.

could that be a deployment/web.config issue overwriting the code?

Call FireOnChange event MS CRM 4.0 via webBrowser Control in C#

$
0
0

Hi,

i would like to fire the event FireOnChange event in a webBrowser Control for an Outlook Plugin, but the event won't be fired. This function should be executed when i leave the name field for a duplicate function check in JS.

 webBrowser1.Document.InvokeScript("crmForm.all.lastname.FireOnChange();");

plz help thx

Andreas

File Upload Control on CRM 2011 Form

$
0
0

Hi

I added a file upload control inside an Iframe on form. I called a web-resource to do this.

HTML webresource has following source :

<html><head><meta><meta><meta><meta></head><body><table style="width:100%; background-color:white"><colgroup><col width="79%"><col width="1%"><col width="20%"></colgroup><tbody><tr><td><input type="file" onchange="setFormDirty();" id="userFileId" name="userFile" ></td></tr></tbody></table></body></html>

Now, when I select a file and click save button on form, I want to create a webresource. I will be uploading only Image files, so please let me know how I can do it.

Primarily, I am stuck at, how to read the file path, file and other file specifications which I can use in either jscript or a plugin to upload it as a webresource.

Sum values from Subgrid with if statement

$
0
0

Hello,

I'm having some difficult getting this code to execute properly. I am trying to total the Quantity field from the subgrid based on the product type. So when a sales rep is entering in opportunity products a field below the subgrid would show the total units. I only want the field to sum the quantity of products with the value of software or hardware. I get odd behavior back with the below code. If I have the if statement point to just one product type i.e "Software" the summed value is returned as 0. If I use the or statement "Software" || "Hardware" the summed value totals everything thing in the subgrid not just the hardware or software items. Below is my code. Any help is greatly appreciated.

function UnitsTimeout(){
 setTimeout(calcUnits, 1500);
}
function calcUnits() {
var grid = document.getElementById('opportunityproductsGrid'); 
var ids = grid.control.get_allRecordIds();
var sum = 0.00;
for(i = 0; i < ids.length; i++) {
  if(grid.control.getCellValue('producttypecode',ids[i]) == "Software" || "Hardware") {
  var cellValue = grid.control.getCellValue('quantity',ids[i]);
  var number = Number(cellValue.replace(/[^0-9\.]+/g,""));
  sum = sum + number;
}
}
Xrm.Page.data.entity.attributes.get("new_itemssold").setValue(sum);
Xrm.Page.data.entity.attributes.get("new_itemssold").setSubmitMode("always");
}

CRM 2011 Online - Silverlight/WCF alwasy get an error

$
0
0

Hello!

I have a SL 5 project.In the SilverlightApplication.Web I have a Silverlight-enabled WCF service, which connects to a Sharepoint and do something. (returns a byte[]) I use this as a Service Reference in my SilverlightApplication. On my local computer it works well, but not in CRM Online.

My web.config looks like this:

<?xml version="1.0"?><!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  --><configuration><configSections></configSections><system.web><compilation debug="true" targetFramework="4.0" /></system.web><system.serviceModel><serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/><behaviors><serviceBehaviors><behavior name=""><serviceMetadata httpsGetEnabled="true" /><serviceDebug includeExceptionDetailInFaults="true" /></behavior><behavior name=""><serviceMetadata httpGetEnabled="true" /><serviceDebug includeExceptionDetailInFaults="true" /></behavior><behavior name="DisableServiceCertificateValidation"><serviceCredentials><clientCertificate><authentication certificateValidationMode="None" revocationMode="NoCheck"/></clientCertificate></serviceCredentials></behavior></serviceBehaviors></behaviors><bindings><customBinding><binding name="SilverlightApplication4.Web.AuthService.customBinding0" ><binaryMessageEncoding  maxReadPoolSize="2147483647" maxSessionSize="2147483647" maxWritePoolSize="2147483647" /><httpsTransport maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="StreamedResponse" /></binding></customBinding></bindings><services><service name="SilverlightApplication4.Web.AuthService"><endpoint address="" binding="customBinding" bindingConfiguration="SilverlightApplication4.Web.AuthService.customBinding0"
            contract="SilverlightApplication4.Web.AuthService" /><endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" /></service></services><!--<behaviors><serviceBehaviors><behavior name=""><serviceMetadata httpGetEnabled="true" /><serviceDebug includeExceptionDetailInFaults="false" /></behavior></serviceBehaviors></behaviors>--><!--<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />--></system.serviceModel></configuration>


And my clientconfig:

<configuration><system.serviceModel><bindings><customBinding><binding name="CustomBinding_AuthService"><binaryMessageEncoding /><httpsTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="StreamedResponse"/></binding></customBinding></bindings><client><endpoint binding="customBinding"
                bindingConfiguration="CustomBinding_AuthService" contract="AuthService.AuthService"
                name="CustomBinding_AuthService" /></client></system.serviceModel></configuration>

And the error text is: (from Fiddler)

HTTP Error 500 - Internal Server Error<?xml version="1.0"?><error xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><exception>Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #EE5999FBDetail: &lt;OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts"&gt;&lt;ErrorCode&gt;-2147220970&lt;/ErrorCode&gt;&lt;ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" /&gt;&lt;Message&gt;System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #EE5999FB&lt;/Message&gt;&lt;Timestamp&gt;2013-05-29T06:40:56.383069Z&lt;/Timestamp&gt;&lt;InnerFault i:nil="true" /&gt;&lt;TraceText i:nil="true" /&gt;&lt;/OrganizationServiceFault&gt;</exception><parameters xsi:nil="true" /><displaytitle /><displaytextencoded /><displaytext /><description>CRM Parameter Filter - Invalid parameter 'V&#x2;&#xB;&#x1;s&#x4;&#xB;&#x1;a&#x6;V&#x8;D&#x1E;&#x0;??&#x14;urn:AuthService/TestD&#x1A;??w?/?%?C?m/&#x8;????D,D*?&#x14;&#x1;D&#xC;&#x1E;&#x0;??Vhttps://domain.crm4.dynamics.com/%7B635053590270003339%7D/WebResources/AuthService.svc&#x1;V&#xE;@&#x4;Test&#x1;&#x1;&#x1;' in Request.InputStream on page /Handlers/WebResource.ashx
The raw request was 'POST /{635053590270003339}/WebResources/AuthService.svc' called from https://domain.crm4.dynamics.com/%7B635053590270003339%7D/WebResources/new_spsl.</description><file>Not available</file><line>Not available</line><details>Not available</details><traceInfo /><requesturl>http://domain.crm4.dynamics.com:port/Handlers/WebResource.ashx?name=AuthService.svc</requesturl><pathAndQuery>/Handlers/WebResource.ashx?name=AuthService.svc</pathAndQuery><source>ASHX_XML</source><stacktrace /></error>

Does anybody has a good idea?

Thanks and regards,

Peter

Programmatically remove resources for Service Appointment

$
0
0

I am adding the resource to the SA in the following manner:

ActivityParty resParty = new ActivityParty();
resParty.PartyId = new EntityReference() { LogicalName = "systemuser", Id = appt.new_PhysicianAssigned.Id };

resParty.ActivityId = new EntityReference() { LogicalName = "serviceappointment", Id = appt.ActivityId };

resParty.ParticipationTypeMask = new OptionSetValue() { Value = 10 }; //resource

myContext.AddToActivityPartySet(resParty);
appt.serviceappointment_activity_parties.Add(resParty);
How would I remove all the resources and only the resources for a given Service Activity?



Cannot export solution from one organization to another

$
0
0

Hi,

We work with 2 organizations. One test and one production, the test is where we do all the work on an unmanaged solution. Than we export it managed and import on the production. This has worked without a problem so far. But when I tried it now I get the following error:

A managed solution cannot overwrite a {0} component on the target system that has an unmanaged base instance.  The most likely scenario for this error is that an unmanaged solution has installed a new unmanaged {0} component on the target system, and now a managed solution from the same publisher is trying to install that same {0} component as managed.  This will cause an invalid layering of solutions on the target system and is not allowed.

I assume this means something has changed on production and now can't be overwritten by the solution from the test environment. So I figured, no biggy, I'll just delete this from the test and try again. However the problem is it says that the issue is in Mappings, an Attribute map between quotedetail and salesorderdetail. These two have no relationship... So I went looking in the customization.xml and found the mapping.

Here I found this:

<EntityMap><EntitySource>quotedetail</EntitySource><EntityTarget>salesorderdetail</EntityTarget><AttributeMaps><AttributeMap><AttributeSource>ave_finishingid</AttributeSource><AttributeTarget>ave_finishingid</AttributeTarget></AttributeMap></AttributeMaps></EntityMap>

finishing is a custom entity, which does contain a 1:N relation to both entities. So I tried to delete these relationships but I simply can't. It keeps giving me the error:

Cannot Delete Component because one or more components require it. But there are no dependencies left on the relationships. I've deleted everything from forms, views, charts, even navigations... Still nothing when I select the relationship and click on show dependencies, it says there are none... I'm at a loss here on what to do.. I need to export the solution to production asap but am not allowed to edit the customization.xml, cause I figured I'ld just delete the entitymap there and it would work, which is probably true but also unsupported... Anyone have any ideas on what else I can do?? 

CRM 2011 Online - Silverlight/WCF alwasy get an error

$
0
0

Hello!

I have a SL 5 project.In the SilverlightApplication.Web I have a Silverlight-enabled WCF service, which connects to a Sharepoint and do something. (returns a byte[]) I use this as a Service Reference in my SilverlightApplication. On my local computer it works well, but not in CRM Online.

My web.config looks like this:

<?xml version="1.0"?><!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  --><configuration><configSections></configSections><system.web><compilation debug="true" targetFramework="4.0" /></system.web><system.serviceModel><serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/><behaviors><serviceBehaviors><behavior name=""><serviceMetadata httpsGetEnabled="true" /><serviceDebug includeExceptionDetailInFaults="true" /></behavior><behavior name=""><serviceMetadata httpGetEnabled="true" /><serviceDebug includeExceptionDetailInFaults="true" /></behavior><behavior name="DisableServiceCertificateValidation"><serviceCredentials><clientCertificate><authentication certificateValidationMode="None" revocationMode="NoCheck"/></clientCertificate></serviceCredentials></behavior></serviceBehaviors></behaviors><bindings><customBinding><binding name="SilverlightApplication4.Web.AuthService.customBinding0" ><binaryMessageEncoding  maxReadPoolSize="2147483647" maxSessionSize="2147483647" maxWritePoolSize="2147483647" /><httpsTransport maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="StreamedResponse" /></binding></customBinding></bindings><services><service name="SilverlightApplication4.Web.AuthService"><endpoint address="" binding="customBinding" bindingConfiguration="SilverlightApplication4.Web.AuthService.customBinding0"
            contract="SilverlightApplication4.Web.AuthService" /><endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" /></service></services><!--<behaviors><serviceBehaviors><behavior name=""><serviceMetadata httpGetEnabled="true" /><serviceDebug includeExceptionDetailInFaults="false" /></behavior></serviceBehaviors></behaviors>--><!--<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />--></system.serviceModel></configuration>


And my clientconfig:

<configuration><system.serviceModel><bindings><customBinding><binding name="CustomBinding_AuthService"><binaryMessageEncoding /><httpsTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="StreamedResponse"/></binding></customBinding></bindings><client><endpoint binding="customBinding"
                bindingConfiguration="CustomBinding_AuthService" contract="AuthService.AuthService"
                name="CustomBinding_AuthService" /></client></system.serviceModel></configuration>

And the error text is: (from Fiddler)

HTTP Error 500 - Internal Server Error<?xml version="1.0"?><error xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><exception>Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #EE5999FBDetail: &lt;OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts"&gt;&lt;ErrorCode&gt;-2147220970&lt;/ErrorCode&gt;&lt;ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" /&gt;&lt;Message&gt;System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #EE5999FB&lt;/Message&gt;&lt;Timestamp&gt;2013-05-29T06:40:56.383069Z&lt;/Timestamp&gt;&lt;InnerFault i:nil="true" /&gt;&lt;TraceText i:nil="true" /&gt;&lt;/OrganizationServiceFault&gt;</exception><parameters xsi:nil="true" /><displaytitle /><displaytextencoded /><displaytext /><description>CRM Parameter Filter - Invalid parameter 'V&#x2;&#xB;&#x1;s&#x4;&#xB;&#x1;a&#x6;V&#x8;D&#x1E;&#x0;??&#x14;urn:AuthService/TestD&#x1A;??w?/?%?C?m/&#x8;????D,D*?&#x14;&#x1;D&#xC;&#x1E;&#x0;??Vhttps://domain.crm4.dynamics.com/%7B635053590270003339%7D/WebResources/AuthService.svc&#x1;V&#xE;@&#x4;Test&#x1;&#x1;&#x1;' in Request.InputStream on page /Handlers/WebResource.ashx
The raw request was 'POST /{635053590270003339}/WebResources/AuthService.svc' called from https://domain.crm4.dynamics.com/%7B635053590270003339%7D/WebResources/new_spsl.</description><file>Not available</file><line>Not available</line><details>Not available</details><traceInfo /><requesturl>http://domain.crm4.dynamics.com:port/Handlers/WebResource.ashx?name=AuthService.svc</requesturl><pathAndQuery>/Handlers/WebResource.ashx?name=AuthService.svc</pathAndQuery><source>ASHX_XML</source><stacktrace /></error>

Does anybody has a good idea?

Thanks and regards,

Peter

How to I find the Contact icon when defaulting a partylist lookup to a Contact's view? [CRM 2011] [Jscript]

$
0
0

Per this post ( http://social.microsoft.com/Forums/en-US/b5c553b8-a90b-47f7-9191-4d825ecb9280/change-default-view-for-partylist-type-field ), I'm trying to set the default view of the Sender or Recipient lookups (depending on the Direction of the Phone Call) to Contacts. Outgoing calls are Phase 2 so I know I'll need to be able to set this to Users as well but I'm not going to worry about that for now.

Anyway, the snippet here works but the icon is for Accounts, not Contacts. Where can I find how to get the icon I need?

///////////////////////////////////////////////////////////////////////////////////////////////// function ToggleLookupViewtoContacts(){ var Direction = Xrm.Page.getAttribute('directioncode'); var Sender = Xrm.Page.getAttribute('from'); var Sender_field = Xrm.Page.getControl('from'); var Sender_style = document.getElementById('from'); /*var Recipient = Xrm.Page.getAttribute('to'); var Recipient_field = Xrm.Page.getControl('to'); var Recipient_style = document.getElementById('to'); */ if (Direction.getValue() == 0){ Sender_style.setAttribute('lookuptypes', '2'); Sender_style.setAttribute('lookuptypeicons', '/_imgs/ico_16_2.gif,/CRM2011/WebResources/xrm_icolist16,/CRM2011/WebResources/xrm_icocom16');

//^This isn't right apparently. Get a big old ugly red X. Sender_style.setAttribute('defaulttype', '2'); //Sender_field.setDefaultView('00000000-0000-0000-00AA-000010001003'); //From the linked post above. Defaults to the My Contacts view which I don't want. Sender_field.setDefaultView('A2D479C5-53E3-4C69-ADDD-802327E67A0D'); //The Contact lookup view for my Org }

}




returning target ID on crm 4 custom activity

$
0
0

I just want a simple custom workflow activity to return the accounted (guid value) so I can pass it to another activity like an email. this is the code that I am using . it is pretty simple but is not working

I need to run it "ON DEMAND", so, I would expect it would get at least the accountId of my selected record

the activity is appearing on the workflow wizard but when I use it, my workflow fails.

am I doing something wrong?

[CrmWorkflowActivity("Return accountid")]
    public partial class RetrieveContactIDActivity : Activity
    {

        public static DependencyProperty ResponseProperty = DependencyProperty.Register("Response", typeof(string), typeof(RetrieveContactIDActivity));
        [CrmOutput("ResponseId")]
        [CrmReferenceTarget("account")]
        public string Response
        {
            get
            {
                return (string)base.GetValue(ResponseProperty);
            }
            set
            {
                base.SetValue(ResponseProperty, value);
            }
        }
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {

            // Get the context service.
            IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
            IWorkflowContext context = contextService.Context;
            ICrmService crmService = context.CreateCrmService(true);

           
            try
            {

                if (context.InputParameters.Properties.Contains("Target") && context.InputParameters.Properties["Target"] is DynamicEntity)
                {
                    DynamicEntity entity = context.InputParameters.Properties["Target"] as DynamicEntity;

                    if (entity.Properties.Contains("contactid"))
                    {
                        Response = ((Key)entity.Properties["contactid"]).Value.ToString();

                    }
                    

                    if (entity.Properties.Contains("id"))
                    {
                        Response = ((Key)entity.Properties["contactid"]).Value.ToString();

                    }                    
                }
            }
            catch (SoapException ex)            {
               
                //logger.LogError(ex.Detail.InnerText);
            }
            catch (Exception ex)            {
                
                //logger.LogError(ex.Message);
            }

            return base.Execute(executionContext);
        }
    }

Call localhost endpoints on IFD deployment

$
0
0

We have a loadbalanced deployment with 3 front end servers. While processing async plugins we make calls out to other organizations on the same deployment, but the IFD url is load balanced (https://orgname.domain.com) thus causing a hit out to the loadbalancer and back (unnecessary). I would like to be able to make a call directly to the server the process is running on (http://localhost/orgname) however I run into a few issues:

1) When initializing the service the server redirects from http -> https so the resulting url is https://localhost/orgname, not a huge problem, except...

2) Causes invalid server certificate...

easy enough to get around

ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
{
	var request = sender as HttpWebRequest;
	return (request != null && (request.Host == "localhost" || request.Host == "127.0.0.1")) || sslPolicyErrors == SslPolicyErrors.None;
};

3) This is the show stopper, I receive an exception saying it cannot authenticate:

System.InvalidOperationException: The user authentication failed! 
   at Microsoft.Xrm.Sdk.ClientExceptionHelper.Assert(Boolean condition, String message) 
   at Microsoft.Xrm.Sdk.Client.ServiceProxy`1.AuthenticateCore() 
   at Microsoft.Xrm.Sdk.Client.ServiceProxy`1.ValidateAuthentication() 
   at Microsoft.Xrm.Sdk.Client.ServiceContextInitializer`1.Initialize(ServiceProxy`1 proxy) 
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceContextInitializer..ctor(OrganizationServiceProxy proxy) 
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request) 

So I can get around 1 and 2... anyone have any suggestions for #3?

One alternative is to resolve the local machine name and fqdn and use that, but I'd still like to see why I'm getting the Unable to authenticate. Below is the code to generate the service:

public IOrganizationService LocalHostOrganizationService(string orgUrlName, TimeSpan timeout, bool enableProxyTypes = true)
{
	var organizationUri = new Uri(string.Format(OrganizationServiceUrl(AuthenticationProviderType.ActiveDirectory), orgUrlName, "localhost"));

	var creds = new ClientCredentials();
	creds.Windows.ClientCredential = new NetworkCredential();
	creds.Windows.ClientCredential.UserName = _auth.Domain + "\\" + _auth.UserName;
	creds.Windows.ClientCredential.Password = _auth.Password;
	var serviceProxy = new OrganizationServiceProxy(organizationUri, null, creds, null);

	if (enableProxyTypes)
		serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
	serviceProxy.Timeout = timeout;
	return serviceProxy;
}

private string OrganizationServiceUrl(AuthenticationProviderType authType)
{
	var url = (_auth.UseSSL ? "https" : "http");
	switch (authType)
	{
		case (AuthenticationProviderType.ActiveDirectory):
			url += "://{1}/{0}/XRMServices/2011/Organization.svc";
			break;
		default:
			url += "://{0}.{1}/XRMServices/2011/Organization.svc";
			break;
	}
	return url;
}


Thank you in advance for your help. If you think you may be able to help with any of my unanswered threads please look at them here

Accessing the CRM lookup window from an external application

$
0
0

I have some nice JavaScript code that allows you to access the lookupinfo.aspx page when deploying a solution as an html web resource.  

var surl = "http://mycrmtest.crm.dynamics.com/_controls/lookup/lookupinfo.aspx?AllowFilterOff=1&DefaultType=2&DefaultViewId=%7bA2D479C5-53E3-4C69-ADDD-802327E67A0D%7d&DisableQuickFind=0&DisableViewPicker=0&LookupStyle=single&ShowNewButton=1&ShowPropButton=1&browse=0&objecttypes=2";
var oLookupItems = window.showModalDialog(surl, window, "dialogwidth: 450; dialogheight: 300; resizable: yes");
            if (oLookupItems != null) {
                if (oLookupItems.items.length > 0) {
                    var name = oLookupItems.items[0].name;
                    alert('name: ' + name);
                    document.getElementById('new_actionby').textContent = name;
                    var Id = oLookupItems.items[0].id;
                    Id = Id.replace("{", "");
                    Id = Id.replace("}", "");
                    alert('Id: ' + Id);
                }

I ran into a problem using this code when attempting to access it from an external .aspx page.  
The first issue I noticed was the inability to script across domains.  I found a solution that utilizes a local proxy:  http://www.sharepointjohn.com/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/
This solution works great when authentication is NOT involved, but does not work when authenticating to onPremise or online.  I even tried wrapping the proxy code in my OrganizationServiceProxy authentication, but that does not work.
Is there a way to authenticate to CRM when passing code via a proxy?
Is there a way to  legally script across domains?
Is there a better way to access the lookupinfo.aspx page when hosted on another domain?

Thank you for reading.

Linq exception occurs while retrieving paged crm data in a multihreaded manner

$
0
0

I try to read data from CRM 2011 in a paged and multithreaded manner with a Statement like this:

List<object> pageResult = new List<object>(xrm.CreateQuery("contact").Skip(i * pagesize).Take(pagesize));

Doing so i always get, after a few minutes, a "System.InvalidOperationException: Collection was modified; enumeration operation may not execute."
Exception (but the collection which is reportedly modified seems not to be the query it result itself as the stacktrace below indicates.
I have build a testcase to reproduce this but i do yet not know how to file a bug or where to upload the testacse. So maybe this Forum is the right place?


So here are the technical details:
Environment: Win 2008 Server R2, .NET 4.5, CRM SDK 5.0.16, CRM 2011 Update Rollup 14
The issue is always reproducible with this code

using Generated;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ReproduceBug
{
    class Program
    {

        /*
         * THIS IS BROKEN. After a few minutes you get this exception
      
        Environment: Win 2008 Server R2, .NET 4.5, CRM SDK 5.0.16, Update Rollup 14
  
 [Thread: 10] - Error with page 4 :: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
 at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
 at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
 at System.Collections.Generic.List`1.Enumerator.MoveNext()
 at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.CreateLocalChannelFactory()
 at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.CreateChannelFactory(ClientCredentials clientCredentials)
 at Microsoft.Xrm.Sdk.Client.OrganizationServiceConfiguration.CreateChannelFactory(ClientCredentials clientCredentials)
 at Microsoft.Xrm.Sdk.Client.ServiceProxy`1.get_ChannelFactory()
 at Microsoft.Xrm.Sdk.Client.ServiceProxy`1.CreateNewServiceChannel()
 at Microsoft.Xrm.Sdk.Client.ServiceProxy`1.ValidateAuthentication()
 at Microsoft.Xrm.Sdk.Client.ServiceContextInitializer`1.Initialize(ServiceProxy`1 proxy)
 at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
 at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest request)
 at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request)
 at Microsoft.Xrm.Sdk.Linq.QueryProvider.RetrieveEntityCollection(OrganizationRequest request, NavigationSource source)
 at Microsoft.Xrm.Sdk.Linq.QueryProvider.AdjustPagingInfo(OrganizationRequest request, QueryExpression qe, NavigationSource source, Boolean& moreRecordAfterAdjust)
 at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute(QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource sou
rce, List`1 linkLookups, String& pagingCookie, Boolean& moreRecords)
 at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, Navigation
Source source, List`1 linkLookups)
 at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression)
 at Microsoft.Xrm.Sdk.Linq.QueryProvider.GetEnumerator[TElement](Expression expression)
 at Microsoft.Xrm.Sdk.Linq.Query`1.GetEnumerator()
 at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
 at ReproduceBug.Program.<>c__DisplayClass3.<DoPagedQuery>b__1(Int32 i) in c:\Users\salyh\Documents\Visual Studio 2012\Projects\ReproduceBug\ReproduceBug\Program.cs:line 88
Page 0 with 643 records
Finised with 1 errors
        
        
   
      */

        static void Main(string[] args)
        {

            Console.WriteLine("Connecting to " + args[0]);

            IServiceManagement<IOrganizationService> orgServiceManagement =
                        ServiceConfigurationFactory.CreateManagement<IOrganizationService>(
                        new Uri(args[0]));

            AuthenticationCredentials creds = GetCredentials(orgServiceManagement.AuthenticationType, args.Length > 1 ? args[1] : null, args.Length > 2 ? args[2] : null);

            AuthenticationCredentials authCreds = orgServiceManagement.Authenticate(creds);

 

            int errCount = 0;


            do
            {
                errCount = DoPagedQuery(orgServiceManagement, authCreds);

            } while (errCount == 0);

            Console.WriteLine("Finised with "+errCount+" errors");


        }


        private static int DoPagedQuery(IServiceManagement<IOrganizationService> orgServiceManagement, AuthenticationCredentials authCreds)
        {


            int errCount = 0;

            const int pagesize = 5000;
            const int threads = 6;

            ParallelOptions opts = new ParallelOptions { MaxDegreeOfParallelism = threads };

            int startPage = 0;
            bool finished = false;


            bool isActiveDirectoryAuth = (orgServiceManagement.AuthenticationType == AuthenticationProviderType.ActiveDirectory);


            while (!finished)
            {

                Parallel.For(startPage, threads + startPage, opts, i =>
                {
                    try
                    {

                        OrganizationServiceProxy proxy;

                        if (isActiveDirectoryAuth)
                        {
                            proxy = new OrganizationServiceProxy(orgServiceManagement, authCreds.ClientCredentials);
                        }
                        else
                        {
                            proxy = new OrganizationServiceProxy(orgServiceManagement, authCreds.SecurityTokenResponse);
                        }

                        proxy.EnableProxyTypes();

                        using (var xrm = new XrmServiceContext(proxy))
                        {


                            List<object> pageResult = new List<object>(xrm.CreateQuery("contact").Skip(i * pagesize).Take(pagesize));

                            int count = pageResult.Count;

                            Console.WriteLine("Page " + i + " with " + count + " records");

                            if (count < pagesize)
                            {
                                finished = true;
                            }


                        }

                       

                        proxy = null;

                    }
                    catch (NotSupportedException e)
                    {
                        //ignore empty pages

                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(("[Thread: " + Thread.CurrentThread.ManagedThreadId + "] - Error with page "+ i + " :: " + e));
                        Interlocked.Increment(ref errCount);

                    }
                });


                startPage = startPage + threads;

            }

 

            return errCount;
        }

 

        private static AuthenticationCredentials GetCredentials(AuthenticationProviderType endpointType, string user, string password)
        {

            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            switch (endpointType)
            {
                case AuthenticationProviderType.ActiveDirectory:
                    if (!string.IsNullOrEmpty(user))
                    {
                        authCredentials.ClientCredentials.Windows.ClientCredential =
                            new System.Net.NetworkCredential(user.Split('\\')[1],
                                                             password,
                                                             user.Split('\\')[0]);
                    }
                    else
                    {
                        authCredentials.ClientCredentials.Windows.ClientCredential =
                            System.Net.CredentialCache.DefaultNetworkCredentials;
                    }
                    break;
                case AuthenticationProviderType.LiveId:
                    authCredentials.ClientCredentials.UserName.UserName = user;
                    authCredentials.ClientCredentials.UserName.Password = password;
                    //authCredentials.SupportingCredentials = new AuthenticationCredentials();
                    //authCredentials.SupportingCredentials.ClientCredentials =
                    //Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
                    break;
                default: // For Federated and OnlineFederated environments.                   
                    authCredentials.ClientCredentials.UserName.UserName = user;
                    authCredentials.ClientCredentials.UserName.Password = password;
                    // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password.
                    // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName;  //Windows/Kerberos
                    break;
            }

            return authCredentials;
        }
    }
}

 

 

 

 

 


How to access discovery.svc service, if it needs authorisation (MS Forefront)?

$
0
0

I have an URL like https://crm.xxxx.com/XRMServices/2011/Discovery.svc and I want to discover an organisation with my client. But if I open this URL in a browser window, I will get an authorisation screen:

I get an exception, If I try to add this url on client to following method as parameter "url":  

ServiceConfigurationFactory.CreateManagement<T>(new Uri(url));

Exception:  Metadata contains a reference that cannot be resolved: "https://crm.xxxx.com/XRMServices/2011/Discovery.svc?wsdl".

or

Exception:  Metadata contains a reference that cannot be resolved: "https://crm.xxxx.com/XRMServices/2011/Organisation.svc?wsdl".


How to pass through this authentication?




CRM 2011 Getting System.TypeLoadException after plugin build

$
0
0

Hi!

Fixed an error in a plugin 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


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.

xpathevaluator' is undefined

$
0
0

I got error on this line... (IE10)

var result = window.showModalDialog(Xrm.Page.context.getServerUrl() + "/WebResources/ser_constituentdialog", obj, 'dialogWidth=380px,dialogHeight=380px,resizable:yes');

Full description is attach below.

Custom Import Application creating Import System Job - Records are not imported & Job Status Failed

$
0
0

Hi,

I have created a console application intended to read a XML data file and create records in CRM.

1. I have defined a Data map in crm and retrieving it in the code and passing it.

2. The code executes without any error.

3. Creates a Import Job record in CRM

4. Initially it shows status parsing and also shows total record count.

5. Next it shows Failed status. But when I opened Import record, it didn't have any failures & the System jobs were successful as well. 

I am not sure what am I missing here. Please have a look at the code and let me know what is the issue in it.

Thanks in advance,

Danny

static void Main(string[] args)
        {
            // Load the xml spreasheet file from your local drive using XmlDocument class
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(@"C:\Customer.xml");

            IOrganizationService service = createService();

            // Create the Import
            Entity import = new Entity("import");
            import.Attributes.Add("modecode", new OptionSetValue(0));
            import.Attributes.Add("name", "CustomEntityDataImport");
            import.Attributes.Add("sendnotification", false);
            Guid importId = service.Create(import);

            // Get the Guid of the DataMap by using the datamap name
            QueryExpression custDataMap = new QueryExpression("importmap");
            ConditionExpression cond1 = new ConditionExpression("name", ConditionOperator.Equal, "CustomerDataMap");
            FilterExpression filter1 = new FilterExpression(LogicalOperator.And);
            filter1.AddCondition(cond1);
            custDataMap.Criteria.AddFilter(filter1);
            custDataMap.ColumnSet = new ColumnSet(new string[] { "name" });
            EntityCollection custDataMaps = service.RetrieveMultiple(custDataMap);
            Entity dataMap = new Entity("importmap");
            if (custDataMaps.Entities.Count > 0)
            {
                dataMap = custDataMaps[0];           
                Entity importFile = new Entity("importfile");
                importFile.Attributes.Add("content", xmldoc.InnerXml);
                importFile.Attributes.Add("name", "CustomEntityDataImport");
                importFile.Attributes.Add("filetypecode", new OptionSetValue(1));
                importFile.Attributes.Add("isfirstrowheader", true);
                importFile.Attributes.Add("source", Path.GetFileName("CustomEntityDataImport.xml"));
                importFile.Attributes.Add("sourceentityname", "xrm_customer");
                importFile.Attributes.Add("targetentityname", "xrm_customer");
                importFile.Attributes.Add("importmapid", new EntityReference("import", dataMap.Id));
                importFile.Attributes.Add("importid", new EntityReference("import", importId));
                importFile.Attributes.Add("size", importFile["content"].ToString().Length.ToString());
                importFile.Attributes.Add("processcode", new OptionSetValue(1));
                importFile.Attributes.Add("usesystemmap", false);
                importFile.Attributes.Add("enableduplicatedetection", true);
                service.Create(importFile);

                ParseImportRequest parseRequest = new ParseImportRequest();
                parseRequest.ImportId = importId;
                service.Execute(parseRequest);
                TransformImportRequest transRequest = new TransformImportRequest();
                transRequest.ImportId = importId;
                TransformImportResponse transResponse = (TransformImportResponse)service.Execute(transRequest);
                ImportRecordsImportRequest request = new ImportRecordsImportRequest();
                request.ImportId = importId;
                ImportRecordsImportResponse response = (ImportRecordsImportResponse)service.Execute(request);
            }
        }


Danny



Viewing all 465 articles
Browse latest View live


Latest Images

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